text
stringlengths
15
59.8k
meta
dict
Q: How do I import a sprite sheet with its JSON file into my phaser game? I am creating a game using the phaser game engine. I created a sprite sheet and downloaded it. It came with the 256 × 384 .png file with my frames and a JSON file which I assume contains information about how to split up the frames. I don't know how to import the sprite sheet with the JSON file into my preload() function. I tried using the following code but it is not working. Any help would be greatly appreciated. var game = new Phaser.Game(1200, 750, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload(){ game.load.image('background', 'assets2/background.png'); game.load.json('robot', 'assets2/VillainSpriteSheet_json.json'); game.load.spritesheet('robot', 'assets2/VillainSpriteSheet.png'); } var villain; function create(){ var villainjson = game.cache.getJSON('robot'); //enable physics game.physics.startSystem(Phaser.Physics.ARCADE); //create background var background = game.add.sprite(0, 0, 'background'); //villain villain = game.add.sprite(50, 50, 'robot'); //enable phsyics game.physics.arcade.enable(villain); villain.body.bounce.y = .2; villain.body.gravity.y = 300; villain.body.collideWorldBounds = true; } A: I think you are confusing two frameworks, jQuery and Phaser. For loading and displaying sprites you don't need jQuery, just Phaser will do. The load.spritesheet expects a spritesheet where all sprites have a fixed width and height, so with all sprites in a grid layout. What you have sounds like a spriteatlas, the difference being that in a spriteatlas each sprite can have a different width and height, and all these widths and heights per sprite are described in the accompanying .JSON file. So I think you are looking for the load.atlasJSONHash function, something like this: function preload(){ //.. game.load.atlasJSONHash('robot', 'assets2/VillainSpriteSheet.png', 'assets2/VillainSpriteSheet_json.json'); // and then load a sprite like so // Note: 'myframename1' should be some framename from the .json file var villain = game.add.sprite(50, 50, 'robot', 'myframename1'); And btw just to clarify, the load.json in Phaser can be used to just load a .json file, for example with for your own customised data like level layouts, dialog/multilanguage texts, highscore data, enemy patterns etc. A: You don't want jQuery's getJSON(). You want the Phaser one. It would be something like p = new Phaser.Game(...); p.cache.getJSON('foo'); p.load.image(...);
{ "language": "en", "url": "https://stackoverflow.com/questions/42311723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to sum up minutes and seconds ?in oracle I have a column called duration_d which is varchar2 and the data in that table looks like below duration_d ----------- 12:25 01:35 12:10 04:21 12:18 12:24 I tried below query SELECT SUM( to_date( duration_d, 'mi:ss' )) FROM table GROUP BY calling_number; When I execute it following error is coming ORA-00933: SQL command not properly ended 00933. 00000 - "SQL command not properly ended" can any one tell me how to make sum it? A: To get the total as fractions of a day you can use: SELECT SUM( TO_DATE( duration_d, 'MI:SS' ) - TO_DATE( '00:00', 'MI:SS' ) ) AS total FROM your_table Which gives the result: TOTAL ------------------------------------------ 0.0383449074074074074074074074074074074074 To convert this to an interval data type you can use NUMTODSINTERVAL: SELECT NUMTODSINTERVAL( SUM( TO_DATE( duration_d, 'MI:SS' ) - TO_DATE( '00:00', 'MI:SS' ) ), 'DAY' ) AS total FROM your_table Which gives the result: TOTAL ------------------- +00 00:55:13.000000 A: Please try below: with x as (select sum((regexp_substr(YOUR_COLUMN, '[0-9]+', 1, 1)*60) + regexp_substr(id, '[0-9]+', 1, 2)) seconds from YOUR_TABLE) SELECT TO_CHAR(TRUNC(seconds/3600),'FM9900') || ':' || TO_CHAR(TRUNC(MOD(seconds,3600)/60),'FM00') || ':' || TO_CHAR(MOD(seconds,60),'FM00') FROM x Will work only if the duration is always [MI:SS]. Also you can add the group by as per your requirement. Converting Seconds to the required duration format Reference. Group By with x as (select calling_number,sum((regexp_substr(YOUR_COLUMN, '[0-9]+', 1, 1)*60) + regexp_substr(id, '[0-9]+', 1, 2)) seconds from YOUR_TABLE group by calling_number) SELECT calling_number, TO_CHAR(TRUNC(seconds/3600),'FM9900') || ':' || TO_CHAR(TRUNC(MOD(seconds,3600)/60),'FM00') || ':' || TO_CHAR(MOD(seconds,60),'FM00') FROM x A: Use a combination of SUBSTR, to_char, to_date, NVL, INSTR, reverse and SUM. SELECT "calling_number", to_char(to_date(SUM(NVL(SUBSTR("duration_d", 0, INSTR("duration_d", ':')-1), "duration_d"))*60 + SUM(substr("duration_d", - instr(reverse("duration_d"), ':') + 1)),'sssss'),'hh24:mi:ss') AS SUM_DURATION_D FROM yourtable GROUP BY "calling_number" Output calling_number SUM_DURATION_D 1 00:26:10 2 00:29:03 SQL Fiddle: http://sqlfiddle.com/#!4/9b0a81/33/0 A: Correct spelling as below SELECT SUM( TO_DATE( duration_d, 'mi:ss' ) ) FROM YOURTABLE Group By calling_number
{ "language": "en", "url": "https://stackoverflow.com/questions/45478614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP:checked attribute in array of checkboxes I have an array like this $current_asset = [ ['name'=>'Land,'id'=>1], ['name'=>'Building ,'id'=>2], ['name'=>'Machinery','id'=>3], ]; <?php foreach($current_asset as $key=>$value){ ?> <input type="checkbox" name="current_asset[]" value="<?php echo $value['id'] ?>"> <?php } ?> My question how can I add checked attribute in if one of the value is checked when the form populated with the POST data I am getting the checkbox array like this on form submit Here are the current checkboxes on form submit (ie values of current_asset) Array( 0=>1 1=>1 ) A: You would need to do some kind of check before printing $html=‘’; foreach($current_asset as $asset) { if($asset[‘hasBeenCheckedBefore’]) { $checked = ‘checked’; } else { $checked = ‘’; } $html .= “$asset[‘name’] <input type=‘checkbox’ name=‘current_asset[]’ value=‘$asset[“id”]’ $checked />”; } A: Here is an example of one way to do it. I have changed your data structure to be easier to use. I was confused initially because you didn't mention any way to store data. So this is only good for the one page view. <?php // initialize data /** * Data structure can make the job easy or hard... * * This is doable with array_search() and array_column(), * but your indexes might get all wonky. */ $current_asset = [ ['name'=>'Land','id'=>1], ['name'=>'Building' ,'id'=>2], ['name'=>'Machinery','id'=>3], ]; /** * Could use the key as the ID. Note that it is being * assigned as a string to make it associative. */ $current_asset = [ '1'=>'Land', '2'=>'Building', '3'=>'Machinery', ]; /** * If you have more information, you could include it * as an array. I am using this setup. */ $current_asset = [ '1'=> ['name' => 'Land', 'checked'=>false], '2'=> ['name' => 'Building', 'checked'=>false], '3'=> ['name' => 'Machinery', 'checked'=>false], ]; // test for post submission, set checked as appropriate if(array_key_exists('current_asset', $_POST)) { foreach($_POST['current_asset'] as $key => $value) { if(array_key_exists($key,$current_asset)) { $current_asset[$key]['checked'] = true; } } } // begin HTML output ?> <html> <head> <title></title> </head> <body> <!-- content .... --> <form method="post"> <?php foreach($current_asset as $key=>$value): ?> <?php $checked = $value['checked'] ? ' checked' : ''; ?> <label> <input type="checkbox" name="current_asset[<?= $key ?>]" value="<?= $key ?>"<?= $checked ?>> <?= htmlentities($value['name']) ?> </label> <?php endforeach; ?> </form> <body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/50545173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vbox Parent, Pane Child overlapping other components javafx Hey all I am new to java and javafx trying to learn them. I am currently trying to do a problem where the user inputs values for two circles (the center and radius of circle). It is supposed to then show the circles, and display what they are doing, such as they are equal, one is contained in the other, etc. To do this I used a vbox, and I am attempting to draw the circles using a pane, and implementing the pane into the vbox. Here is my code: public class Shapes extends Application { @Override public void start(Stage stage) { createTextField(); VBox root = new VBox(); root.setSpacing(10); Pane pane = new Pane(); Color blue = new Color(1,0,0,1); Color red = new Color(0,0,1,1); Circle circle1 = createCircle(50, 50, 50, red); Circle circle2 = createCircle(50, 50, 200, blue); pane.getChildren().addAll(circle1, circle2); root.getChildren().addAll(label0, label1, label2, tField, label3, label4, pane); Scene scene = new Scene(root, 1000 , 1000); stage.setTitle("Spatial Relations Demo by"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } Label label0, label1, label2, label3, label4; TextField tField; public void createTextField() { label0 = new Label(); label0.setText("Spatial Relations Demo"); label1 = new Label(); label1.setText(" "); label1.setTextAlignment(TextAlignment.CENTER); label2 = new Label(); label2.setText("Input Circles: x1 y1 r1 x2 y2 r2 "); label2.setTextAlignment(TextAlignment.CENTER); label3 = new Label(); label3.setTextAlignment(TextAlignment.CENTER); label4 = new Label(); label4.setTextAlignment(TextAlignment.CENTER); tField = new TextField(); tField.setOnAction(new TextFieldHandler()); } public class TextFieldHandler implements EventHandler<ActionEvent> { public void handle( ActionEvent e) { String str = tField.getText(); int x1, y1, r1, x2, y2, r2; Scanner scanner = new Scanner(str); x1 = scanner.nextInt(); y1 = scanner.nextInt(); r1 = scanner.nextInt(); x2 = scanner.nextInt(); y2 = scanner.nextInt(); r2 = scanner.nextInt(); tField.setText( "" ); String str1 = str.format("Input is: " + x1 + " " + y1 + " " + r1 + " " + x2 + " " + y2 + " " + r2); label3.setText(str1); double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); if ((x1==x2) & (y1==y2) & (r1==r2)) label4.setText( " The circles are equal."); else if (d >= (r1+r2)) label4.setText( " The circle interiors are disjoint."); else if (d <= (r2-r1)) label4.setText( " Circle1 is inside Circle2."); else if (d <= (r1-r2)) label4.setText( " Circle2 is inside Circle1."); else label4.setText( " The circles overlap."); } } public Circle createCircle(int x, int y, int r, Color color) { Circle circle = new Circle(); circle.setRadius(r); circle.setCenterX(x); circle.setCenterY(y); circle.setStroke(color); circle.setFill(null); return circle; } } As of right now I just have implemented some test numbers to draw the circles, but I am still trying to figure out how to get the user inputted numbers as my circle parameters. I was not sure how to get the pane to work properly. Any tips or advice would be greatly appreciated thanks! I tried to post an image to show my output but I guess I dont have enough reputation for it. My circles are overlapping everything instead of staying below the labels and textfield. I cant seem to figure out how to keep them below those items in the vbox. A: Your red circle (the one with the color you called blue ;) ) has bounds that extend into negative coordinate ranges in both x- and y-directions (it has center (50, 50) and radius 200). Hence it extends beyond the bounds of the pane. If you want to make sure the pane doesn't paint outside of its bounds, you can set a clip that is bound to its size: Rectangle clip = new Rectangle(0, 0, 0, 0); clip.widthProperty().bind(pane.widthProperty()); clip.heightProperty().bind(pane.heightProperty()); pane.setClip(clip); To update the circles, you just have to make them instance variables instead of local to the start method, and update their centers and radii: import java.util.Scanner; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.TextAlignment; import javafx.stage.Stage; public class Shapes extends Application { private Label label0, label1, label2, label3, label4; private TextField tField; private Circle circle1 ; private Circle circle2 ; @Override public void start(Stage stage) { createTextField(); VBox root = new VBox(); root.setSpacing(10); Pane pane = new Pane(); Color blue = new Color(1, 0, 0, 1); Color red = new Color(0, 0, 1, 1); circle1 = createCircle(50, 50, 50, red); circle2 = createCircle(50, 50, 200, blue); pane.getChildren().addAll(circle1, circle2); // If desired: // Rectangle clip = new Rectangle(0, 0, 0, 0); // clip.widthProperty().bind(pane.widthProperty()); // clip.heightProperty().bind(pane.heightProperty()); // pane.setClip(clip); root.getChildren().addAll(label0, label1, label2, tField, label3, label4, pane); Scene scene = new Scene(root, 1000, 1000); stage.setTitle("Spatial Relations Demo by"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } public void createTextField() { label0 = new Label(); label0.setText("Spatial Relations Demo"); label1 = new Label(); label1.setText(" "); label1.setTextAlignment(TextAlignment.CENTER); label2 = new Label(); label2.setText("Input Circles: x1 y1 r1 x2 y2 r2 "); label2.setTextAlignment(TextAlignment.CENTER); label3 = new Label(); label3.setTextAlignment(TextAlignment.CENTER); label4 = new Label(); label4.setTextAlignment(TextAlignment.CENTER); tField = new TextField(); tField.setOnAction(new TextFieldHandler()); } public class TextFieldHandler implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { String str = tField.getText(); int x1, y1, r1, x2, y2, r2; Scanner scanner = new Scanner(str); x1 = scanner.nextInt(); y1 = scanner.nextInt(); r1 = scanner.nextInt(); x2 = scanner.nextInt(); y2 = scanner.nextInt(); r2 = scanner.nextInt(); circle1.setCenterX(x1); circle1.setCenterY(y1); circle1.setRadius(r1); circle2.setCenterX(x2); circle2.setCenterY(y2); circle2.setRadius(r2); tField.setText(""); String str1 = String.format("Input is: " + x1 + " " + y1 + " " + r1 + " " + x2 + " " + y2 + " " + r2); label3.setText(str1); double d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if ((x1 == x2) & (y1 == y2) & (r1 == r2)) label4.setText(" The circles are equal."); else if (d >= (r1 + r2)) label4.setText(" The circle interiors are disjoint."); else if (d <= (r2 - r1)) label4.setText(" Circle1 is inside Circle2."); else if (d <= (r1 - r2)) label4.setText(" Circle2 is inside Circle1."); else label4.setText(" The circles overlap."); scanner.close(); } } public Circle createCircle(int x, int y, int r, Color color) { Circle circle = new Circle(); circle.setRadius(r); circle.setCenterX(x); circle.setCenterY(y); circle.setStroke(color); circle.setFill(null); return circle; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/32958310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting ongoing recording data segments from AVAudioRecorder My problem is as follows: I need to capture every 320 bytes of raw audio data. I do this by using an NSTimer that fires a method every 0.02 seconds - that is because i need to record 8000Hz and 16bit mono audio, and i've calculated that it should be 50x a second (8000 * 16 / 320 / 8). So, knowing that the AVAudioRecorder saves to a file, i can get every 320 bytes from that file by [[NSData dataWithContentsOfURL:[audioRecorder url]] subdataWithRange:NSMakeRange(bytesUsed, 320)], but the thing that has confused me, is that the moment i start the recording, the data files size is 4096 bytes and then after 0.5 seconds, it's 9424 bytes and increases by around 5,3k bytes every half a second. So i'm confused if i'm getting the right data and thinking that the settings might be wrong. Current settings for AVAudioRecorder are: [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey, [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey, [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey, [NSNumber numberWithInt:16], AVEncoderBitRateKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithFloat:8000.0], AVSampleRateKey, So the main problem is: What settings should i use? Is this the right way to go about getting segments from an ongoing audio recording? I apologize for the bad explanation, do ask questions to help me make it more understandable.
{ "language": "en", "url": "https://stackoverflow.com/questions/9531803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding an HTTP bottleneck I'm developing a custom Blog application in Ruby on Rails, having load speed as a primary measure of success. I'm caching (with Redis) both views and models to shorten up queries and rendering of raw HTML. Finally I succeeded loading a single post in under 15ms. Time to deploy. I bought a Linode 20$/month machine with 2gb ram, 2 cores, ssd storage, 40gbit in, 250mbit out. The machine is hosted in London. I installed Ubuntu 15.04. I set up Cloudflare free plan for more aggressive caching and minification of assets. I enabled the Full SSL functionality. I installed nginx as a proxy to the Rails application running on Unicorn. Rails, Redis, PostgreSQL and nginx run on the same server. I am in Rome, Italy. The nearest Cloudflare datacenter is in Milan, while the origin Linode server is in London. The average request time (as reported by the chrome network panel) is 230ms. Whops... So first of all I checked out the Rails logs, and the log reported times (and the X-Runtime header) where consistent with my development data (< 20ms). I edited nginx configuration to add an X-Time header: add_header X-Time $request_time; And that shows just a few ms over the Rails timings. Then I enabled direct access to the server (disabled Cloudflare) and disabled SSL to remove the handshake overhead. So I finally found that with or without Cloudflare, with or without SSL, load times where always quite random in the range [180-350]ms, with no apparent explaination. Here's a shot of the Chrome timing panel, without both Cloudflare and SSL. Just a raw HTTP connection directly on port 80 of the nginx server. Why am I seeing such high times on a blazing fast application? What should I check next? Is the Linode server my bottleneck? Thanks Edit It looks like gzip compression as enabled by default by nginx was slowing the whole thing down by a 30%. I have now disabled it since Cloudflare will gzip it anyway in a second step. Now request times are between 120 and 200ms but I still feel like it could be improved.
{ "language": "en", "url": "https://stackoverflow.com/questions/30413631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Way to slice a string using 2 variable? I m new to programming and came across a question If I have a string where I have 2 variables indexed.. and need the value from the middle. for example, my string is HeyEveryoneImtryingtolearnpythonandihavequestion where I have variables V1 = 'Imtrying' V2 = 'andihave' what can I do to get the "learnpython" substring? or is it not valid? A: You can use index and slicing: s = 'HeyEveryoneImtryingtolearnpythonandihavequestion' v1 = 'Imtrying' v2 = 'andihave' start = s.index(v1) + len(v1) end = s.index(v2, start) output = s[start:end] print(output) # tolearnpython A: You can also use regex: import re s = "HeyEveryoneImtryingtolearnpythonandihavequestion" V1 = 'Imtryingto' V2 = 'andihave' a = re.search(f"{re.escape(V1)}(.*?){re.escape(V2)}", s).group(1) # 'learnpython'
{ "language": "en", "url": "https://stackoverflow.com/questions/70514079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Symfony: Overriding Symfony service ( compiler pass ) I'm on symfony 2.7 and need to override Symfony\Component\Asset\UrlPackage I've looked at http://symfony.com/doc/current/cookbook/bundles/override.html and http://symfony.com/doc/current/cookbook/service_container/compiler_passes.html but can't get it working. I have made a file in my bundle MyApp\CoreBundle\Overrides\UrlPackage; I registered UrlPackage as a service and added a function: public function process(ContainerBuilder $container) { $definition = $container->getDefinition('assets.url_package'); $definition->setClass('MyApp\CoreBundle\Overrides\UrlPackage'); } The weird thing is, if I call $this->has('assets.url_package') in any controller, it returns false. I did grab it from the services file under Symfony: <service id="assets.url_package" class="Symfony\Component\Asset\UrlPackage" abstract="true"> <argument /> <!-- base URLs --> <argument type="service" /> <!-- version strategy --> <argument type="service" id="assets.context" /> </service> If I run php app/console debug:container, the UrlPackage from symfony isn't in there, but, if I change something inside the vendor/*/UrlPackge file, it does work Can someone point me in the right direction? A: Decorating the service is the thing you're looking for: bar: public: false class: stdClass decorates: foo arguments: ["@bar.inner"] You can inject the original service in your own service, and implement the original interface to make them compatible. http://symfony.com/doc/2.7/service_container/service_decoration.html A: Symfony 5.1+ Symfony 5.1+ provide a simpler service decoration: In previous Symfony versions you needed to use the syntax decorating service ID + .inner to refer to that service. This quickly becomes cumbersome in YAML/XML when using PHP classes as service IDs. That's why in Symfony 5.1 we've simplified this feature to always use .inner to refer to the original service. @source: https://symfony.com/blog/new-in-symfony-5-1-simpler-service-decoration # config/services.yaml services: App\MyService: ~ # Before App\SpecialMyService: decorates: App\MyService arguments: ['@App\SpecialMyService.inner'] # After App\SpecialMyService: decorates: App\MyService arguments: ['@.inner'] # <--- the service ID is no longer needed
{ "language": "en", "url": "https://stackoverflow.com/questions/31511019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: C++ - Are there ways to get current class type with invariant syntax? I want to write a macro which, when expanded within a class, uses that class type (specifically, as template argument). Within class method, I can use this: #define METHOD_MACRO int sample_method(void)const {\ return template_struct<this_type<decltype(this)>::type>::index;} (this_type is my struct, here it's equivalent to remove_pointer<remove_const<T>>) But when I need class type outside of method (for typedef for class member pointer), this keyword isn't available; I've tried to use auto for some trick with deducing type, but no luck here. Classes in question are inherited from my class, if this can be of any help. I would like to avoid anyone using my macro having to write obligatory typdedef. Any ideas? A: You can use the following trick: #define SELF \ static auto helper() -> std::remove_reference<decltype(*this)>::type; \ typedef decltype(helper()) self struct A { SELF; }; I declare a helper function using the auto return type, which allows me to use decltype(*this) as a return type, not knowing what is the class name. Then I can use decltype(helper()) to use the class type in the code. Note that the function has to be static, otherwise you can not use it in decltype. Also the function is just declared, not defined; this should not be a problem as you are not going to call it anyway. (You can add an empty body to it, but it will raise a warning that a function has no return. Still you may change the return type to be decltype(this) and return nullptr.) You may then use the self typedef for further declarations, or just alter the macros to typedef not the class itself, but what you need to. Adjust it to suit your particular need. UPD: This seems to be a non-standard behavior of GCC. For example, ICC does not allow this in static functions even in trailing return type.
{ "language": "en", "url": "https://stackoverflow.com/questions/33230665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: add icon to wpform submit button hi i want to make the form button same like in the image. the link of the form is this http://ministerievanlicht.com/contact/ the code is this that will get the button same to same but it not worked. .button { margin: 0 auto; text-decoration:none; text-align:center; display: flex; background: #333333; color: white; justify-content: space-between; align-items: center; pointer-events:none; max-width:660px; border-bottom:solid gray 1px font-family: DIN pro; font-weight: bold; } .button .fa { padding:1em; pointer-events:auto; width:1.5em; } .button::before { content: ''; padding: 1em } and here is the custom css is this i want to add icon at the end of the button div.wpforms-container-full .wpforms-form input[type=date], div.wpforms-container-full .wpforms-form input[type=datetime], div.wpforms-container-full .wpforms-form input[type=datetime-local], div.wpforms-container-full .wpforms-form input[type=email], div.wpforms-container-full .wpforms-form input[type=month], div.wpforms-container-full .wpforms-form input[type=number], div.wpforms-container-full .wpforms-form input[type=password], div.wpforms-container-full .wpforms-form input[type=range], div.wpforms-container-full .wpforms-form input[type=search], div.wpforms-container-full .wpforms-form input[type=tel], div.wpforms-container-full .wpforms-form input[type=text], div.wpforms-container-full .wpforms-form input[type=time], div.wpforms-container-full .wpforms-form input[type=url], div.wpforms-container-full .wpforms-form input[type=week], div.wpforms-container-full .wpforms-form select, div.wpforms-container-full .wpforms-form textarea { padding: 18px 0px 18px 26px; } div.wpforms-container-full .wpforms-form .wpforms-field-label { font-family: 'DIN PRO'; font-style: normal; font-weight: normal; font-size: 12px; line-height: 24px; color: #333333; opacity: 1.0; } div.wpforms-container div.wpforms-uploader { width: 330px; height: 193px; } div.wpforms-container-full .wpforms-form input[type=checkbox], div.wpforms-container-full .wpforms-form input[type=radio] { width: 21px; height: 21px; } div.wpforms-container-full .wpforms-form input[type=submit], div.wpforms-container-full .wpforms-form button[type=submit], div.wpforms-container-full .wpforms-form .wpforms-page-button { background-color: #eee; border: 1px solid #ddd; color: #333; font-size: 1em; padding: 10px 330px; text-decoration: none; text-align: center; display: flex; background: #333333; color: white; justify-content: space-between; align-items: center; pointer-events: none; width: 660px; height: 55px; border-bottom: solid gray 1px; font-family: DIN pro; font-weight: bold; } A: I have prepared two icon buttons for you. One works with a hover and the other without a hover. .btn { background-color: #333333; border: none; color: white; padding: 12px 16px; font-size: 16px; cursor: pointer; height: 60px; margin: 10px; position: relative; width: 660px; border-bottom: solid gray 1px } /* Darker background on mouse-over */ .btn:hover { background-color: #444444; } .btn .ic-line { width: 1px; height: 60px; background: #ddd; float: right; position: absolute; right: 60px; top: 0; } .fa-custom { float: right; position: absolute; right: 20px; top: 22px; font-size: 1.1rem; color: #fff; } .btn .ic-line1 { width: 1px; height: 60px; background: #ddd; float: right; position: absolute; right: 60px; top: 0; visibility: hidden; } .fa-custom1 { float: right; position: absolute; right: 20px; top: 22px; font-size: 1.1rem; visibility: hidden; color: #fff; } .btn:hover .ic-line1 { visibility: visible; } .btn:hover .fa-custom1 { visibility: visible; } <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <h2>Icon Buttons</h2> <p>Icon buttons:</p> <button class="btn"><i class="fa fa-arrow-right fa-custom"></i><i class="ic-line"></i>Send</button> <h2>Icon Buttons When hover</h2> <p>Icon buttons:</p> <button class="btn"><i class="fa fa-arrow-right fa-custom1"></i><i class="ic-line1"></i>Send</button>
{ "language": "en", "url": "https://stackoverflow.com/questions/66368799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add my output from a "FOR" Loop and sum together I am a beginner, so I want to ask that how to sum my "FOR" loop value from my input form? and the GrandTotal is used to change it "readonly" textbox in my form. let grandTotal = 0; for(let i = 1; i <= 5; ++i) { grandTotal += parseInt(document.getElementById("Total" + i).value); } grandTotal = document.getElementById("GrandTotal").value; This is one part of my HTML\ <tr id="One"> <td style="font-family: papyrus;font-weight: bold;">1</td> <td width="20%"><input type="text" id="BookTitle" name="BookTitle" size="30" ></td> <td width="17%"><input type="text" id="Author" name="Author" size="10"></td> <td width="20%"><select id="Category" name="Category"> <option value="Please choose the categoty...">Please choose the Category...</option> <option value="Business">Business</option> <option value="Fiction">Fiction</option> <option value="Mathematics">Mathematics</option> <option value="Technology">Technology</option> </select></td> <td width="13%"><input type="text" class="UnitPrice" id="UnitPrice1" name="Unit Price" step="0.01" value="0.00" placeholder="0.00" onkeypress="return forNumberOnly(event)"></td> <td width="13%"><input type="text" class="Quantity" id="Quantity1" name="Quantity" value="0" min="0" onkeypress="return forNumberOnly(event)"></td> <td width="13%"><input type="text" id="Total1" name="Total" value="0.00" readonly></td> </tr> A: Have a look at this - I use the selector [name=Total] because it makes more sense than [id^=Total] I delegate the change to the tbody: document.getElementById("tb").addEventListener("change", function(e) { const tgt = e.target; const parent = tgt.closest("tr"); const up = +parent.querySelector(".UnitPrice").value || 0 const qty = +parent.querySelector(".Quantity").value || 0 parent.querySelector("[name=Total]").value = (up * qty).toFixed(2); const grandTotal = [...document.querySelectorAll("[name=Total]")] // all total .map(ele => +ele.value) // get each value and convert to number .reduce((a, b) => a + b); // sum them document.getElementById("GrandTotal").value = grandTotal; // assign to a field }) <table> <tbody id="tb"> <tr id="One"> <td style="font-family: papyrus;font-weight: bold;">1</td> <td width="20%"><input type="text" id="BookTitle" name="BookTitle" size="30"></td> <td width="17%"><input type="text" id="Author" name="Author" size="10"></td> <td width="20%"> <select id="Category" name="Category"> <option value="Please choose the categoty...">Please choose the Category...</option> <option value="Business">Business</option> <option value="Fiction">Fiction</option> <option value="Mathematics">Mathematics</option> <option value="Technology">Technology</option> </select> </td> <td width="13%"><input type="text" class="UnitPrice" id="UnitPrice1" name="Unit Price" step="0.01" value="0.00" placeholder="0.00"></td> <td width="13%"><input type="text" class="Quantity" id="Quantity1" name="Quantity" value="0" min="0"></td> <td width="13%"><input type="text" id="Total1" name="Total" value="0.00" readonly></td> </tr> <tr id="Two"> <td style="font-family: papyrus;font-weight: bold;">1</td> <td width="20%"><input type="text" id="BookTitle" name="BookTitle" size="30"></td> <td width="17%"><input type="text" id="Author" name="Author" size="10"></td> <td width="20%"> <select id="Category" name="Category"> <option value="Please choose the categoty...">Please choose the Category...</option> <option value="Business">Business</option> <option value="Fiction">Fiction</option> <option value="Mathematics">Mathematics</option> <option value="Technology">Technology</option> </select> </td> <td width="13%"><input type="text" class="UnitPrice" id="UnitPrice2" name="Unit Price" step="0.01" value="0.00" placeholder="0.00" onkeypress="return forNumberOnly(event)"></td> <td width="13%"><input type="text" class="Quantity" id="Quantity2" name="Quantity" value="0" min="0" onkeypress="return forNumberOnly(event)"></td> <td width="13%"><input type="text" id="Total2" name="Total" value="0.00" readonly></td> </tr> </tbody> </table> <input type="text" readonly id="GrandTotal" />
{ "language": "en", "url": "https://stackoverflow.com/questions/64313992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What should I type in python to open a file located on my desktop when using a Mac? When I opened a .txt file located in a folder called scripts on my h-drive using Windows I typed this: F = open('h:\\scripts\\data.txt') I copied the file to a USB drive (n:) and now I want to access this file by using Python on a macbook. I typed this: P = open('n:\\data.txt') But I keep getting the following error: IOError: [Errno 2] No such file or directory: 'data.txt' So I guess I need to use a different way of specifying pathways to folders when using Python on a Macbook? Thank you for the replies, sorry for asking the original question without explaining it properly, but as you can tell I am completely new to coding. A: If by open you mean that you want to get a file() object back, then: import os filename = "Your_file.something" username = os.environ["USER"] f = open(os.path.join("/Users", username, "Desktop", filename), <mode>) But there should be a $HOME variable present which will give you the real home folder even if it is not named as the user: f = open(os.path.join(os.environ["HOME"], "Desktop/Your_file.something"), <mode>) That is if shell alias for home folder won't work: f = open("~/Desktop/Your_file.something", <mode>) BTW, <mode> is of course the mode you wish to open your file in ("r", "w", "rb", "wb", "a", "ab", etc.)
{ "language": "en", "url": "https://stackoverflow.com/questions/33745621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Writing tab spaced words to a file in Python I have a set of words in a file. I want to add a new character separated by tab to all these words and write to a new file. The code I wrote is #file to read is opened as ff and file to write is opened as fw. count = "X" x = ff.readlines() for word in x: fw.write('%s\t%s'% (word, count)) fw.write("\n") The problem is the new word 'X' is not alignment with the existing words. The sample output i am getting is A. O Mahesh O Anand O Anton O Plot The output I want is: Original File word word2 New File word X word2 X I want it to be aligned properly A: readlines() includes the end of line characters: In [6]: ff.readlines() Out[6]: ['word1\n', 'word2'] You need to strip them off: word = word.rstrip() count = "X" with open('data', 'r') as ff, open('/tmp/out', 'w') as fw: for word in ff: word = word.rstrip() # strip only trailing whitespace fw.write("{}\t{}\n".format(word, count)) A: use str.rstrip() as to remove end of line \n. use context manager with statement to open the file, and use str.formate to write in file. with open('out_file.txt') as ff, open('in_file.txt', 'w+') as r: for line in ff: r.write('{}\t{!r}\n'.format(line.rstrip(), 'X')) r.seek(0) print r.read() >>> word1 'X' word2 'X' word3 'X' word4 'X' A: you should remove '\n': count = "X" with open('data', 'r') as ff, open('/tmp/out', 'w') as fw: for word in ff.readlines(): print >> fw, '%s\t%s' % (word.rstrip(), count)
{ "language": "en", "url": "https://stackoverflow.com/questions/27600072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Column name checking null still giving null error I want to insert values in a table. So I have written the below code for that. create or replace PROCEDURE NEIQC_DATA_DUMP_MST AS BEGIN execute immediate 'truncate table TBL_NEIQC_WF_SITE_MST_NEW'; INSERT INTO TBL_NEIQC_WF_SITE_MST_NEW ( OBJECTID, SAP_ID, NETWORK_ENTITY_ID , SITE_NAME , SITE_ADDRESS , MAINTENANCEZONE_CODE , INVENTORY_TYPE , TYPE_NAME , SITE_STATUS_CODE , NE_MODIFIED_DATE , NE_MODIFIED_BY , --SERVICE_CODE, CREATED_DATE , CREATED_BY , STRUCTURE_NAME , RJ_CITY_CODE , RJ_R4G_STATE_CODE , RJ_DISTRICT_CODE , RJ_TALUK_CODE , RJ_JC_CODE , RJ_JIOPOINT_SAPCODE , RJ_COMPANY_CODE_1 , RJ_COMPANY_CODE_2 , PLACEMENT_DATE, SITE_TYPE ) SELECT OBJECTID , RJ_SAPID , RJ_NETWORK_ENTITY_ID , RJ_SITE_NAME , RJ_SITE_ADDRESS , RJ_MAINTENANCE_ZONE_CODE , CASE when RJ_SAPID LIKE '%ENB%' THEN 'SITE' ELSE 'OTHERS' end as INVENTORY_TYPE, TYPE_NAME , 4, RJ_LAST_MODIFIED_DATE, RJ_LAST_MODIFIED_BY , --APP_FIBERINV.FUNC_SC(RJ_SAPID), SYSDATE, 'SCHEDULER', STRUCTURE_NAME , RJ_CITY_CODE , RJ_R4G_STATE_CODE , RJ_DISTRICT_CODE , RJ_TALUK_CODE , RJ_JC_CODE , RJ_JIOPOINT_SAPCODE , RJ_COMPANY_CODE_1 , RJ_COMPANY_CODE_2 , PLACEMENT_DATE, REGEXP_SUBSTR(TO_CHAR(RJ_SAPID),'[^-]+', 1, 4) AS SITE_TYPE from APP_FTTX.ne_structures WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL; COMMIT; END NEIQC_DATA_DUMP_MST; But the issue is, even after checking the null condition for OBJECTID I am still getting error as ORA-01400: cannot insert NULL into ("APP_FIBERINV"."TBL_NEIQC_WF_SITE_MST_NEW"."OBJECTID") Please suggest what may be wrong here. A: This is probably down to operator precedence; AND has higher precedence than OR. So your condition: WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL is interpreted as WHERE RJ_SAPID IS NOT NULL OR (RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL) If you have a source row where OBJECTID is null then it will still pass than condition, and fail on insertion, if RJ_SAPID is anything except 'NA', including if that is null. I believe you want: WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL so you need to include those parentheses in your statement. A: i think your where condition should be improved. add '()' around your or condition WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL;
{ "language": "en", "url": "https://stackoverflow.com/questions/56394658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting entire POST response in one line I've modified the following code from an example on the internet. Currently it POSTs and returns the response line by line. How can I modify the code so it returns the entire response in one line, so I can parse it more easily. static void updateIp() throws MalformedURLException, IOException { String urlParameters = "name=sub&a=rec_edit&id=9001"; URL url = new URL("http://httpbin.org/post"); URLConnection con = url.openConnection(); con.setDoOutput(true); BufferedReader reader; try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream())) { writer.write(urlParameters); writer.flush(); String line; reader = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); } } reader.close(); } Any help would be greatly appreciated! A: You can't determine how many lines the URL response will be over, so you need to join them all together yourself in one line using StringBuilder: static void updateIp() throws MalformedURLException, IOException { String urlParameters = "name=sub&a=rec_edit&id=9001"; URL url = new URL("http://httpbin.org/post"); URLConnection con = url.openConnection(); con.setDoOutput(true); BufferedReader reader; try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream())) { writer.write(urlParameters); writer.flush(); String line; StringBuilder urlResponse = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = reader.readLine()) != null) { urlResponse.append(line); } String response = urlResponse.toString(); System.out.println(response); } reader.close(); } The response string variable will now contain all the output in a single line.
{ "language": "en", "url": "https://stackoverflow.com/questions/24072699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cocos2d-x Shaky, Liquid , Wave effect weird behaviour with android I am trying to use the effects like shaky on Sprites and Wave which I guess are heavy process. When I apply this on the sprites they work properly but after If I pause my game and then resume. Background becomes black and I can not see my bg anymore Why is this happening I really have no idea ? It happens only when I use these effects Is there anything I need to take care of after applying this effects on the sprite. I am not sure is it android bug or my mistake ?
{ "language": "en", "url": "https://stackoverflow.com/questions/12614945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DataTable with childrows (sub-dataTables). How can I create/expand ALL sub-dataTables by default? I have a dataTable with sub dataTables and I can't make them be expanded on every page. I can make them be expanded on the current page, but when I go to another page, the subtables aren't displayed. It appears as though the child row exists but no dataTable has been created. If I collapse and then expand the childrow the dataTable is created. Here is my fiddle that I forked from gyrocode.com https://jsfiddle.net/jsfiddlertwo/8rmq3foy/ Here is the expand button function $('#btn-show-all-children').on('click', function(){ // Enumerate all rows table.rows().every(function(){ // If row has details collapsed if(!this.child.isShown()){ // Open this row this.child(format(this.data())).show(); childTable(this.data()); $(this.node()).addClass('shown'); } }); }); My format function creates the html for the sub-dataTable function format ( d ) { var childId = d.extn; return '<div><table id=\'child-table' + childId + '\' class=\'table-striped table-bordered\'></table></div>'; } The childTable function creates the sub-dataTable var childTable = $(childId).DataTable({ colReorder: true, searching: false, info: false, paging: false, scrollY: false, data: data.children, columns: [{ title: "Name", render: function(data, type, row, meta) { return row.name; } }, { title: "Class", render: function(data, type, row, meta) { return row.class; } }, ] }); } The expand button expands and shows the sub-dataTables on the current page. The trouble is that when I go to another page, the sub-dataTables aren't there. Once on another page I can click on the row twice (to collapse and then re-expand) and the sub-dataTables are created. I've tried using the drawcallback but it is called before the new page is created. How can I make the sub-dataTables be created on all pages?
{ "language": "en", "url": "https://stackoverflow.com/questions/51217133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use GCP Local SSD with KubeDB Is there an example of how to set up a KubeDB PostgreSQL streaming replication cluster, where each pod's data is using Google Cloud's Local SSDs (need 2x375GB SSDs merged for each PG node). I am aware of local SSDs being temporary - for my usecase, performance and ease of scaling is far more important, and my data can be regenerated within a day. KubeDB docs in the first link have these two settings, but I am not certain how to configure pod affinity, as well as initialize (merge) two local SSDs into one as part of PostgreSQL initialization. spec.storageType specifies the type of storage that will be used for Postgres database. It can be Durable or Ephemeral. Default value of this field is Durable. If Ephemeral is used then KubeDB will create Postgres database using EmptyDir volume. In this case, you don’t have to specify spec.storage field. This is useful for testing purpose. spec.storage specifies the size and StorageClass of PVC that will be dynamically allocated to store data for this database. This storage spec will be passed to the StatefulSet created by KubeDB operator to run database pods. You can specify any StorageClass available in your cluster with appropriate resource requests. If you don’t specify spec.storageType: Ephemeral, then this field is required.
{ "language": "en", "url": "https://stackoverflow.com/questions/58021468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: binding vs with-bindings in clojure There are two macros binding and with-bindings to redefine dynamic vars. However both seem to have the utility, what is the difference between them ? ;; binding (def :^dynamic a 10) (binding [a 20] a) ;; => 20 a ;; => 10 ;; with-bindings (with-bindings {#'a 20} a) ;; => 20 a ;; => 10 both of them are changing the per thread dynamic scope, and resetting it to the root binding after the lexical scope is over. A: The underlying implementation of both is pretty much identical: * *push thread bindings (using the bindings supplied) *try the body *finally pop thread bindings binding was added in Clojure 1.0 and with-bindings in 1.1. I don't see the latter used in any code tho', just the former.
{ "language": "en", "url": "https://stackoverflow.com/questions/58258568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error with download a file from https using webclient I have create a piece of code that download a file from a given URL using WebClient. The problem is i am getting the following error when the code is trying to download a file from a HTTPS site. The remote certificate is invalid according to the validation procedure This issue happened only on the server not on the local machine, so i also don't know how to debug it. I have read several answers on the web but didn't find anything that could help me. The piece of code: using (WebClient Client = new WebClient()) { string fileName = System.Configuration.ConfigurationManager.AppSettings["siteUploadedDirectory"] + "/temp/" + Context.Timestamp.Ticks.ToString() + "_" + FileURL.Substring(FileURL.LastIndexOf('/')+1); fileName = Server.MapPath(fileName); Client.DownloadFile(FileURL, fileName); return fileName + "|" + FileURL.Substring(FileURL.LastIndexOf('/')+1); } The URL i am trying: http://Otakim.co.il/printreferrer.aspx?ReferrerBaseURL=cloudents.com &ReferrerUserName=ram &ReferrerUserToken=1 &FileURL=https://www.cloudents.com/d/lzodJqaBYHu/pD0nrbAtHSq The file URL: FileURL=https://www.cloudents.com/d/lzodJqaBYHu/pD0nrbAtHSq Any help will be appreciated A: You can bypass the certificate validation process by following code snieppet ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
{ "language": "en", "url": "https://stackoverflow.com/questions/20955833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add classes from a selector string? I have several CSS classes in the form of a selector, for example .myclass.myclass2 and I want to apply both classes to an element. I could .split() the string and apply each class with .addClass(), but before I do, I'd like to know if there's a "native" jQuery function to do this kind of thing or if someone has written a function to handle it. To better explain: I want a function that I can pass it a CSS selector and it'll add the classes to an element. Like $('#myelem').addClass('.myclass.myclass'). (I would also love it to handle other CSS selectors such as #myid, but I fear that's asking too much and I'd probably need a full parser function.) A: addClass takes a space separated string, so all you need to do is replace dots with spaces: var classes = '.myclass.myclass2'; $(element).addClass(classes.replace(/\./g,' ').trim())) A: create two classes inside style tag like this .a { backgroud-color:red; } .b{ color:blue; } </style> now add your jquery codes then inside javascript code <script type="text/javascript"> $(document).ready(function(){ $('#mydiv').addClass(a).addCLass(b); or $("#mydiv").addClass({a,b}); or $('#mydiv').addClass(a); $('#mydiv').addClass(b); }); </script> here is the html <html> <body> <div id="mydiv"></div> </body> </html> A: You can add this to your script: $.fn.oldAddClass = $.fn.addClass; $.fn.addClass = function(x){ if(typeof x == 'string'){ this.oldAddClass(x.replace(/\./g, ' ')); }else{ this.oldAddClass(x); } } Then call addClass() with your dot : $(el).addClass('.class1.class2'); Fiddle : http://jsfiddle.net/8hBDr/ A: You cannot add css selectors (like #elemid.myclass) directly to an element in native jQuery. The example below shows how to add multiple classes using a space delimited string. $(elem).addClass("myclass mycalss2") And the documentation: http://api.jquery.com/addClass/
{ "language": "en", "url": "https://stackoverflow.com/questions/17182478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to clear pending message from azure service bus? I am using azure service bus for receiving message to processing my background process. In my background process I want to clear already processed messages from azure service bus. Is there any way or method to clear azure service bus messages??? A: Read How to receive messages from a queue and make sure you use _queueClient.Complete() or _queueClient.Abandon() to finish with each message. A: You can use "Microsoft.ServiceBus.Messaging" and purge messages by en-queue time. Receive the messages, filter by ScheduledEnqueueTime and perform purge when the message has been en-queued at the specific time. using Microsoft.ServiceBus.Messaging; MessagingFactory messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString); var queueClient = messagingFactory.CreateQueueClient(resourceName, ReceiveMode.PeekLock); var client = messagingFactory.CreateMessageReceiver(resourceName, ReceiveMode.PeekLock); BrokeredMessage message = client.Receive(); if (message.EnqueuedTimeUtc < MessageEnqueuedDateTime) { message.Complete(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/28877204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to refer to yourself in the anonymous class? I have next code in kotlin: handler.postDelayed(object : Runnable { override fun run() { Timber.i("run post msg") handler.postDelayed(this, AppPrefs.SEARCH_DELAY) } },AppPrefs.SOCKET_INTERVAL) how you see it's simple standard way to create delayed task (with Runnable class). Value this references to anonimus Object implements Runnable and compile and works fine But when i make lamdba for this: handler.postDelayed({ Timber.i("run post msg") handler.postDelayed(this, AppPrefs.SOCKET_INTERVAL) },AppPrefs.SOCKET_INTERVAL) value this referenced to outher class. How referenced from inner anonimus class to yourself? A: You cannot do this. A similar question was asked on Kotlin's forum and yole (one of the creators of the language) said this: this in a lambda refers to the instance of the containing class, if any. A lambda is conceptually a function, not a class, so there is no such thing as a lambda instance to which this could refer. The fact that a lambda can be converted into an instance of a SAM interface does not change this. Having this in a lambda mean different things depending on whether the lambda gets SAM-converted would be extremely confusing.
{ "language": "en", "url": "https://stackoverflow.com/questions/44696398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: EF code first uncertainty principle - referred entities may not get loaded With automatic database recreation, it is uncertain whether referred entities will get loaded or not. The context is EF CTP 5 and ASP.NET MVC 2. In the global.asax a database initializer is set that forces recreation of the database every time the application starts up. Successfully retrieving an entity from a context in a controller action may still cause null reference errors when traversing references even if the references are marked as required (not null in the database). Turning off lazy loading does not make any difference. This behaviour cannot be reproduced reliably but was observed on two different workstations (XP, 7) using Cassini. Below are the models. Null reference exception is thrown when trying to access the NewsProvider property of the NewsFeed object. It makes no difference taking off the virtual qualifier. public class NewsProvider { public int Id { get; set; } [Required(ErrorMessage = "Please enter a name")] [StringLength(50, ErrorMessage = "The name is too long")] public string Name { get; set; } } public class NewsFeed { public int Id { get; set; } [Required(ErrorMessage = "Please enter a name")] [StringLength(50, ErrorMessage = "The name is too long")] public string Name { get; set; } [Required(ErrorMessage = "Please enter a URL")] [StringLength(300, ErrorMessage = "The URL is too long")] public string Url { get; set; } [Required(ErrorMessage = "Please enter a news provider")] public virtual NewsProvider NewsProvider { get; set; } } A: This is just a guess, but complex types can NEVER be null. So if you have any reference to a complex type (ICollection) you should initialize them from the Entity constructor. Example: public class NewsProvider { public int Id { get; set; } [Required(ErrorMessage = "Please enter a name")] [StringLength(50, ErrorMessage = "The name is too long")] public string Name { get; set; } } public class NewsFeed { public NewsFeed() { //Never allow NewsProvider to be null NewsProvider = new NewsProvider(); } public int Id { get; set; } [Required(ErrorMessage = "Please enter a name")] [StringLength(50, ErrorMessage = "The name is too long")] public string Name { get; set; } [Required(ErrorMessage = "Please enter a URL")] [StringLength(300, ErrorMessage = "The URL is too long")] public string Url { get; set; } [Required(ErrorMessage = "Please enter a news provider")] public virtual NewsProvider NewsProvider { get; set; } } For more info, here is a great blog post: http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/5194156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQLI new query within a while fetch I'm just making some website for fun at the moment but I'm stuck at a point. I want to perform a group quest and any member of the group can start it. All people of the group will get the same ammount of gold,experience and share the same cooldown. I have 3 tables in my database(I will only show important information) Members: username, level, experience, playergold Levels: level, required_experience Groups: leader, member_1, member_2, member_3, last_quest_started, quest_cooldown Quests: success_message, failed_message, chance, minimum_experience, maximum_experience, minimum_gold, maximum_gold, cooldown I want to update last_quest_started and quest_cooldown in groups, and I want to update each member his/her level, experience, playergold So after getting each username of the group members, the quests data, calculating the experience and gold. I use this to update: if($select_members_info_stmt = $mysqli->prepare("SELECT members.username, members.level, members.experience, members.playergold, levels.required_experience FROM members INNER JOIN levels ON members.level = levels.level WHERE ((members.username = ?) OR (members.username = ?) OR (members.username = ?) OR(members.username = ?))")) { $select_members_info_stmt->bind_param('ssss', $leader, $member_1, $member_2, $member_3); $select_members_info_stmt->execute(); $select_members_info_stmt->bind_result($selected_username, $level, $experience, $playergold, $required_experience); while($select_members_info_stmt->fetch()) { $now = time(); if($update_user_stats_stmt = $mysqli->prepare("UPDATE members SET level = ?, experience = ?, playergold = ? WHERE username = ?")) { $update_user_stats_stmt->bind_param('iiiiis', $new_level, $new_experience, $new_gold, $now, $cooldown, $selected_username); $update_user_stats_stmt->execute(); if($update_user_stats_stmt->affected_rows == 0) { echo '<div>Because of a system error it is impossible to perform a task, we apologize for this inconvience. Try again later.</div>'; } $update_user_stats_stmt->close(); } else { printf("Update user stats error: %s<br />", $mysqli->error); } } $select_members_info_stmt->close(); echo '<div>'.$success_message.'</div><br />'; } else { printf("Select members info error: %s<br />", $mysqli_error); } But I keep getting: Update user stats error: Commands out of sync; you can't run this command now (4 times, which is the size my groups are when they are full.) I just can't find the solution to work around the out of sync error, because I can not close the $select_members_info_stmt because then it would stop fetching. Please help me out, because I really have no clue what to do. A: You can't nest your execute() like that. The best solution is to toss that list of members into an array() once, close your connection, and THEN iterate that array and update each record. It should look like this: $select_members_info_stmt->bind_param('ssss', $leader, $member_1, $member_2, $member_3); $select_members_info_stmt->execute(); $select_members_info_stmt->bind_result($selected_username, $level, $experience, $playergold, $required_experience); $members = array(); while($select_members_info_stmt->fetch()) { // tossing into the array $members[] = array( 'selected_username' =>$selected_username, 'level' => $level, 'experience' => $experience, 'playergold' => $playergold, 'required_experience' => $required_experience ); } $select_members_info_stmt->close(); // Now iterate through the array and update the user stats foreach ($members as $m) { if($update_user_stats_stmt = $mysqli->prepare("UPDATE members SET level = ?, experience = ?, playergold = ? WHERE username = ?")) { // Note that you need to use $m['selected_username'] here. $update_user_stats_stmt->bind_param('iiiiis', $new_level, $new_experience, $new_gold, $now, $cooldown, $m['selected_username']); $update_user_stats_stmt->execute(); if($update_user_stats_stmt->affected_rows == 0) { echo '<div>Because of a system error it is impossible to perform a task, we apologize for this inconvience. Try again later.</div>'; } $update_user_stats_stmt->close(); } else { printf("Update user stats error: %s<br />", $mysqli->error); } } A: You cannot nest actively running prepared statements on the same connection to mysql. Once you call execute() on any statement you cannot run another one on the same connection until that prepared statement is closed. Any fetches on the first prepared statement will fail once you start executing on the second one. Only one 'live' statement can be prepared and running on the mysql server per connection If you really need to nest your prepared statements, you could establish 2 separate mysqli connections.
{ "language": "en", "url": "https://stackoverflow.com/questions/14470157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Angular2 Two way bindings doesn't work on Firefox I am a newee using Angular 2. I developped some forms with Typesript and it is working with Chrome but doesn't with FireFox (version 45). First of all, I tried the "two way" data bindings with both browsers : Chrome has a correct behavior but FireFox doesn't take in consideration the binding with ngModel (Find my exemple based on 5 min quickstart of angular2). In addition, the datepicker of bootstrap works well on Chrome and NOT on Firefox. Thanks in advance, app.component.ts import {Component, OnInit, Event} from 'angular2/core'; import {FORM_DIRECTIVES, NgForm, NgIf, NgFor} from 'angular2/common'; import {Types} from './types'; @Component({ selector: 'my-app', templateUrl:'./app/app.component.html', directives : [ FORM_DIRECTIVES, NgForm, NgIf, NgFor ] }) export class AppComponent implements OnInit { field:any; types:Array<string> = Types; ngOnInit() { this.field= {}; } onChange(event:Event) { console.log(this.field.type); } } app.component.html <h1>My First Angular 2 App</h1> <div class="form-group"> <label class="col-sm-2 control-label"> Select </label> <div class="col-sm-4"> <select class="form-control" [(ngModel)]="field.type" (change)=onChange($event) title="Type"> <option *ngFor="#t of types">{{ t }}</option> </select> </div> <hr/> <label class="col-sm-2 control-label"> Input </label> <div class="col-sm-4"> <input type="text" class="form-control input-sm" [(ngModel)]="field.type" placeholder="type"> </div> </div> A: I found a solution which is not very nice : * *HTML file : in the select tag I added #typeField *TS file : I changed the onChange method like below : app.component.ts import {Component} from 'angular2/core'; import {Types} from './types'; @Component({ selector: 'my-app', templateUrl:'./app/app.component.html' }) export class AppComponent { field:any = {}; types:Array<string> = Types; onChange(event:Event, newValue:any) { this.field.type = newValue; console.log(this.field.type); } } app.component.html <h1>My First Angular 2 App</h1> <div class="form-group"> <label class="col-sm-2 control-label"> Select </label> <div class="col-sm-4"> <select class="form-control" [(ngModel)]="field.type" #typeField (change)="onChange($event, typeField.value)" title="Type"> <option *ngFor="#t of types">{{ t }}</option> </select> </div> <hr/> <label class="col-sm-2 control-label"> Input </label> <div class="col-sm-4"> <input type="text" class="form-control input-sm" [(ngModel)]="field.type" placeholder="type"> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/36650575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Values from Image column are different than expected after insertion I'm developing a windows form application for insert records contained in a table from one database from another table located in a different database. The involved column is called FPTemplate and its data type is Image. Using this line of code for get the information of a column which its data type is System.Byte[] (in the DataTable variable): BitConverter.ToString((byte[])row["FPTemplate"], 0) I don't get the expected results which I detailed in the following lines. When I make the insert with this code-behind1: // Insert records in "UserFinger" destination table. string sql_cmd = ""; DataTable dt; // Has the info obtained from origin database. // Loop rows of 'dt' variable. foreach (DataRow row in dt.Rows) { // Build the T-SQL statement to execute. sql_cmd = " INSERT INTO UserFinger (Userid, Fingerid, FPTemplate) " + " VALUES ('" + row["Userid"].ToString() + "', " + row["Fingerid"].ToString() + ", '" + BitConverter.ToString((byte[])row["FPTemplate"], 0) + "')"; // Execute built T-SQL statement. ExecuteSQL(GetConnectionStringSQL_Cloud(), "UserFinger", sql_cmd); } I get this results in the destination table - see FPTemplate column -: But, in the origin table, its values - in the FPTemplate column - are: How can I correctly send the origin values to the destination table? I think this is due to use BitConverter instead of ByteConverter, but I have no idea how to proceed for get the desired results, honestly. 1 I know this isn't the best way to do the insertions of the records, this is a test I'm working.
{ "language": "en", "url": "https://stackoverflow.com/questions/52429242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract a .tar.gz file on UNIX I have a file (reviews_dataset.tar.gz) that contains many files which contains data. I am required to extract the files in this archive and then perform some basic commands on the file. So far I have created a directory named (CW) and found a command tar zxvf fileNameHere.tgz but when I run this it of course cannot find my file as I have not "downloaded it" into my directory yet? How do I get this file into my directory so that I can then extract it? Sorry if this is poorly worded I am extremely new to this. A: You must either run the command from the directory your file exists in, or provide a relative or absolute path to the file. Let's do the latter: cd /home/jsmith mkdir cw cd cw tar zxvf /home/jsmith/Downloads/fileNameHere.tgz A: You should use the command with the options preceded by dash like this: tar -zxvf filename.tar.gz If you want to specify the directory to save all the files use -C: tar -zxf filename.tar.gz -C /root/Desktop/folder
{ "language": "en", "url": "https://stackoverflow.com/questions/35398830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot create multidimentional array in PHP I have array of workers named $workers and there jobs named $jobs. Lets, each day they can do $jobs_for_each nos. of job. Now I need to create an array for there daily jobs. Here is my code: $all_workers=array("worker1","worker2","worker3","worker4", ... ... ); $all_jobs=array("j1","j2","j3", .... .... ); $jobs_for_each=7; $k=0; $day=0; for ($n=0; $n < 3; $n++) { for ($j=0; $j < count($all_workers) ; $j++) { for ($i=0; $i < $jobs_for_each; $i++) { $job_arr[$day][trim($all_workers[$j])][]=trim($all_jobs[($k*$jobs_for_each)+$i]); $distributed_arr[]=trim($all_jobs[($k*$jobs_for_each)+$i]); } $k++; } $remaining=array_diff ( $all_jobs , $distributed_arr ); unset($all_jobs); $all_jobs = $remaining; if (empty($all_jobs)) { $n=5; } else { $n=0; array_values($all_jobs); } $k=0; $day++; } This code is not working. I need $job_arr in formate of $job_arr[day][worker]=array(jobs); If my worker is 4 and jobs is 100 jobs fir each per day is 7 then it shoult take 4 days and some worker should not get job at last day; Thanks. A: I make some change in second part and add isset : <?php $all_workers=array("worker1","worker2","worker3","worker4"); $count_workers = count($all_workers); $all_jobs=array("j1","j2","j3","j4","j5","j6","j7","j8","j9","j10"); $jobs_for_each=2; $k=0; $day=0; for ($n=0; $n < 3; $n++) { for ($j=0; $j < $count_workers ; $j++) { for ($i=0; $i < $jobs_for_each; $i++) { if(!isset($job_arr[$day])){ $job_arr[$day]=array(); } $job_left = count($all_jobs); if( $job_left <= $jobs_for_each*$count_workers){ $jobs_for_each = ceil($job_left / $count_workers); } if(!isset($all_jobs[($k*$jobs_for_each)+$i])){ echo 'no more job<br />';break(3); }else{ $job_arr[$day][trim($all_workers[$j])][]=trim($all_jobs[($k*$jobs_for_each)+$i]); $distributed_arr[]=trim($all_jobs[($k*$jobs_for_each)+$i]); } } $k++; } $remaining=array_diff ( $all_jobs , $distributed_arr ); if (empty($remaining)) { break; } else { $all_jobs = array_values($remaining); } $k=0; $day++; } ?> Will ouput : no more job array (size=2) 0 => array (size=4) 'worker1' => array (size=2) 0 => string 'j1' (length=2) 1 => string 'j2' (length=2) 'worker2' => array (size=2) 0 => string 'j3' (length=2) 1 => string 'j4' (length=2) 'worker3' => array (size=2) 0 => string 'j5' (length=2) 1 => string 'j6' (length=2) 'worker4' => array (size=2) 0 => string 'j7' (length=2) 1 => string 'j8' (length=2) 1 => array (size=1) 'worker1' => array (size=2) 0 => string 'j9' (length=2) 1 => string 'j10' (length=3)
{ "language": "en", "url": "https://stackoverflow.com/questions/35559780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Method Not Allowed The method is not allowed for the requested URL. (Flask) I've cloned a flask chat app respo on Git (link: https://github.com/techwithtim/Chat-Web-App). But when I logged in and try to send a message from the form, the server said that The method is not allowed for the requested URL. I'm not sure because the Database file is separated, however I think the issues is in the @view.route("/") @view.route("/home") def home(): """ displays home page if logged in :return: None """ if NAME_KEY not in session: return redirect(url_for("views.login")) return render_template("index.html", **{"session": session}) @view.route("/get_messages") def get_messages(): """ :return: all messages stored in database """ db = DataBase() msgs = db.get_all_messages(MSG_LIMIT) messages = remove_seconds_from_messages(msgs) return jsonify(messages) and the send message is index.html like <div class="container"> <div id="messages" class="overflow-auto msgs" style="overflow-y: scroll; height:500px;"> </div> <form method="POST" id="msgForm" action="" style="bottom:0; margin: 0% 0% 0% 0%;"> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Message" aria-label="Message" id="msg"> <div class="input-group-append"> <button class="btn btn-success" type="submit" id="sendBtn">Send</button> </div> </div> </form> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/67338854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reliable way to detect a JSONP request on the server side? I have a web application that can serve some requests to the same URL either as HTML or as JSON. So far I relied on the Accept HTTP header to determine what to return. Now there is a new requirement to be able to serve the JSON as a JSONP response if a specific URL parameter exists. Unfortunately most browsers request the src attribute of a <script> tag with an Accept header of */*. At the moment i see two options around this and both have some drawbacks: * *When the Accept header is */*, check for a callback parameter and if that parameter exists, serve JSONP. This might lead to the wrong content type when the callback parameter is used for different purposes. *Do not rely on the Accept header any more and use different URL paths for different content types. This might break backwards compatibility of applications that consume the JSON or lead to duplicate URLs. Is there any other way to detect JSONP requests?
{ "language": "en", "url": "https://stackoverflow.com/questions/41040951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Write a program that stores the name as a String and number as int's of 11 players How do I get the average points from each player of both games? Write a program that stores the name as a String and numbers as int's of 11 players on a team. Your program should display/output the average points scored of each player over the two games. Nick (34), Joey (33), Ken (24), Ryan (11), Josh (3), Simon (6), Dillon (10), Mike (28), and Cameron (5). Game 1: 4, 3, 3, 2, 4, 5, 6, 6, 7, 7, 8. Game 2: 8, 4, 3, 3, 5, 5, 7, 8, 8, 9, 5. import java.util.Scanner; import java.util.Arrays; public class BasketballStats { public static void main(String[] args) { // TODO Auto-generated method stub int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10}; String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud", "Clark", "Barry", "Jose", "Paul"}; int[] game1 = new int[11]; int[] game2 = new int[11]; for (int i = 0; i < 10; i++) System.out.printf("Number %d: %s \n" , jerseyNumber[i], playerName[i]); } public void setGame1Score() { int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10}; String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud", "Clark", "Barry", "Jose", "Paul"}; Scanner input = new Scanner (System.in); for (int i = 0; i < 10; i++) { System.out.println("For game 1, how many points does he score?"); int game2 = input.nextInt(); } } } A: Things tend to get very tedious when you handle data attributes in individual arrays. Conceptually, it makes more sense in this scenario to treat a Player as a unique Object to hold their name, number and scores. public class Player { private String name; private int number; private int scores[]; private int currentGame = 0; public Player(String name, int number, int numGames) { this.name = name; this.number = number; this.scores = new int[numGames]; } // Getters and Setters public String getName() { return name; } // Required public void addScore(int score) { if (currentGame < scores.length) { scores[currentGame++] = score; } } public int getAverage() { int total = 0; for (int i = 0; i < currentGame; i++) { total += scores[i]; } return total / currentGame; } @Override public String toString() { return String.format("%s (%s) : avg %d", name, number, getAverage()); } } You then can instantiate a player with their name, number and how many games they played. You might, however, like to treat the Player class as a single game and have an Object that describes each Game itself; consisting of 10 Players. The Object is lacking getters/setters for the name and number attribute. Then you can create a single array to hold all data for a game. If you plan on having multiple games, you may want to have an array of scores instead of a single score per Player. public static final String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud", "Clark", "Barry", "Jose", "Paul"}; public static final int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10}; public Player[] createGame(int numGames) { Player[] players = new Player[10]; for (int i = 0; i < 10; i++) { players[i] = new Player(playerName[i], jerseyNumber[i], numGames); } return players; } Then when you will need to get the score somehow. public void getScore(Player[] players, int numGames) { Scanner input = new Scanner(System.in); for (int i = 0; i < numGames; i++) { System.out.println("Game " + i); for (Player player : players) { System.out.print(player.getName() + " : "); player.addScore(input.nextInt()); } } } public void getAverage(Player[] players) { for (Player player : players) { System.out.println(player.toString()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/48219106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix font-lock for Java generics? Emacs (even the latest 24.3.1) fails to render Java generics correctly. static<T> void println(T arg) { System.out.println(arg); } In the above example the method name printf is not rendered as a function. It is black and not blue. I think it must be possible to fix this by some better regular expressions. Does anybody know how to do it? A: I use this to highlight generics in java correctly: (setq c-recognize-<>-arglists t)
{ "language": "en", "url": "https://stackoverflow.com/questions/17493825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to parallelize a non-vectorizable function (i.e., root-finding) in pandas? I have a dataframe with many rows, and having columns a, b, and c. Something like: | a | b | c -------------------- 0 | 10.1| .01 | 3.0 1 | 9.7| .02 | 2.0 2 | 11.2| .03 | 1.0 ...| ... | ... | ... and a function foo(x_, a, b, c) that takes a, b, and c as parameters. I want find the root of the function for each choice of values for the parameters. This is how I currently implement it: from scipy.optimize import root df.apply(lambda x: root(foo, 0.0, args=(x["a"], x["b"], x["c"])), axis=1) The problem is that it is very slow and I would like to somehow parallelize it to speed things up. (My understanding is that apply with axis=1 simply loops through all of the rows.) What are some ways to achieve faster performance in python?
{ "language": "en", "url": "https://stackoverflow.com/questions/73559906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: While I do file.read(1) is there a way to go back 1 byte? I have to read 1 file letter by letter but sometimes I have to go a back byte (to read something that I have already read). Is there anyway to make that happen? Or how can I see the next byte without forwarding the file to then next position? A: First, I will challenge your belief that you actually need to do that. with open("babar.txt", 'rb') as file: text = file.read() print(text[42]) then, what is the actual way to accomplish this: with open("babar.txt", 'rb') as file: file.seek(42) print(file.read(1)) The first loads everything in RAM, and (if your file fits on RAM) it is incredibly fast. The second way is incredibly slow. To go back one byte, you can do this: with open("babar.txt", 'rb') as file: file.seek(42) print(file.read(1)) file.seek(-1, 1) # goes back by one relative to current position print(file.read(1)) # reeds the same char file.seek(-1, 2) # goes at the end of the file print(file.read(1)) # reads the last char Check the whence argument of seek(). Generally, one can assume making a RAM access is 1000x faster than making a HDD access, so this is probably 1000x slower than the first option. A: i just found a solution using file.seek(file.tell()-1) so it goes back if i need it to go thank you all for your help and time.
{ "language": "en", "url": "https://stackoverflow.com/questions/54851031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving custom text from mysql I have a self-made blog where I post articles. I store the articles in a db (mysql) , and from time to time I like to edit the articles. Whenever I run this code (in my edit page) , I only retrieve the text in simple form (no font , no colour , no nothing) , just the basic text : <form method="post" action="edit_script.php"> Title:<input type="text" name="title" value="<?php echo $title; ?>"><br> Body:<br><input name="body" value="<?php echo $body; ?>"> <script>CKEDITOR.replace( 'body' );</script> (<-this is the rich text editor I use) <input type="hidden" name="id" value="<?php echo $id; ?>"><br><br> <input type="submit" value="submit"> </form> and whenever I edit it , I add a word with font-size 14 for example , it shows up on the main page just like the other words , all in the same font. This is the main page code (the one where I display the text from the db after it's been written || Basically same code) : while($row = mysqli_fetch_array($run)) { echo "<h1>" . $row['title'] . "</h1>"; echo $row['body']; echo "<h6>" . $row['data'] . "</h6>"; } Again , text shows up , its just not customised (edited etc.) Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/28775572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Place file contents in email body in Ansible I have a playbook that checks hard drive space on a group of servers, sends out an email, and it attaches a file containing the output contents. Is there a way to place the contents of the file in the body itself? I would like the file contents to be able to be seen at a glance in the email. The content would be the registered variable, result. The current tasks: --- - name: Check for output file stat: path: /tmp/ansible_output.txt register: stat_result delegate_to: localhost - name: Create file if it does not exist file: path: /tmp/ansible_output.txt state: touch mode: '0666' when: stat_result.stat.exists == False delegate_to: localhost - name: Check hard drive info become: yes become_user: root shell: cat /etc/hostname; echo; df -h | egrep 'Filesystem|/dev/sd' register: result - debug: var=result.stdout_lines - local_action: lineinfile line={{ result.stdout_lines | to_nice_json }} dest=/tmp/ansible_output.txt - name: Email Result mail: host: some_email_host port: some_port_number username: my_username password: my_password to: - first_email_address - second_email_address - third_email_address from: some_email_address subject: My Subject body: <syntax for file contents in body here> <--- What is the syntax? attach: /tmp/ansible_output.txt run_once: true delegate_to: localhost - name: Remove Output File file: path: /tmp/ansible_output.txt state: absent run_once: true delegate_to: localhost Edit: I tried body: "{{ result.stdout_lines | to_nice_json }}" but it only sends me the output of the first host in the group. A: Ok, I figured it out. I created a directory, files, and sent the output to a file in that directory using the {{ role_path }} variable. In the body portion of the email task, I used the lookup plugin to grab the contents of the file. Here is the updated playbook with the original lines commented out: --- - name: Check for output file stat: #path: /tmp/ansible_output.txt path: "{{ role_path }}/files/ansible_output.txt" register: stat_result delegate_to: localhost - name: Create file if it does not exist file: #path: /tmp/ansible_output.txt path: "{{ role_path }}/files/ansible_output.txt" state: touch mode: '0666' when: stat_result.stat.exists == False delegate_to: localhost - name: Check hard drive info become: yes become_user: root shell: cat /etc/hostname; echo; df -h | egrep 'Filesystem|/dev/sd' register: result - debug: var=result.stdout_lines #- local_action: lineinfile line={{ result.stdout_lines | to_nice_json }} dest=/tmp/ansible_output.txt - local_action: lineinfile line={{ result.stdout_lines | to_nice_json }} dest="{{ role_path }}/files/ansible_output.txt" - name: Email Result mail: host: some_email_host port: some_port_number username: my_username password: my_password to: - first_email - second_email - third_email from: some_email_address subject: Ansible Disk Space Check Result #body: "{{ result.stdout_lines | to_nice_json }}" body: "{{ lookup('file', '{{ role_path }}/files/ansible_output.txt') }}" #attach: #/tmp/ansible_output.txt attach: "{{ role_path }}/files/ansible_output.txt" run_once: true delegate_to: localhost - name: Remove Output File file: #path: /tmp/ansible_output.txt path: "{{ role_path }}/files/ansible_output.txt" state: absent run_once: true delegate_to: localhost Now, my email contains the attachment, as well as the contents in the body, and I didn't have to change much in the playbook. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/62558335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React state conflict with javascript "document.getElementById" function I have this function in my React web application: const handleRateLightSelection = (cardId, rateId) => { setRateLightSelected(0); if (lastSelectedLightCardId != -1 && lastSelectedLightCardId != cardId) { document.getElementById('lightBox-' + lastSelectedLightCardId).classList.remove("rate-box-grosso-light"); document.getElementById('lightBox-' + lastSelectedLightCardId + '-check').classList.add("d-none"); } if (lastSelectedLightCardId == -1 || lastSelectedLightCardId != cardId) { document.getElementById('lightBox-' + cardId).classList.add("rate-box-grosso-light"); document.getElementById('lightBox-' + cardId + '-check').classList.remove("d-none"); setRateLightSelected(rateId); } else { var boxSelection = document.getElementById('lightBox-' + cardId).classList.contains("rate-box-grosso-light"); if (boxSelection) { document.getElementById('lightBox-' + cardId).classList.remove("rate-box-grosso-light"); document.getElementById('lightBox-' + cardId + '-check').classList.add("d-none"); setRateLightSelected(0); } else { document.getElementById('lightBox-' + cardId).classList.add("rate-box-grosso-light"); document.getElementById('lightBox-' + cardId + '-check').classList.remove("d-none"); setRateLightSelected(rateId); } } lastSelectedLightCardId = cardId; } Using document.getElementById function, I'm handling boxes styles when users select them. All is working fine by now. In retrospect, I've added setRateLightSelected state to handle the selection ID save and send it to my backend in a later time. After I've added this, the document.getElementById functions stopped working and I don't understand why?
{ "language": "en", "url": "https://stackoverflow.com/questions/64133111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: changing file's name of an file field when saving or editing a node I'm trying to change the file name of a file uploaded as part of a node form, I'm using the file widget that comes with Drupal 8. do you know with hook should I use? thanx A: Can try with hook_file_presave(); https://drupal.stackexchange.com/questions/9744/how-do-i-change-the-uploaded-file-name-after-the-node-has-been-saved
{ "language": "en", "url": "https://stackoverflow.com/questions/64102907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically adding and removing TextFields to a ScrollView iPhone How to dynamically add and remove TextFields on button press (iPhone)? Also need to retrieve values from those TextFields. I could add textfields to scrollview, but while removing textfields by pressing delete button,that textfield is getting removed but have left the space there itself. For instance , if I delete second textfield, it gets deleted, but the below textfields are not moving up.
{ "language": "en", "url": "https://stackoverflow.com/questions/26052996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Win32 : How to trap left and right mouse button clicked at the same time I am trying to program specific behaviour when the user (clicks and) releases the left and right mouse at the same time. Is there a known way to trap such an event / gesture. I am aware of how to trap leftButtonUp and rightButtonUp but not sure how I can trap this event. If the left button is pressed and then the right button is pressed with a delta delay, that is OK. When the user releases the right button / left button and if this is followed up by release of other button within a defined epsilon time then such an event should be raised. A: There is no such event in WinAPI, but you may track it yourself. wParam of all button down/up messages contains information of the state of all buttons at the time of event: MK_LBUTTON 0x0001 The left mouse button is down. MK_MBUTTON 0x0010 The middle mouse button is down. MK_RBUTTON 0x0002 The right mouse button is down. Thus, you need to keep the track of changes and define a threshold that will filter out all events that you like to consider as a "simultaneous click/release" A: You will need to write your own method of handling this. Record when the first button was clicked, when the other button is clicked see if the first button is still down and if the delay is less than whatever delta you've supplied. A: If GetAsyncKey(0x01) && GetAsyncKey(0x02){ DoEvent(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/12615994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validators on deployment server stopped working This is strange and baffling. In my ASP.NET 2.0 app I have a form that uses a number of client-side validators. Custom, Regularexpression and RequiredField. My app requires that I enable or disable certain validators based on a dropdown selection. I do this in my codebehind event. All this works great in my dev environment however when I deploy to the server it does not. Mainly when I run the app from the server it will not allow me to enable or disable the validators in code. When I set the enabled property in the aspx file it remains in that state regardless of what I do in the server event. Again - this works perfectly in dev. Any suggestions? Could it be the version of .NET 2.0 is different on my dev machine and the server? I am at a loss and we are heading for production soon. Please help! A: This turned out to be a .NET version issue. Once I applied the 2.0 Service Pack 2 on the server my problems went away. A: Do the validators work at all on the production machine? That is, do they prevent you from entering invalid data? I have a vague recollection of something like this happening to me. It may have been an issue of the JavaScript file needed by the validators not being sent from the server. Do a View Source, or turn on debugging (FireBug or IE8's F12 command). See if you're maybe getting JavaScript errors you didn't know about.
{ "language": "en", "url": "https://stackoverflow.com/questions/727828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQLdb on Mac Catalina: Library not loaded: libmysqlclient.18.dylib I have been trying to create an app with Flask on PyCharm, but I keep getting this error. After doing some research, I found that some people say that I need to fix the PATH to it, but I do not know how to fix it. Here's the code and the output I receive: import re import MySQLdb.cursors import mysql.connector from flask import Flask, render_template, request, redirect, url_for, session from flask_mysqldb import MySQL app = Flask(__name__) app.secret_key = 'hotdog' app.config['MYSQL_HOST'] = '<SOME_HOST>' app.config['MYSQL_USER'] = '<SOME_USER>' app.config['MYSQL_PASSWORD'] = '<SOME_PASSWORD>' app.config['MYSQL_DB'] = '<SOME_DATABASE>' mysql = MySQL(app) @app.route('/', methods=['GET', 'POST']) def login(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form: username = request.form['username'] password = request.form['password'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, password,)) account = cursor.fetchone() session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] return render_template('home.html', msg=msg) else: msg = 'Incorrect username/password!' return render_template('index.html', msg=msg) @app.route('/logout') def logout(): session.pop('loggedin', None) session.pop('id', None) session.pop('username', None) return redirect(url_for('login')) @app.route('/home') def home(): if 'loggedin' in session: return render_template('home.html', username=session['username']) return redirect(url_for('login')) @app.route('/profile') def profile(): if 'loggedin' in session: cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE id = %s', (session['id'],)) account = cursor.fetchone() return render_template('profile.html', account=account) return redirect(url_for('login')) if __name__ == '__main__': app.run() Output: FLASK_APP = app.py FLASK_ENV = development FLASK_DEBUG = 0 In folder /Users/parth/Desktop/School/Comp/3380_Database/team_16 /Users/parth/Desktop/School/Comp/3380_Database/team_16/venv/bin/python -m flask run * Serving Flask app "app.py" * Environment: development * Debug mode: off Usage: python -m flask run [OPTIONS] Error: While importing "app", an ImportError was raised: Traceback (most recent call last): File "/Users/parth/Desktop/School/Comp/3380_Database/team_16/venv/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app __import__(module_name) File "/Users/parth/Desktop/School/Comp/3380_Database/team_16/app.py", line 2, in <module> import MySQLdb.cursors File "/Users/parth/Desktop/School/Comp/3380_Database/team_16/venv/lib/python3.7/site-packages/MySQLdb/__init__.py",line 18, in <module> from . import _mysql ImportError: ImportError: dlopen(/Users/parth/Desktop/School/Comp/3380_Database/team_16/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Users/parth/Desktop/School/Comp/3380_Database/team_16/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found
{ "language": "en", "url": "https://stackoverflow.com/questions/61051837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How is flask able to access login.html? I am trying to learn flask. My login.html file- <html> <body> <form action = "http://localhost:5000/login" method = "post"> <table> <tr><td>Name</td> <td><input type ="text" name ="uname"></td></tr> <tr><td>Password</td> <td><input type ="password" name ="pass"></td></tr> <tr><td><input type = "submit"></td></tr> </table> </form> </body> </html> And my main.py file has this- @app.route('/login',methods = ['POST']) def login(): uname=request.form['uname'] passwrd=request.form['pass'] if uname=="ayush" and passwrd=="google": return "Welcome %s" %uname I am not able to understand how is this able to access login.html without specifying. Also also please explain what is the code in main.py means. A: You have to specify the 'html' in flask to access it, however, if you open the html file in browser this will still work since its action is aimed directly at your flask server. the code of your main.py says that if the in the form sent the data 'uname' and 'pass' are respectively 'ayush' and 'google', the code sends back to the browser a text indicating: "Welcome ayush" If you want to directly implement the html in your flask web server, you have to create the function and put your html code in templates folder. from flask import render_template ... @app.route('/', methods=['GET']) def code(): return render_template('index.html', name='') So you can access with http://localhost:5000/ now
{ "language": "en", "url": "https://stackoverflow.com/questions/69265094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Condition before a for loop def uncompress(xs): zs = [] b = True for k in xs: zs.extend([b for i in range(k)]) b = not b return zs Just wanted to know what having a variable or a condition before the for loop does in any case, so in this case what does 'b' for i in range do. A: Since b = True, zs.extend([b for i in range(k)]) is effectively zs.extend([True for i in range(k)]) or zs.extend([True, True, ..., True (k times)]). Update. I'm assuming that the intended (indented) code is the following: def uncompress(xs): zs = [] b = True for k in xs: zs.extend([b for i in range(k)]) b = not b return zs Then if xs is, say, [2, 1, 3], then: * *after the first for-loop execution (so called "iteration"), zs = [] + [True, True] = [True, True] and b becomes False, *then zs = [True, True] + [False] = [True, True, False] and b becomes True, *finally zs = [True, True, False, True, True, True] and b becomes False. So if xs == [s, t, u, v, ...] then zs is True s times, False t times, True u times, False v times and so on.
{ "language": "en", "url": "https://stackoverflow.com/questions/44483326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Array parsing and matching with values in an XML node (XSLT 1.0) Allow me to pose here a problem that I am currently encountering: I have two files: * *An XML file containing tags representing operations (historical) *A specific label file for certain operations (the common between the 2 files is the operation reference) I load the label file into my xslt and iterate through the array to build the output. I make a test to know if the reference of the current node is found in the label file so I recover the label located in the file for display. Here is my code (the loop part): <xsl:variable name="file-extrait-labels" select="'../../../../../../../../Ressources-bank/xml-xsl/EXTRAIT-10765280004-01102021-31122021.xml'" /> <xsl:variable name="table-extrait-labels" select="document($file-extrait-labels)/transactions-reals-labels" /> <table-movement struct="table"> <xsl:for-each select="/ACCOUNT_EXTRACTION/MOVEMENT"> <ligne struct="row"> <mvt.date><xsl:value-of select="normalize-space (@MOVEMENT_DATE)" /></mvt.date> <mvt.ref><xsl:value-of select="normalize-space (@MOVEMENT_ACCOUNTING_RECORD)" /></mvt.ref> <xsl:choose> <xsl:when test="$table-extrait-labels/transaction[reference = @MOVEMENT_ACCOUNTING_RECORD]"> <mvt.lib> <xsl:value-of select="normalize-space ($table-extrait-labels/transaction[reference = @MOVEMENT_ACCOUNTING_RECORD]/label)"/> </mvt.lib> </xsl:when> <xsl:otherwise> <mvt.lib><xsl:value-of select="normalize-space (@MOVEMENT_DESCRIPTION)" /></mvt.lib> <xsl:choose> <xsl:when test="LABELS"> <mvt.label><xsl:value-of select="concat(' - ', normalize-space (LABELS[1]/@LABEL))" /></mvt.label> </xsl:when> <xsl:otherwise> <mvt.label><xsl:value-of select="''" /></mvt.label> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </ligne> </xsl:for-each> </table-movement> The problem is that it doesn't work despite the fact that the references do exist in the label file. Thanks a lot for your help. Part of transaction xml file: <?xml version="1.0" encoding="UTF-8"?> <ACCOUNT_EXTRACTION> <MOVEMENT MOVEMENT_DESCRIPTION="TENUE COMPTE / FOND GARANTIE R" MOVEMENT_ACCOUNTING_RECORD="AG452032" MOVEMENT_DATE="01/11/2021" ACCOUNTING_DATE="29/10/2021" MOVEMENT_AMOUNT="6000,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE FRAIS FIXE AU 31/10/21" MOVEMENT_ACCOUNTING_RECORD="AG452032" MOVEMENT_DATE="01/11/2021" ACCOUNTING_DATE="29/10/2021" MOVEMENT_AMOUNT="1134,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="INTERETS DEBITEURS AU 31/10/21" MOVEMENT_ACCOUNTING_RECORD="AG452032" MOVEMENT_DATE="01/11/2021" ACCOUNTING_DATE="29/10/2021" MOVEMENT_AMOUNT="149,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE/INTERETS DBT AU 31/10/21" MOVEMENT_ACCOUNTING_RECORD="AG452032" MOVEMENT_DATE="01/11/2021" ACCOUNTING_DATE="29/10/2021" MOVEMENT_AMOUNT="28,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="COMM. DE DECOUVERT AU 31/10/21" MOVEMENT_ACCOUNTING_RECORD="AG452032" MOVEMENT_DATE="01/11/2021" ACCOUNTING_DATE="29/10/2021" MOVEMENT_AMOUNT="13,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TX/COM. DECOUVERT AU 31/10/21" MOVEMENT_ACCOUNTING_RECORD="AG452032" MOVEMENT_DATE="01/11/2021" ACCOUNTING_DATE="29/10/2021" MOVEMENT_AMOUNT="2,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="VERSEMENT APPRO COMP" MOVEMENT_ACCOUNTING_RECORD="VE001302150" MOVEMENT_DATE="02/11/2021" ACCOUNTING_DATE="01/11/2021" MOVEMENT_AMOUNT="470000,0000" MOVEMENT_SIDE="C"/> <MOVEMENT MOVEMENT_DESCRIPTION="RET DEPLAC" MOVEMENT_ACCOUNTING_RECORD="RA424988" MOVEMENT_DATE="02/11/2021" ACCOUNTING_DATE="03/11/2021" MOVEMENT_AMOUNT="200000,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="RET DAB ON US 130689454025" MOVEMENT_ACCOUNTING_RECORD="RETMO625051" MOVEMENT_DATE="02/11/2021" ACCOUNTING_DATE="03/11/2021" MOVEMENT_AMOUNT="150000,0000" MOVEMENT_SIDE="D"> <LABELS LABEL_ID="1" LABEL="10000014 - 2021/11/0222:07:34 "/> <LABELS LABEL_ID="2" LABEL="130689454025 "/> </MOVEMENT> <MOVEMENT MOVEMENT_DESCRIPTION="RET DAB ON US 130689501027" MOVEMENT_ACCOUNTING_RECORD="RETMO625339" MOVEMENT_DATE="02/11/2021" ACCOUNTING_DATE="03/11/2021" MOVEMENT_AMOUNT="100000,0000" MOVEMENT_SIDE="D"> <LABELS LABEL_ID="1" LABEL="10000014 - 2021/11/0222:08:21 "/> <LABELS LABEL_ID="2" LABEL="130689501027 "/> </MOVEMENT> <MOVEMENT MOVEMENT_DESCRIPTION="TENUE COMPTE / FOND GARANTIE R" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="6000,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE FRAIS FIXE AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="1134,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="COMMISSION DE CPTE AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="158,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE COMM. DE CPTE AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="30,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="COMM. DE DECOUVERT AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="21,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="INTERETS DEBITEURS AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="8,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TX/COM. DECOUVERT AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="4,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE/INTERETS DBT AU 30/11/21" MOVEMENT_ACCOUNTING_RECORD="AG526044" MOVEMENT_DATE="01/12/2021" ACCOUNTING_DATE="30/11/2021" MOVEMENT_AMOUNT="2,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TENUE COMPTE / FOND GARANTIE R" MOVEMENT_ACCOUNTING_RECORD="AG634388" MOVEMENT_DATE="01/01/2022" ACCOUNTING_DATE="31/12/2021" MOVEMENT_AMOUNT="6000,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE FRAIS FIXE AU 31/12/21" MOVEMENT_ACCOUNTING_RECORD="AG634388" MOVEMENT_DATE="01/01/2022" ACCOUNTING_DATE="31/12/2021" MOVEMENT_AMOUNT="1134,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="INTERETS DEBITEURS AU 31/12/21" MOVEMENT_ACCOUNTING_RECORD="AG634388" MOVEMENT_DATE="01/01/2022" ACCOUNTING_DATE="31/12/2021" MOVEMENT_AMOUNT="80,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TAXE/INTERETS DBT AU 31/12/21" MOVEMENT_ACCOUNTING_RECORD="AG634388" MOVEMENT_DATE="01/01/2022" ACCOUNTING_DATE="31/12/2021" MOVEMENT_AMOUNT="15,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="COMM. DE DECOUVERT AU 31/12/21" MOVEMENT_ACCOUNTING_RECORD="AG634388" MOVEMENT_DATE="01/01/2022" ACCOUNTING_DATE="31/12/2021" MOVEMENT_AMOUNT="7,0000" MOVEMENT_SIDE="D"/> <MOVEMENT MOVEMENT_DESCRIPTION="TX/COM. DECOUVERT AU 31/12/21" MOVEMENT_ACCOUNTING_RECORD="AG634388" MOVEMENT_DATE="01/01/2022" ACCOUNTING_DATE="31/12/2021" MOVEMENT_AMOUNT="1,0000" MOVEMENT_SIDE="D"/> </ACCOUNT_EXTRACTION> Part of label xml file: <?xml version="1.0" encoding="UTF-8"?> <transactions-reals-labels> <transaction> <reference>VE001302150</reference> <label>Operation Match label 1</label> </transaction> <transaction> <reference>RETMO625051</reference> <label>Operation Match label 2</label> </transaction> <transaction> <reference>RETMO625339</reference> <label>Operation Match label 3</label> </transaction> </transactions-reals-labels> A: Your expression: $table-extrait-labels/transaction[reference = @MOVEMENT_ACCOUNTING_RECORD] is looking for a transaction that has a child reference and a MOVEMENT_ACCOUNTING_RECORDattribute whose values are equal to each other. If you want to find a transaction whose child reference value is equal to the value of the MOVEMENT_ACCOUNTING_RECORDattribute of the context node (in your case, the currently processed MOVEMENT), you need to use: $table-extrait-labels/transaction[reference = current()/@MOVEMENT_ACCOUNTING_RECORD] Or (preferably) construct a key and use it as shown in the examples I pointed to in the comments. Untested, because no reproducible example was provided. Note also that testing for the existence of a node and then getting data from that node would be more efficient if you use a variable, instead of repeating the XPath expression.
{ "language": "en", "url": "https://stackoverflow.com/questions/72972988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determine if a VBComponent regards a workbook or a worksheet The following code allows me to go through the workbook and worksheets that have macros: For Each VBCmp In ActiveWorkbook.VBProject.VBComponents Msgbox VBCmp.Name Msgbox VBcmp.Type Next VBCmp As this page shows, for a workbook and a sheet, their type are both 100, ie, vbext_ct_Document. But I still want to distinguish them: I want to know which VBCmp is about a workbook, which one is about a worksheet. Note that VBCmp.Name can be changed, they are not necessarily always ThisWorkbook or Sheet1, so it is not a reliable information for what I am after. Does anyone know if there exists a property about that? A: Worksheet objects and Workbook objects both have a CodeName property which will match the VBCmp.Name property, so you can compare the two for a match. Sub Tester() Dim vbcmp For Each vbcmp In ActiveWorkbook.VBProject.VBComponents Debug.Print vbcmp.Name, vbcmp.Type, _ IIf(vbcmp.Name = ActiveWorkbook.CodeName, "Workbook", "") Next vbcmp End Sub A: This is the Function I'm using to deal with exported code (VBComponent's method) where I add a preffix to the name of the resulting file. I'm working on an application that will rewrite, among other statements, API Declares, from 32 to 64 bits. I'm planning to abandon XL 32 bits definitely. After exportation I know from where did the codes came from, so I'll rewrite them and put back on the Workbook. Function fnGetDocumentTypePreffix(ByRef oVBComp As VBIDE.VBComponent) As String '[email protected] Dim strWB_Date1904 As String Dim strWS_EnableCalculation As String Dim strChrt_PlotBy As String Dim strFRM_Cycle As String On Error Resume Next strWB_Date1904 = oVBComp.Properties("Date1904") strWS_EnableCalculation = oVBComp.Properties("EnableCalculation") strChrt_PlotBy = oVBComp.Properties("PlotBy") strFRM_Cycle = oVBComp.Properties("Cycle") If strWB_Date1904 <> "" Then fnGetDocumentTypePreffix = "WB_" ElseIf strWS_EnableCalculation <> "" Then fnGetDocumentTypePreffix = "WS_" ElseIf strChrt_PlotBy <> "" Then fnGetDocumentTypePreffix = "CH_" ElseIf strFRM_Cycle <> "" Then fnGetDocumentTypePreffix = "FR_" Else Stop 'This isn't expected to happen... End If End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/36466922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AttributeError: 'NoneType' object has no attribute 'decode' names, plot_dicts = [], [] for repo_dict in repo_dicts: names.append(repo_dict['name']) plot_dict = { 'value': repo_dict['stargazers_count'], 'label': repo_dict['description'], 'xlink': repo_dict['owner']['html_url'], } plot_dicts.append(plot_dict) my_style = LS('#333366', base_style=LCS) chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False) chart.title = 'Most-Stared Python Project On Github' chart.x_labels = names chart.add('', plot_dicts) chart.render_to_file('new_repos.svg') *If I run this, there will be an error. Traceback (most recent call last): File "new_repos.py", line 54, in <module> chart.render_to_file('new_repos.svg') File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 114, in render_to_file f.write(self.render(is_unicode=True, **kwargs)) File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 52, in render self.setup(**kwargs) File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\base.py", line 217, in setup self._draw() File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\graph.py", line 933, in _draw self._plot() File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 146, in _plot self.bar(serie) File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 116, in bar metadata) File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\util.py", line 234, in decorate metadata['label']) File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\_compat.py", line 62, in to_unicode return string.decode('utf-8') AttributeError: 'NoneType' object has no attribute 'decode' *How ever if I change part of the code to this, the error will disappear, *however the description will be ignored in the chart. names, plot_dicts = [], [] for repo_dict in repo_dicts: names.append(repo_dict['name']) plot_dict = { 'value': repo_dict['stargazers_count'], #'label': repo_dict['description'], 'xlink': repo_dict['owner']['html_url'], } plot_dicts.append(plot_dict) *I don't know why, Can anyone help me with this problem? A: 'label':str(repo_dict['description']) Try str() like above, it seems the data you got before hasn't clarifed the type of value that 'description' storged. A: May be the API didn't match the description, so you can use ifelse to solve it. Just like this. description = repo_dict['description'] if not description: description = 'No description provided' plot_dict = { 'value': repo_dict['stargazers_count'], 'label': description, 'xlink': repo_dict['html_url'], } plot_dicts.append(plot_dict)` If the web API returns the value null, it means there's no result, so you can solve it with if statement. Maybe here, the items shadowsocks didn't return anything, so it maybe something went wrong. A: from requests import get from pygal import Bar, style, Config url = "https://api.github.com/search/repositories?q=language:python&sort=stars" # получение данных по API GitHub get_data = get(url) response_dict = get_data.json() repositories = response_dict['items'] # получение данных для построения визуализации names, stars_labels = [], [] for repository in repositories: names.append(repository['name']) if repository['description']: stars_labels.append({'value': repository['stargazers_count'], 'label': repository['description'], 'xlink': repository['html_url']}) else: stars_labels.append({'value': repository['stargazers_count'], 'label': "нет описания", 'xlink': repository['html_url']}) # задание стилей для диаграммы my_config = Config() my_config.x_label_rotation = 45 my_config.show_legend = False my_config.truncate_label = 15 # сокращение длинных названий проектов my_config.show_y_guides = False # скроем горизонтальные линии my_config.width = 1300 my_style = style.LightenStyle('#333366', base_style=style.LightColorizedStyle) my_style.label_font_size = 16 my_style.major_label_font_size = 20 # построение визуализации chart = Bar(my_config, style=my_style) chart.title = "Наиболее популярные проекты Python на GitHub" chart.x_labels = names chart.add('', stars_labels) chart.render_to_file("python_projects_with_high_stars.svg")
{ "language": "en", "url": "https://stackoverflow.com/questions/44004609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to clone a project and stay tuned with new updates I want to clone POX Controller from Github repository into my laptop. The only way I know is by cloning. However, I think if someone clone a project, he/she won't get the updates that the others have done in it. I have read about forking but I don't really understand the difference between fork and clone. So how do I get a project from Github and still be able to receive updates? Thank you. A: To clone a repository means that you will download the whole code of the repository to your laptop. A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project. Most commonly, forks are used to either propose changes to someone else's project or to use someone else's project as a starting point for your own idea. More at Fork A Repo. as @TimBiegeleisen says, you can get the project and stay updated by clone once then git fetch it periodically. For example, if you want to cloning POX Controller, clone it: git clone https://github.com/noxrepo/pox Then to update it, do the following command on your cloned project: cd pox // go to your clone project git fetch Or you can use git pull instead of git fetch if only need to stay update without keeping your change in the cloned project. But you must remember the difference between git fetch and git pull. @GregHewgill answers explain it in details: In the simplest terms, git pull does a git fetch followed by a git merge. You can do a git fetch at any time to update your remote-tracking branches under refs/remotes/<remote>/. This operation never changes any of your own local branches under refs/heads, and is safe to do without changing your working copy. I have even heard of people running git fetch periodically in a cron job in the background (although I wouldn't recommend doing this). A git pull is what you would do to bring a local branch up-to-date with its remote version, while also updating your other remote-tracking branches. Git documentation: git pull
{ "language": "en", "url": "https://stackoverflow.com/questions/38602266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RGB to norm rgb transformation. Vectorizing I'm writing a piece of code that has to transform from an RGB image to an rgb normalized space. I've got it working with a for format but it runs too slow and I need to evaluate lots of images. I'm trying to vectorize the full function in order to faster it. What I have for the moment is the following: R = im(:,:,1); G = im(:,:,2); B = im(:,:,3); r=reshape(R,[],1); g=reshape(G,[],1); b=reshape(B,[],1); clear R G B; VNormalizedRed = r(:)/(r(:)+g(:)+b(:)); VNormalizedGreen = g(:)/(r(:)+g(:)+b(:)); VNormalizedBlue = b(:)/(r(:)+g(:)+b(:)); NormalizedRed = reshape(VNormalizedRed,height,width); NormalizedGreen = reshape(VNormalizedGreen,height,width); NormalizedBlue = reshape(VNormalizedBlue,height,width); The main problem is that when it arrives at VNormalizedRed = r(:)/(r(:)+g(:)+b(:)); it displays an out of memory error (wich is really strange because i just have freed three vectors of the same size). Were is the error? (solved) Its possible to do the same process in a more efficiently way? Edit: After using Martin sugestions I found the reshape function was not necessary, being able to do the same with a simple code: R = im(:,:,1); G = im(:,:,2); B = im(:,:,3); NormalizedRed = R(:,:)./sqrt(R(:,:).^2+G(:,:).^2+B(:,:).^2); NormalizedGreen = G(:,:)./sqrt(R(:,:).^2+G(:,:).^2+B(:,:).^2); NormalizedBlue = B(:,:)./sqrt(R(:,:).^2+G(:,:).^2+B(:,:).^2); norm(:,:,1) = NormalizedRed(:,:); norm(:,:,2) = NormalizedGreen(:,:); norm(:,:,3) = NormalizedBlue(:,:); A: I believe you want VNormalizedRed = r(:)./(r(:)+g(:)+b(:)); Note the dot in front of the /, which specifies an element-by-element divide. Without the dot, you're solving a system of equations -- which is likely not what you want to do. This probably also explains why you're seeing the high memory consumption. A: Your entire first code can be rewritten in one vectorized line: im_normalized = bsxfun(@rdivide, im, sum(im,3,'native')); Your second slightly modified version as: im_normalized = bsxfun(@rdivide, im, sqrt(sum(im.^2,3,'native'))); BTW, you should be aware of the data type used for the image, otherwise one can get unexpected results (due to integer division for example). Therefore I would convert the image to double before performing the normalization calculations: im = im2double(im);
{ "language": "en", "url": "https://stackoverflow.com/questions/7865866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to mock nested dependencies in NodeJS I have a Module a const b = require(./b); function aGetResult() { return b.getInfo(); } Module B const c = require(./c); function getInfo() { return getDetailInfo(); } function getDetailInfo() { const result = c.getApiResult(); return result } Module C function getApiResult() { return api.get(/test/1); } I've written a test for module A but am running into an issue with stubbing dependencies.I just want to stub c.getApiResult() and not b.getInfo() or b.getDetailInfo(). I've tried selectively stubbing using proxyquire but am having issues. Any help? A: You should use Globally override require of proxyquire package. a depends b, b depends on c. Now you want to mock the indirect c dependency instead of direct b dependency when you test a. It's NOT recommended to do this. But anyway, here is the solution: E.g. a.js: const b = require('./b'); function aGetResult() { return b.getInfo(); } exports.aGetResult = aGetResult; b.js: const c = require('./c'); function getInfo() { return getDetailInfo(); } function getDetailInfo() { const result = c.getApiResult(); return result; } module.exports = { getInfo }; c.js: const api = { get(url) { return 'real result'; }, }; function getApiResult() { return api.get('/test/1'); } module.exports = { getApiResult }; a.test.js: const proxyquire = require('proxyquire'); const { expect } = require('chai'); const sinon = require('sinon'); describe('63275147', () => { it('should pass', () => { const stubs = { './c': { getApiResult: sinon.stub().returns('stubbed result'), '@global': true, }, }; const a = proxyquire('./a', stubs); const actual = a.aGetResult(); expect(actual).to.be.eq('stubbed result'); sinon.assert.calledOnce(stubs['./c'].getApiResult); }); }); unit test result: 63275147 ✓ should pass (2630ms) 1 passing (3s) ----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|------------------- All files | 83.33 | 100 | 60 | 83.33 | a.js | 100 | 100 | 100 | 100 | b.js | 100 | 100 | 100 | 100 | c.js | 50 | 100 | 0 | 50 | 3-8 ----------|---------|----------|---------|---------|-------------------
{ "language": "en", "url": "https://stackoverflow.com/questions/63275147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ExcelJS: doesn't save file properly I wrote an script and here's an snippet from my code: let workbook = new Excel.Workbook(); await workbook.xlsx.readFile('./input.xlsx'); await workbook.xlsx.writeFile('./output.xlsx'); console.log('file saved!'); I know how async/await works and there is no error! the input.xlsx is a valid excel file. but the output.xlsx can't be opened by libreOffice or Microsoft Excel. I should notice that if I comment await workbook.xlsx.readFile('./input.xlsx');, in this situation also the output.xlsx can't be read too! It's an strange issue for me! I used exceljs many many times but I don't know why it's happening now! exceljs version: 3.9.0 A: I suppose that exceljs hasn't implemented at least one feature used in input.xlsx. Similar situation I had with images some times ago and fixed by PR: https://github.com/exceljs/exceljs/pull/702 Could I ask you to create an issue on GH? If you want to find what exactly went wrong: * *unzip input.xlsx *unzip output.xlsx *check diff between. You can also upload input.xlsx here, it should help to find a bug reason. I think also, check any other version of exceljs may be helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/61922359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preventing side scroll on mobile I'm attempting to help a friend with her site jessheading.com She's using a WordPress theme and the WP Touch mobile plugin. But when someone clicks to view the full-site version on mobile, the orange box with the quote part way down the page runs off to the side when you zoom out (creating a sort of side-scroll). The CSS on that box is: .pull-quote { background: #fb8063; width: 300%; margin: 30px 0 30px -100%; z-index: 70; position: relative; } How can I fix the CSS or the viewport settings to prevent zooming out so far so that that orange box overflows to the right? A: Parent of the box: { overflow-y: auto } A: .pull-quote { background: #fb8063; width: 300%; margin: 30px 0 30px -100%; z-index: 70; position: relative; overflow: hidden; } this merely clips overflow, and the rest of the content will be invisible some other things to consider is to resize the whole orange box as well as the tags with it. other overflow css you can try are: scroll, auto, etc. quite possibly even set the width of the orange box to be fixed and display it within a div tag that has a background of orange. hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/31954938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate items into galley I have this React Material-UI component implemented in Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <Box m={5} pl={10}> ...... some body text.......... </Box> </Grid> </Grid> How I can generate several Grid item from a array and add a horizontal scroll bar to list them if the list is too big? A: You can use the map method to render a component for each element of your array. As for the horizontal scrolling, there are several ways to do this, but one way I've found that works well is to place the items in a flex-box container and put that container inside another container that scrolls horizontally. Also with this approach you'll need to set width: fit-content on the row component so that it expands outside of the parent component. Let's say your data is stored in an array called items and the component for each is GridItem. Then we can do this: function App() { const items = [{name: "One"}, {name: "Two"}, {name: "Three"}, {name: "Four"}, {name: "Five"}, {name: "Six"}]; return ( <div className="scroll-wrapper"> <div className="row"> {items.map(e => <GridItem name={e.name}/>)} </div> </div> ) } function GridItem({ name }) { return ( <div className="grid-item"> {name} </div> ) } ReactDOM.render(<App/>, document.querySelector("#root")); .scroll-wrapper { overflow-x: scroll; padding-bottom: 1rem; /* for the scroll bar */ } .row { display: flex; flex-direction: row; width: fit-content; } .grid-item { width: 30vw; padding: 0.25rem 0.5rem; border: 1px solid black; margin-right: 1rem; } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/69307743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why am i getting -0 instead of 0? I have written a code in c which gives me rotation of point by angle given in the form of triples. When I compile and run for test case it gives me output as -0,7 . Where as the same code in python gives me output as 0,7 . When I run the same code on online compiling platforms it gives me correct output. I am using codeblocks windows 10 os. Is there something wrong with codeblocks? What should i do? C code: #include<stdio.h> #include<math.h> int main() { double xp,yp,xq,yq,a,b,c; double t,xn,yn; int z; scanf("%d",&z); // printf("Enter coordinates of p \n"); scanf("%lf%lf",&xp,&yp); // printf("\nEnter triple \n"); scanf("%lf%lf%lf",&a,&b,&c); // printf("\nEnter coordinates of q \n"); scanf("%lf%lf",&xq,&yq); t=asin(b/c); if(z==0) { xn=xp*cos(t)-yp*sin(t)-xq*cos(t)+yq*sin(t)+xq; yn=xp*sin(t)+yp*cos(t)-xq*sin(t)-yq*cos(t)+yq; } else { xn=xp*cos(t)+yp*sin(t)-xq*cos(t)-yq*sin(t)+xq; yn=-xp*sin(t)+yp*cos(t)+xq*sin(t)-yq*cos(t)+yq; } printf("%lf %lf",xn,yn); return 0; } Output: 0 4 7 3 4 5 2 3 -0.000000 7.000000 Process returned 0 (0x0) execution time : 10.675 s Press any key to continue. https://stackoverflow.com/questions/34088742/what-is-the-purpose-of-having-both-positive-and-negative-zero-0-also-written A: The most likely thing here is that you don't actually have a signed -0.0, but your formatting is presenting it to you that way. You'll get a signed negative zero in floating point if one of your calculations yields a negative subnormal number that's rounded to zero. If you do indeed have a pure signed zero, then one workaround is to clobber it with a the ternary conditional operator as printf does reserve the right to propagate the signed zero into the output: f == 0.0 ? 0.0 : f is one such scheme or even with the flashier but obfuscated f ? f : 0.0. The C standard defines -0.0 to be equal to 0.0. Another way (acknowledge @EricPostpischil) is to add 0.0 to the value. A: For floating point values there are two zeroes 0.0 and -0.0. They compare as equal (e.g. -0.0 == 0.0 returns 1) but they are two distinct values. They are there for symmetry, because for any small value other than 0, the sign does make a mathematical difference. For some edge cases they make a difference. For example 1.0/0.0 == INFINITY and 1.0/-0.0 == -INFINITY. (INFINITY, -INFINITY and NAN) are also values that the floating point variables can take. To make printf not print -0 for -0.0 and any small that would be truncated to 0 or -0, one way is to artificially put very small values to 0.0, for example: if(abs(x) < 1e-5) x = 0.0;
{ "language": "en", "url": "https://stackoverflow.com/questions/50098715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using Jeet and Compass results in an error? Whenever I try to use a combination of Jeet and Compass I get the following error: Syntax error: Invalid CSS after \" gutter\": expected \")\", was \": 3,\"\A on line 3 of sass/jeet/_settings.scss\A from line 15 of sass/jeet/index.scss\A from line 7 of sass/screen.scss\A \A 1: // Grid Settings\A 2: $jeet: (\A 3: gutter: 3,\A 4: parent-first: false,\A 5: layout-direction: LTR\A 6: );\A 7: \A 8: // Sass Namespacing Function When I run just Jeet or just compass everything works fine. I've tried different versions of SASS, Jeet, and Compass but I can't seem to find either the right combination or the right settings here. Current Versions: Sass 3.3.0.alpha.149 (Bleeding Edge) Compass 0.12.2 (Alnilam) I previously had both at their latest versions. What can I try? Recently tried: - Updating to Compass 0.12.6 which results in the new error: ERROR: Cannot load compass. Previously, this is the related code from Jeet that was throwing the error: // Grid Settings $jeet: ( gutter: 3, parent-first: false, layout-direction: LTR ); // Sass Namespacing Function @function jeet($var) { @return map-get($jeet, $var); } $g: jeet(gutter); error sass/jeet/_settings.scss (Line 3: Invalid CSS after " gutter": expected ")", was ": 3,") A: I am using it in a Yeoman scaffold with * *Sass 3.3.4 (Maptastic Maple) *Compass 0.12.5 (Alnilam) It is being compiled by "grunt-contrib-compass": "~0.7.0" and so far have had no errors. edit: Also those settings appear to be stylus not scss.
{ "language": "en", "url": "https://stackoverflow.com/questions/23186156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Object recognition with android using OpenCV library Possible Duplicate: Where do I start learning about image processing and object recognition? Is there any best way for implemeting Object Recognition in android? I tried to implement object recognition(Face tracking) in my project using OpenCV library, But I have a problem with openCV when I run this application on my device it require to install OpenCV Manager in your device. I just wanted to know is there any way to do object recognition without install any external application or supporting file in device. A: Or you could try the FaceDetector class. Its available since API Level 1. A: Try attach native libraries for OpenCV to your project and use OpenCVLoader.initDebug(); to initialization.
{ "language": "en", "url": "https://stackoverflow.com/questions/13682833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why Query returns some null values to my list Object using dapper I have this functional query where I only used fictive tables names for security concerns : SELECT h.CENID, h.BMHFMC, h.BMHDONEMIDASSTEP1, h.BMHDONEMIDASSTEP2, h.LMIID, h.BMHHOLD, h.BMHBATCHMIDAS, h.BMHFMCVALUEDATE AS HeaderValueDate, h.SUNID, h.BRAID, d.BMHID, d.BMDRUBRIQUE, d.BMDCLIENT, d.BMDSEQUENCE, d.BMDDATE, d.BMDDEVISE, d.BMDMONTANT, d.BMDTYPE, d.BMDNOTE, d.BMDENTRYNBRE, v.DEVDECIMAL , NVL(t.TYPVERIFCOMPTEMIDAS, 0) AS TYPVERIFCOMPTEMIDAS FROM dbo.TableOne h INNER JOIN dbo.Tabletwoo d ON h.BMHID = d.BMHID INNER JOIN dbo.tableThree v ON d.BMDDEVISE = v.DEVID LEFT JOIN dbo.TableFour t ON t.TYPID=h.BMHFMC WHERE d.BMDMONTANT != 0 AND h.BMHDONEMIDASSTEP1 = 0 AND h.BMHDONEMIDASSTEP2 = 0 AND h.LMIID = 0 AND h.BMHHOLD = 0 And I made a class in order to bind every fields public class Batch :BaseRepository ,IList<Batch> { public Batch() { } private string cendid; private string bmhfmc; private double bmhdonemidasstep1; private double bmhdonemidasstep2; private double lmiid; private double bmhhold; private double bmhbatchmidas; private DateTime headervaluedateordinal; private double sunid; // private string bradid; // private double bmhid; private string bmdrubirique; // private string bmdclient; private string bmdsequence; private DateTime bmddate; private string bmddevise; private double bmdmontant; private string bmdtype; private string bmdnote; private string bmdentrynbre; // private double devdecimalordinal; private double typverifcomptemidasordinal; public Batch(string cendid, string bmhfmc, double bmhdonemidasstep1, double bmhdonemidasstep2, double lmiid, double bmhhold, double bmhbatchmidas, DateTime headervaluedateordinal, double sunid, string bradid, double bmhid, string bmdrubirique, string bmdclient, string bmdsequence, DateTime bmddate, string bmddevise, double bmdmontant, string bmdtype, string bmdnote, string bmdentrynbre, double devdecimalordinal, double typverifcomptemidasordinal) { this.cendid = cendid; this.bmhfmc = bmhfmc; this.bmhdonemidasstep1 = bmhdonemidasstep1; this.bmhdonemidasstep2 = bmhdonemidasstep2; this.lmiid = lmiid; this.bmhhold = bmhhold; this.bmhbatchmidas = bmhbatchmidas; this.headervaluedateordinal = headervaluedateordinal; this.sunid = sunid; this.bradid = bradid; this.bmhid = bmhid; this.bmdrubirique = bmdrubirique; this.bmdclient = bmdclient; this.bmdsequence = bmdsequence; this.bmddate = bmddate; this.bmddevise = bmddevise; this.bmdmontant = bmdmontant; this.bmdtype = bmdtype; this.bmdnote = bmdnote; this.bmdentrynbre = bmdentrynbre; this.devdecimalordinal = devdecimalordinal; this.typverifcomptemidasordinal = typverifcomptemidasordinal; } public string Cendid { get { return cendid; } set { cendid = value; } } public string Bmhfmc { get { return bmhfmc; } set { bmhfmc = value; } } public double Bmhdonemidasstep1 { get { return bmhdonemidasstep1; } set { bmhdonemidasstep1 = value; } } public double Bmhdonemidasstep2 { get { return bmhdonemidasstep2; } set { bmhdonemidasstep2 = value; } } public double Lmiid { get { return lmiid; } set { lmiid = value; } } public double Bmhhold { get { return bmhhold; } set { bmhhold = value; } } public double Bmhbatchmidas { get { return bmhbatchmidas; } set { bmhbatchmidas = value; } } public DateTime Headervaluedateordinal { get { return headervaluedateordinal; } set { headervaluedateordinal = value; } } public double Sunid { get { return sunid; } set { sunid = value; } } public string Bradid { get { return bradid; } set { bradid = value; } } public double Bmhid { get { return bmhid; } set { bmhid = value; } } public string Bmdrubirique { get { return bmdrubirique; } set { bmdrubirique = value; } } public string Bmdclient { get { return bmdclient; } set { bmdclient = value; } } public string Bmdsequence { get { return bmdsequence; } set { bmdsequence = value; } } public DateTime Bmddate { get { return bmddate; } set { bmddate = value; } } public string Bmddevise { get { return bmddevise; } set { bmddevise = value; } } public double Bmdmontant { get { return bmdmontant; } set { bmdmontant = value; } } public string Bmdtype { get { return bmdtype; } set { bmdtype = value; } } public string Bmdnote { get { return bmdnote; } set { bmdnote = value; } } public string Bmdentrynbre { get { return bmdentrynbre; } set { bmdentrynbre = value; } } public double Devdecimalordinal { get { return devdecimalordinal; } set { devdecimalordinal = value; } } public double Typverifcomptemidasordinal { get { return typverifcomptemidasordinal; } set { typverifcomptemidasordinal = value; } } Now when I execute the query into a list using dapper Connection conn = new Connection(); OracleConnection connection = conn.GetDBConnection(); myList= connection.Query<Batch>(querySql).ToList(); Now,while debugging, all fields returns the expected values .But, I noticed those fields below are null in myList not empty but really null , but the problem is they aren't null in the database Bmdrubirique , Sunid, Bmdentrynbre, Bradid ,Cenid In oracle database those fields are like the following : CENID is VARCHAR2(3 BYTE)` Bmhid is VARCHAR2(3 BYTE) Sunid is NUMBER(38,0) Bradid is VARCHAR2(3 BYTE) I don't get it , where did it go wrong? why other fields are properly loaded while those returns null value ? A: My default assumption would be that there is a typo in the real code and the constructor is assigning a value from a field to itself. However, frankly: since you have a public Batch() {} constructor, I'm not sure what the benefit of the second one is - it just adds risk of errors. Likewise with the fields and manual properties. So if this as me, where you currently have (simplified to two properties): public class Batch { private string cendid; private string bmhfmc; public Batch() {} public Batch(string cendid, string bmhfmc) { this.cendid = cendid; this.bmhfmc = bmhfmc; } public string Cendid { get { return cendid; } set { cendid = value; } } public string Bmhfmc { get { return bmhfmc; } set { bmhfmc = value; } } } I would have literally just: public class Batch { public string Cendid {get;set;} public string Bmhfmc {get;set;} } All of the rest of the code is just opportunities to make coding errors. Now: the reason that Cendid is null is because: the column is CENID - only one d. This means that dapper isn't even using your custom constructor, because it isn't a perfect match between the constructor and the columns. Ditto the other fields like BRAID vs BRADID. So the next thing to do is to fix the typos.
{ "language": "en", "url": "https://stackoverflow.com/questions/47703332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show google map in web view In my application i want to show Google map with search result in web view. for example i want to search pizza in Texas. So i want to show Google map with already searched result for pizza Texas. A: Use this: StringBuilder u = new StringBuilder(); u.append("geo:0,0?q="); u.append("Pizza, Texas"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(u.toString())); startActivity(mapIntent); Or copy paste the maps.google.com url in this snippet to goto the browser: Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( YOUR-URL-HERE )); startActivity(browseIntent); A: do like this private WebView _webView; _webView = (WebView)_yourrelativelayourSrc.findViewById(R.id.layout_webview); _webView.getSettings().setJavaScriptEnabled(true); _webView.getSettings().setBuiltInZoomControls(true); _webView.getSettings().setSupportZoom(true); _webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { // Activities and WebViews measure progress with different scales. // The progress meter will automatically disappear when we reach 100% ((Activity) activity).setProgress(progress * 1000); } }); // to handle its own URL requests : _webView.setWebViewClient(new MyWebViewClient()); _webView.loadUrl("http://maps.google.com/maps?q=Pizza,texas&ui=maps"); A: private static final String latitude = "12.292037"; private static final String longitude = "76.641601"; webView = (WebView) findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.google.com/maps?q="+latitude+","+longitude);
{ "language": "en", "url": "https://stackoverflow.com/questions/5565002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Don't use session on certain url I'm trying to make a certain api url that can be loaded, but wont update a user's session "last activity" time. I've set things up so that my users get logged out if inactive for 60 minutes, via HttpSession.setMaxInactiveInterval(), server.session.timeout and spring security, which works well. Now, I'm trying to build an api call that the client can call to check how long their session has until it expires. But, the crux of the problem is that if I call an api, it will see this as user activity and renew the session for another 60 min, defeating the purpose. I'm hoping maybe there's a way to disable the use of a session for a certain url. Then I can just manually grab the session id via the cookie sent, manually look up their session object to get the info I need out of it without updating the last activity. A: You are probably best off writing your own session invalidation logic. You cant manually control the tomcat access time behaviour without a lot of hack work. You could write a servlet filter that tracks the last time a page(other than the whitelisted pages) was accessed and invalidates sessions that exceed the threshold. public class AccessTimeFilter implements Filter { private static final long ACCESS_TIME_WINDOW = 30 * 60 * 1000;//30 Mins private static final Set<String> IGNORED_URLS = new HashSet<>(Arrays.asList("/myurl", "/someOtherUrl")); @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpSession session = request.getSession(); Long realLastAccessedTime = (Long) session.getAttribute("realLastAccessedTime"); if(realLastAccessedTime != null && realLastAccessedTime < (System.currentTimeMillis() - ACCESS_TIME_WINDOW)){ session.invalidate(); } doFilter(req, res, chain); String url = request.getServletPath(); if(!IGNORED_URLS.contains(url)){ session.setAttribute("realLastAccessedTime", System.currentTimeMillis()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/39759061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dependency app does not run After I added the android-3.2 dependency, it did not run in my smartphone and gave me this error: Error:Execution failed for task ':app:transformClassesWithInstantRunForDebug'. Unexpected constructor structure. here is the image of adding dependency Whenever I don't add the dependency, the app runs in my smartphone. BTW, I don't use any emulator for testing my app, I just run directly in my smartphone. please help me.
{ "language": "en", "url": "https://stackoverflow.com/questions/40686875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Type Mismatch cannot convert one type to another So I have two classes, an Item class and a Book class that's extended from Item. In theory, Book objects should be treated as Item objects as well. I have a Book store with a collection and want to store books. It gives this error: Type mismatch: cannot convert from Collection Item to Collection Book How do I make it so it recognizes Books as Item as well. Should be able to substitute as Item a = new Book(); Thanks! BookStore class: public class BookStore extends Store { private BookType specialty; public BookStore(Address address, String name, BookType specialty) { super(address, name); this.setSpecialty(specialty); addBooks(); } public void displayAllBooksWrittenByAuthorsOverThisAge(int ageInYears) { Collection<Book> books = getCollectionOfItems(); // error type mismatch cannot convert from Collection<Item to Collection<Book> Iterator<Book> it = books.iterator(); boolean displayedSome = false; while (it.hasNext()) { Book b = it.next(); int ageYears = b.getDatePublished().getYear() - b.getAuthor().getBirthDate().getYear(); if (ageYears > ageInYears) { System.out.println(b.getTitle() + " was written by " + b.getAuthor().getName().getLastName() + " at age " + ageYears + ", which is more than " + ageInYears); displayedSome = true; } } if (displayedSome == false) { System.out.println("No books by authors over age " + ageInYears); } } Book class is this: public class Book extends Item { private Author author; private Date datePublished; private String title; private BookType genre; public Book(double weightKg, double manufacturingPriceDollars, double suggestedRetailPriceDollars, String uniqueID, Author author, Date datePublished, String title, BookType genre) { super(weightKg, manufacturingPriceDollars, suggestedRetailPriceDollars, uniqueID); this.author = author; this.datePublished = datePublished; this.title = title; this.genre = genre; } Item class is this: public class Item { private double weightKg; private double manufacturingPriceDollars; private double suggestedRetailPriceDollars; private String uniqueID; public Item(double weightKg, double manufacturingPriceDollars, double suggestedRetailPriceDollars, String uniqueID) { this.weightKg = weightKg; this.manufacturingPriceDollars = manufacturingPriceDollars; this.suggestedRetailPriceDollars = suggestedRetailPriceDollars; this.uniqueID = uniqueID; } Store Class: public class Store { private Address streetAddress; // instance variable of the street address. private String name; // name of the store. private HashMap<String, Item> itemsForSale; // store's products for sale. /** * Constructor of Store. */ public Store(Address streetAddress, String name) { this.streetAddress = streetAddress; this.name = name; itemsForSale = new HashMap<>(); } public void addItem(Item item) { itemsForSale.put(item.getUniqueID(), item); } /** * method that gets the item when entering key * * @param key * @return itemsForSale.get(key) */ public Item getItemByKey(String key) { return itemsForSale.get(key); } /** * method that returns back all the items * * @return itemsForSale.value() */ public Collection<Item> getCollectionOfItems() { return itemsForSale.values(); } A: In BookStore class, you are calling Collection<Book> books = getCollectionOfItems(); which returns a collection of Itemnote that Book can be casted to an Item but not the other way round. So you need to change the above Collection<Item> books = getCollectionOfItems(); If you then want to display all books, iterate over all items and check if the current item is a book before displaying it, public void displayAllBooksWrittenByAuthorsOverThisAge(int ageInYears) { Iterator<Item> items = getCollectionOfItems().iterator(); while (it.hasNext()) { Item item = it.next(); if(item instanceof Book){ displayBook((Book)item); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/42605986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSIS execute sql task get value from a query statement I am using SSIS 2008 and put a simple query (not proc) in an execute sql task (control flow). The query generate one column with a single value, what I am trying to do is based on this value to decide whether to do the following tasks. I tried mapping the value to a variable in the parameter mapping. I tried direction Output/Return value etc but all failed. The query takes no parameter. I know probably I can create a proc with a output parameter to be mapped to a variable but just wondering if there is other options (e.g. not creating proc, it's very simple query)? A: As mentioned, you need to change the SQL Task to give a Result Set on a 'Single Row', you can then output that result set to a variable. From here you can use the constraints within the Control Flow to execute different tasks based upon what the outcome variable will be; for example:
{ "language": "en", "url": "https://stackoverflow.com/questions/30186984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying Image uploaded to mysql PHP - need to display string I was trying to figure out how to upload an image into mysql then display it. I got the uploading part set. The problem I am have is displaying it. When I go to display it does one of the following: * *Displays no image but only has a little image icon 10x10px image on top left *Displays the whole string of the image and then properly renders the image. When I remove/comment out the echo $contentIMG statement, nothing displays. <?php include 'connections/conn.php'; error_reporting(E_ALL); // some basic sanity checks if(isset($_GET['id']) && is_numeric($_GET['id'])) { $contentIMG = $row_Recordset1['content']; echo $row_Recordset1['content']; //echo $contentIMG; // set the header for the image //header("Content-type: image/jpeg"); header("Content-type: image/jpeg\n\n"); echo "where is the image #1<br>"; //echo '<img src="data:image/jpeg;base64,'.$contentIMG.'"/>'; echo "where is the image #2<br>"; echo '<img src="data:image/jpeg;base64,'.base64_encode( $contentIMG ).'"/>'; if (isset($contentIMG)){ //echo '<img src="data:image/jpg;base64,'.base64_encode($contentIMG).'" />'; } //echo mysql_result($result, 0); // close the db link mysql_close($result); } else { echo 'Please use a real id number'; } echo "break <br>"; $img=base64_encode($row_Recordset1['content']); ?> I looks like this enter image description here A: I may be wrong but I think that when you set your header Content-type to image/jpeg, you should just return the image data (assuming it is stored as a blob in your database) <?php header('Content-type: image/jpeg'); echo $contentIMG; ?> Your code should look like this: <?php include 'connections/conn.php'; error_reporting(E_ALL); // some basic sanity checks if(isset($_GET['id']) && is_numeric($_GET['id'])) { $contentIMG = $row_Recordset1['content']; header('Content-type: image/jpeg'); echo $row_Recordset1['content']; // close the db link mysql_close($result); } else { echo 'Please use a real id number'; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/34099494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sublime locks files so that git cannot unstash I'm on Windows 10 Pro and using the Windows version of Git and Sublime (Build 3103). I installed git up so that I can use that before committing and pushing. This is what happens when Sublime is open: $ git up Fetching origin stashing 1 change develop up to date master up to date unstashing Unstashing failed! Here's what git said: b'error: unable to create file app/scripts/controllers/products.controller.js (Permission denied)\n' If I close Sublime there is no problem at all. I've tried running Git Bash both as user and as administrator, without any difference. Also, this only occurs on the file that is the "active tab" in Sublime, not any other files that I have opened and made changes in. Anyone knows what the problem might be?
{ "language": "en", "url": "https://stackoverflow.com/questions/36031405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to play a set of frequencies (Chords) at the same time with javax.sound.sampled package I am trying to implement a system where I give a set of frequencies to be played at once, currently can play each frequency individually. Below I have a code, that plays the given frequency, one at a time. import java.applet.*; import java.io.*; import java.net.*; import javax.sound.sampled.*; public final class StdAudio { public static final int SAMPLE_RATE = 44100; private static final int BYTES_PER_SAMPLE = 2; // 16-bit audio private static final int BITS_PER_SAMPLE = 16; // 16-bit audio private static final double MAX_16_BIT = Short.MAX_VALUE; // 32,767 private static final int SAMPLE_BUFFER_SIZE = 4096; private static SourceDataLine line; // to play the sound private static byte[] buffer; // our internal buffer private static int bufferSize = 0; // not-instantiable private StdAudio() { } // static initializer static { init(); } // open up an audio stream private static void init() { try { // 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE); buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3]; } catch (Exception e) { System.out.println(e.getMessage()); System.exit(1); } // no sound gets made before this call line.start(); } /** * Close standard audio. */ public static void close() { line.drain(); line.stop(); } /** * Write one sample (between -1.0 and +1.0) to standard audio. If the sample * is outside the range, it will be clipped. */ public static void play(double in) { // clip if outside [-1, +1] if (in < -1.0) in = -1.0; if (in > +1.0) in = +1.0; // convert to bytes short s = (short) (MAX_16_BIT * in); buffer[bufferSize++] = (byte) s; buffer[bufferSize++] = (byte) (s >> 8); // little Endian // send to sound card if buffer is full if (bufferSize >= buffer.length) { line.write(buffer, 0, buffer.length); bufferSize = 0; } } /** * Write an array of samples (between -1.0 and +1.0) to standard audio. If a sample * is outside the range, it will be clipped. */ public static void play(double[] input) { for (int i = 0; i < input.length; i++) { play(input[i]); } } private static double[] tone(double hz, double duration) { int N = (int) (StdAudio.SAMPLE_RATE * duration); double[] a = new double[N+1]; for (int i = 0; i <= N; i++) a[i] = amplitude * Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE); return a; } /** * Test client - play an A major scale to standard audio. */ public static void main(String[] args) { double hz = 440.4// 440.4 Hz for 1 sec double duration = 1.0; double[] a = tone(hz,duration); StdAudio.play(a); } } A: Simply sum the sample values at each time point, and divide by an appropriate scaling factor to keep your values in range. For example, to play A 440 and C 523.25 at the same time: double[] a = tone(440,1.0); double[] b = tone(523.25,1.0); for( int i=0; i<a.length; ++ i ) a[i] = ( a[i] + b[i] ) / 2; StdAudio.play(a); A: In this example, Tone opens a single SourceDataLine for each Note, but you can open as many lines as there are notes in your chord. Then simply write() each Note of the chord to a separate line. You can create an arpeggio effect by using Note.REST. A: you could use different threads for each frequence :) here you can find a small example of threads in java I hope this helps you :)
{ "language": "en", "url": "https://stackoverflow.com/questions/11881595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use socat to transfer serial commands in a script over TCP/IP? I have a web application that will constantly post some queries and get replies from a device through the serial port on Raspberry Pi. Like this: @cherrypy.expose def login (self, **data): passcode = data.get("passcode", None) print "logging in using passcode %s"%passcode ,type(passcode) import serial import time #open connection serialport=serial.Serial ("/dev/ttyAMA0", 9600, timeout=0.5) #write in user sign in code serialport.write("\x03LI%s\x0D"%passcode) reply=serialport.readlines(1) print reply, type(reply) #check if log in success if not "00" in reply[0]: if "FE" in reply[0]: state="engineer" else: state="user" else: state="none" print state time.sleep(1) return state Currently I am using direct 3 wires (gnd, txd, rxd) from Raspberry Pi to the device's (gnd, rxd, txd). The serial port of Raspberry Pi is /dev/ttyAMA0 and say the device has an IP of 10.0.0.55. i could send netcat command one at a time like this: nc 10.0.0.55 1001 ^CLI1234^M //this is an example of the serial command sent to the device from Raspberry Pi terminal How should i do it with **socat**? I don't want to change the script but just to manipulate some configuration in socat (or something else) that would forward the command to the device's IP. I want to get rid of the 3 wires connected to R-Pi UART. i hardly find examples on socat that would suit this requirement (or may be i don't know what keyword i should use). Please enlighten me :) Thanks a lot!
{ "language": "en", "url": "https://stackoverflow.com/questions/16579357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python3 Matplotlib psutil script not running So i have an issue. I have two Scripts running one which is a CPU and Time logger of every second to record the CPU usage to a text file. The other is a Script that reads the text file into a graph but the graph is not a uniform axis and does not increase in units and i get the wrong output view. Script1: logs PSU and time to txt file import psutil import time print(str(time.strftime("%H:%M:%S", time.localtime())) + ", " + str(psutil.cpu_percent(interval=1))) f = open("example.txt", "a+") f.write(str(time.strftime("%H:%M:%S", time.localtime())) + ", " + str(psutil.cpu_percent(interval=1)) + " \n") Program 2: plots to a graph import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style style.use('fivethirtyeight') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) def animate(i): graph_data = open ('example.txt','r').read() lines = graph_data.split('\n') xs = [] ys = [] for line in lines: if len(line) > 1: x, y = line.split(',') xs.append(x) ys.append(y) ax1.clear() ax1.plot(xs, ys) ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show() Script2 output If this can be made into one Script then great but i am trying to learn the basics. I think it is a String issue with writing to txt files but dont know why a string would matter in a txt file. A: I suppose that the string you need to write in the TXT o CSV file will be generated by (in CSV is much easier to read before): import time import psutil import csv num_measures = 10 with open("cpu_pcnt.csv", mode='w') as file: for _ in range(num_measures): str_time = time.strftime("%H:%M:%S") cpu_pcnt = psutil.cpu_percent(interval=1) str_data = f"{str_time},{cpu_pcnt}\n" file.write(str_data) Then, convert the time in datetime object to the plot and look to cast the pcu percent into float: def animate(i): xs = [] ys = [] with open("cpu_pcnt.csv") as file: reader = csv.reader(file) for line in reader: xs.append(datetime.strptime(line[0], "%H:%M:%S")) ys.append(float(line[1])) ax1.clear() ax1.plot(xs, ys)
{ "language": "en", "url": "https://stackoverflow.com/questions/62665043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access 2013 and Sharepoint 2013 Web Integration First of all, this question is somewhat high level (or as I also like to call it.. Vague). I have worked in a few IT departments and every place I go I seem to see the same thing, users are looking for a way to bring there old access databases for things like IT inventory and task management onto the web. SharePoint is the obvious choice, but it seems it can get about 90% of the way there out of the box. Then all of a sudden you hit a dead end and your only option is to bust out visual studio to complete the rest, obviously not great when the end user has done the first 90% themselves ! The real restrictions seem to be on linking lists, permissions on individual list columns etc I see SharePoint 2013 and Access 2013 can now be linked/integrated, has anybody tried this sort of stuff and is it really doable for an end user like Microsoft say ? A: The abilities that Access 2013 has compared to the Sharepoint "web app" feels limited. You cannot use the VBA code in any of your forms and must deal with SQL and Macro Commands only. So if you use a lot of VBA you will have to redo most of your project and learn how to use the macro's. Personally i have used VBA to do most of my work but like you need it to be out on the web now. My main fear with spending time using Access and Sharepoint is not being able to custom code pieces in. If i run into a limitation i don't believe there is another option. * *Example Web App *When Access web apps 2013 gets Johnny frustrated... *Discontinued features and modified functionality in Access 2013 The interface is different and from an overview seems more effective for simple input and view forms, something easily used on a phone. For instance this is a default contact form in its edit view in Access. Most of your control is centered around the custom buttons on top which i found to be limited to on click macros and simple edit / save data actions. Your options for forum design also is limited, however there is an added bonus of an autocomplete search input bar which is absent from the desktop based projects. In addition the macro list options have been reduced some.
{ "language": "en", "url": "https://stackoverflow.com/questions/14303692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Credit Card Options in Paypal Express Checkout I have setup the express checkout process integration in asp.net mvc. When user is redirected to paypal website after submission, there is only option to login using paypal or sign up new account. There is no option to pay using credit card ? Am i using right API for this? A: By default Express Checkout is for PayPal accountholder payments; originally you would pair this with some other product for credit card payments (such as collecting the card information on your site and calling PayPal DirectPay or some other card processing partner). PayPal also has several somewhat-similar products that collect the card information on their site (so you don't have to) and do that as well as accountholder payments; these vary in whether they end up giving you access to the credit card information (more flexible, but means you have to safely handle the card information and meet industry regulations, including vetting) or you do not ever see the card, just the money (simpler). This is often called some form of "guest checkout." And eventually PayPal did add a guest checkout option to Express Checkout called "Account Optional." So you can use Express Checkout and get a guest checkout experience. See this link: PayPal: express checkout pay without account So in short you can get this from EC if you configure things for it, although some other PayPal products might be a better fit depending upon your particular requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/28622525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Errors running the Math.Round I am taking some Lynda.com classes approved by my work and looking to learn some Java. Can someone please tell me why I am getting an error with the Round and Absolute functions? The error I am seeing is 'Cannot resolve method round(double)'. I get the same error with the absolute value. All I am doing is pretty much copying what the instructor is giving me. I am just doing some simple Math calculations: public class Math { public static void main(String[] args) { int intValue1 = 56; int intValue2 = 42; int result1 = intValue1 + intValue2; System.out.println("Addition: " + result1); int result2 = intValue1 - intValue2; System.out.println("Subtraction: " + result2); int result3 = intValue1 * intValue2; System.out.println("Multiplication: " + result3); double result4 = (double) intValue1 / intValue2; System.out.println("Division: " + result4); int result5 = intValue1 % intValue2; System.out.println("Remainder: " + result5); double doubleValue = -3.999999; long rounded = Math.round(doubleValue); System.out.println("Rounded: " + rounded); double absValue = Math.abs(doubleValue); System.out.println("Absolute: " + absValue); } } Also please let me know if I did not perform the code tags correctly? A: The problem is that your class is called Math, so the compiler is looking for a method round() on your class, which doesn't exist. Rename your class to MyJavaLesson or somesuch, and then the compiler will know you want methods from java.lang.Math. You should never name your own classes with the same name as a class from anything under the java package, because it usually leads to confusion (as it has here). A: See if replacing double doubleValue to float doubleValue helps you.The Math.round() functions takes float as its arguements. Dont forget to add f after the float number assignment i.e float doubleValue = -3.999f. A: The main problem here is that this class is named Math (at the very top: public class Math {). Which overwrites the Math toolkit provided by java. If you name your class and file to something else it should be fine. p.s. generally by convention, we don't use capital letters in class and file names; to avoid these from happening. A: Thanks everyone for the help on this. Also, not sure if asking this question is allowed on this forum but was just curious how others learned Java? I am considering take a class at a community college but wondering if I am just better off learning from Lynda.com, Udemy, and Coursera.
{ "language": "en", "url": "https://stackoverflow.com/questions/53844633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript File load other Javascript files With no window/document I'm working with javascript file that has no window or document. I have package.json file that calls another Javascript file task.js package.json: { "name": "mytask", "version": "1.0.0", "description": "mytask TFS Build", "main": "scripts/mytask.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "install": "npm install" }, "repository": {}, "author": "OST", "license": "ISC", "dependencies": { "https-proxy-agent": "1.0.0", "jquery": "3.3.1", "jsdom": "13.0.0", "load-json-file": "^2.0.0", "moment": "^2.22.2", "object.values": "^1.0.4", "request": "2.81.0", "vso-node-api": "^5.1.2", "vss-web-extension-sdk": "5.141.0", "vsts-task-lib": "1.1.0" } } TFS call javascript file exist in package.json "main" option. package.json call mytask.js via "main" option and this javascript file will run as a task in TFS and print things to console. Basically my issue that there's no HTML page or document so I cannot load javascript file through or document.addElement... I need to load javascript file (VSS.SDK.js from vss-web-extension-sdk) to mytask.js. I'm new in javascript so I don't really know what I'm doing wrong. After long searching, I found "jsdom" which creates a global document. But still didn't know how to load VSS.SDK.js script. mytask.js: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM(`<!DOCTYPE html>`); var jQuery = require("jquery")(window); // Option 1 jQuery.loadScript = function (url, callback) { jQuery.ajax({ url: url, dataType: 'script', success: callback, fail: callback, async: false }); } jQuery.loadScript('vss-web-extension-sdk/lib/VSS.SDK.js', function(){console.log("loaded!!!!!!!!!!!!!!!!!!!!")}); // Option 2 jQuery.getScript('vss-web-extension-sdk/lib/VSS.SDK.js').done(function(){console.log("loaded!!!!!!!!!!!!!")}).fail(function(){console.log("failed!!!!!!!!!!!!!!")}); // Option 3 jQuery.getScript('vss-web-extension-sdk/lib/VSS.SDK.js', function() { VSS.init({explicitNotifyLoaded: true, usePlatformScripts: true, usePlatformStyles: false}); var serverContext = VSS.getWebContext(); }); I tried these three options but it didn't work! nothing was printed. I use VSS.SDK to load webContext. any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/53632616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET and XML for each hit to website I have a question to understand the concept of ASP.NET with each client browser. I am trying to update the XML on server when a user hits a particular page on my website. This page is dynamic, but too large so I want it to load using an XML file also I have several drop downs on the page when user changes the value in drop down, I need to refresh the data based upon the selection, additionally my drop down is a custom designed here I do not get and selectedIndex change event. So I'm using JQuery to get the changed value in my drop down and planning to read XML from jQuery and display the data. But since the XML is updated on hit of the page on server, I want know, if multiple users hit the same page, will the data displayed as per each users selection or it will mix the data and show the last hits record. A: If I'm not mistaken about your question, you basically ask the following: You have an XML file, which is updated, on some event from user. The page, which is displayed to the user is based on this XML file. What info will users see, when multiple users are working with the application? This greatly depends on how you are using that file. In general, if you try to write that file to disk each time, users will see the last update. Basically update from the last user. However, you can synchronize access to this file, write the file on per-user basis and you will see a per-user output: <data> <selectedData user="user name">123</selectedData> <!-- and so on --> </data> UPDATE: For anonymous users this would not work well. However, if you need to store the selection only for the current user, you can use SessionState and not an XML file. A: I would like to introduce a new way that it helped me to answer my above question. What i did here is on Page load we added all the information related to each section in different hidden fields. suppose i have three section with my custom drop down! What exactly we implemented is that on click on my custom drop-down, we separated the values from the hidden field with the separator we entered and displayed the data accordingly, small part of logic but it helped in displaying the data without post back. and Jquery helps a lot to me for just changing the inner html of my block.
{ "language": "en", "url": "https://stackoverflow.com/questions/8533289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Box.com API: How Do I Connect My Own Account To Upload Files? I've a basic (free) account at box.com and I've build a form in PHP where user can select a file and pass that file to upload.php. Now, I need to connect to box.com servers and use my account to store that file. I have my own login used here. How do I implement this? Currently I'm doing this: <pre><?php $parent = array(); $parent['id'] = '0'; $params = array(); $params['name'] = 'Testfolder'; $params['parent'] = $parent; $params = json_encode($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.box.com/2.0/folders"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_HTTPHEADER, array("'Content-Type: application/json', 'Content-Length: ' . strlen($params), Authorization: BoxAuth api_key=[api]&auth_token=[token]")); $result = curl_exec($ch); curl_close($ch); print_r($result); ?> </pre> But currently [token] is very very temporary and it isn't working as well. Please help! A: Take a look at this. I have had success using it and found it to be the best framework out there for box-api and php https://github.com/golchha21/BoxPHPAPI
{ "language": "en", "url": "https://stackoverflow.com/questions/28173473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Micro Edition 3.2 SDK replacement for BufferedOutputStream The Java Micro Edition SDK does not include java.io.BufferedOutputStream. Does anyone know of a suitable replacement which is present within the SDK? http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedOutputStream.html Thanks, Adam A: I don't know of a replacement, but BufferedOutputStream doesn't contain much code. Just duplicate it from the full blown JDK source to your own replacement class. There is no rocket science in the class anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/16107416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Async fetch a function into another node.js file I'm trying to fetch events from Google Calendar. I have code to do that in a js file (googlecal.js) I have posted the function that lists the events. Now I want to write a new js file and get the list of these events from the googlecal.js file. Fairly new to JS, would appreciate a direction for this. function listEvents(auth) { const calendar = google.calendar({version: 'v3', auth}); calendar.events.list({ calendarId: 'primary', timeMin: (new Date()).toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime', }, (err, res) => { if (err) return console.log('The API returned an error: ' + err); const eve = res.data.items; if (eve.length) { //console.log('Upcoming 10 events:'); eve.map((event, i) => { const start = event.start.dateTime || event.start.date; //console.log(`${start} - ${event.summary}`); var attendee = event.attendees; }); } else { console.log('No upcoming events found.'); } }); } I tried to use module.exports or exporting this function and importing in a new file. But I am not very sure how to export it and import in the other js file, which is where I am facing the problem. A: You can export this function as the top level/default through module.exports = listEvents if this is all you're interested in exporting, and use it as const listEvents = require('./googlecal') (the path would mean that the importer is at the same level). Another popular convention is to export as an object so you have space to expand your module's exported funtionalities: module.exports = { listEvents, // future stuff } And use it so by leveraging destructuring: const { listEvents } = require('./googlecal') A: If your environment support ES6 Module syntax, you can use import and export, if not then you should use require and module.exports. if you are going to use module.exports then just add module.exports = { listEvents } and importing it with const { listEvents } = require('./path/to/your/file') You can read this for using export: How to use import/export
{ "language": "en", "url": "https://stackoverflow.com/questions/55974002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Build error while deploying Google Cloud Java Function I am trying to deploy a cloud function with Java-11 runtime and the build is failing. Here is the stack trace: ERROR: build step 5 "us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00" failed: step exited with non-zero status: 2 ERROR Finished Step #5 - "exporter" Step #5 - "exporter": Adding cache layer 'google.java.functions-framework:functions-framework' Step #5 - "exporter": Adding cache layer 'google.java.gradle:cache' Step #5 - "exporter": *** Images (sha256:d1b6b49691d3674ea9676b7f6933d6d2dfdac6151e6cc72e29a6159e7d7f5394): Step #5 - "exporter": Adding label 'google.builder-version' Step #5 - "exporter": Adding label 'google.source-archive' Step #5 - "exporter": Adding label 'io.buildpacks.project.metadata' Step #5 - "exporter": Adding label 'io.buildpacks.build.metadata' Step #5 - "exporter": Adding label 'io.buildpacks.lifecycle.metadata' Step #5 - "exporter": Adding layer 'config' Step #5 - "exporter": Adding layer 'launcher' Step #5 - "exporter": Adding 1/1 app layer(s) Step #5 - "exporter": Adding layer 'google.java.functions-framework:functions-framework' Step #5 - "exporter": Adding layer 'google.utils.archive-source:src' Step #5 - "exporter": Already have image (with digest): us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00 Starting Step #5 - "exporter" Step #4 - "builder": Already have image (with digest): us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00 ***Build steps here, not pasting because my code is here*** Starting Step #4 - "builder" Finished Step #3 - "restorer" Step #3 - "restorer": Already have image (with digest): us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00 Starting Step #3 - "restorer" Finished Step #2 - "analyzer" Step #2 - "analyzer": Already have image (with digest): us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00 Starting Step #2 - "analyzer" Finished Step #1 - "detector" Step #1 - "detector": google.utils.label 0.0.1 Step #1 - "detector": google.java.functions-framework 0.9.0 Step #1 - "detector": google.java.gradle 0.9.0 Step #1 - "detector": google.utils.archive-source 0.0.1 Step #1 - "detector": us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00 Step #1 - "detector": Status: Downloaded newer image for us.gcr.io/fn-img/buildpacks/java11/builder:java11_20200820_12_RC00 Step #1 - "detector": Digest: sha256:335c80ce3fd84e8f1d5152b60951274173f79f460d4995bac26ecb0cf0964007 I am trying to deploy it using the command line tool as so: gcloud functions deploy testFunction --entry-point functions.TestFunction --runtime java11 --trigger-http --memory 256MB --allow-unauthenticated I don't have an idea of what the error means and what to do to fix it. Any help would be appreciated. Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/64045006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NHibernate unique constraint remove if duplicate Is there a way to tell nHibernate to remove the duplicate value on a row's column that is uniquely constrained when updating a row with a duplicate value. For example (OtherId and Animal is compositely unique constrained) Id | OtherId | Animal ------------ 1 | 1 | Dog 2 | 1 | Cat 3 | 1 | Bear 4 | 2 | Dog Updating Id 3 to Dog, should result in this Id | OtherId | Animal 1 | 1 | NULL 2 | 1 | Cat 3 | 1 | Dog 4 | 2 | Dog EDIT: I was able to solve my problem by creating an unique index in my table CREATE UNIQUE INDEX [Id_OtherId_Animal_Index] ON [dbo].[Animals] (OtherId, Animal) WHERE Animal IS NOT NULL; This way, I prevent insertion of duplicate (1, Dog) and still allow (2, Dog). This will also allow multiple (1, NULL) to be inserted. Next, based on Frédéric's suggestion below, I edited my service layer to check BEFORE insertion if it will be a duplicate. If it will, then NULL the animal column of which would be uniquely constrained. A: This answer has been outdated by substantial changes in OP question I am quite sure there is no such feature in NHibernate, or any other ORM. By the way, what should yield updating Id 3 to Cat after having updated it to Dog? Id | Animal 1 | 2 | 3 | Cat If that means that Id 1&2 now have the empty string value, that will be an unique constraint violation too. If they have the null value, it depends then on the db engine being ANSI null compliant or not (null not considered equal to null). This is not the case of SQL Server, any version I know of, at least for the case of unique indexes. (I have not tested the unique constraint case.) Anyway, this kind of logic, updating a row resulting in an additional update on some other rows, has to be handled explicitly. You have many options for that: * *Before each assignment to the Animal property, query the db for finding if another one has that name and take appropriate action on that another one. Take care of flushing right after having handling this other one, for ensuring it get handled prior to the actual update of the first one. *Or inject an event or an interceptor in NHibernate for catching any update on any entities, and add there your check for duplicates. Stack Overflow has examples of NHibernate events or interceptors, like this one. But your case will probably bit a bit tough, since flushing some other changes while already flushing a session will probably cause troubles. You may have to directly tinker with the sql statement with IInterceptor.OnPrepareStatement by example, for injecting your other update first in it. *Or handle that with some trigger in DB. *Or detect a failed flush due to an unique constraint, analyze it and take appropriate action. The third option is very likely easier and more robust than the others.
{ "language": "en", "url": "https://stackoverflow.com/questions/42518799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC 5 App - Implement No Client Page Caching I want to prevent any client page in my MVC 5 application from being cached. My _Layout.cshtml page looks as follows. Notice the code in the head tag. Is this enough (and is it correct) to prevent caching on any page in my app? Or do I need to also add code on every page? <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="no-cache"> <meta http-equiv="Expires" content="-1"> <meta http-equiv="Cache-Control" content="no-cache"> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <img class="visible-lg visible-md" src="~/Images/WebBirderFatbirder.png" title="WebBirder"> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> @Html.Partial("_LoginPartial") </div> </div> </div> <div id="bodyContentDiv" class="container body-content"> @RenderBody() <hr /> <footer> <br/> <br /> <br /> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/26382091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add an outside library to an ESP-IDF Project I've been trying to fix this for a couple days so any insight would be greatly appreciated. I am building a project with an ESP32 board and VSCode's esp-idf framework. I am having trouble getting access to an outside library's functions. For example, I have implemented an FFT-noise-filter program in c, and now i want to bring it into the esp-idf framework. I think it has something to do with my unfamiliarity with CMake, and I have tried all sorts of different "CMakeLists.txt", but not sure what it should look like. I've been through cmake tutorials, but I just can't figure it out. Here's my current 'CMakeLists' inside main folder idf_component_register(SRCS "hello_world_main.c" INCLUDE_DIRS ".") I took an example project 'hello_world' from esp-idf's examples, and wrote my own code inside of the 'hello_world_main.c'. It is weird because in my "hello_world_main.c" the complier seems to know some data types such as 'FFTW_Complex', which are only found in the library I'm trying to use. However, when I call any functions like FFTW's 'malloc' from that same library, I get an error "undefined reference to fftw_malloc()" excerpt from hello_world_main.c's 'app_main(): //complex: double[2] = {real_part,imag_part} fftw_complex *in, *out; //no errors here for some reason fftw_plan p; //initialize the arrays-> "in" is an array of fftw_complex type (basically a pair of doubles) //in is f (set of points we know) -> out is fhat (complex fourier coefficents) with magnitude and phase in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); //'undefined reference to fftw_malloc' Error message: [5/7] Linking CXX executable hello_world_2.elf FAILED: hello_world_2.elf cmd.exe /C "cd . && C:\Users\bgreenwood.espressif\tools\xtensa-esp32-elf\esp-2021r2-patch3-8.4.0\xtensa-esp32-elf\bin\xtensa-esp32-elf-g++.exe -mlongcalls -Wno-frame-address @CMakeFiles\hello_world_2.elf.rsp -o hello_world_2.elf && cd ." c:/users/bgreenwood/.espressif/tools/xtensa-esp32-elf/esp-2021r2-patch3-8.4.0/xtensa-esp32-elf/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: esp-idf/main/libmain.a(hello_world_main.c.obj):(.literal.app_main+0x1c): undefined reference to `fftw_malloc' so my question is, how can I get my main to recognize the function calls I am making? A: Add your libcode.c to: idf_component_register(SRCS "hello_world_main.c" “libcode.c” INCLUDE_DIRS ".") And add a reference to libcode.h: #include “libcode.h” Libcode is an artificial name, change it by the correct one and you could also add a directory if needed like “libcode/libcode.h” Hope this answers your question; with more code it’s easier to understand your problem. A: To check what the minimal component would look like, you can create one using idf.py create-component NAME. The component named NAME will be made, and you can check what is missing in your external library.
{ "language": "en", "url": "https://stackoverflow.com/questions/72552661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide folders in url, rewrite url I have a project with a special hosting structure: * *www * *domains * *projectName (example.com) I have to set the baseUrl config.baseURL = http://example.com/domains/example.com/. Url example http://example.com/domains/example.com/index.php?id=4. If I use only config.baseURL = http://example.com/. The site works but sessions do not work and user cannot log (he can log in but after reload he is logged out) I need to have url only with http://example.com/index.php?id=x. There is 1 htaccess in the www folder with these rules. RewriteEngine On RewriteCond %{REQUEST_URI} !^domains/ RewriteCond %{REQUEST_URI} !^/domains/ RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$ RewriteCond %{DOCUMENT_ROOT}/domains/%2 -d RewriteRule (.*) domains/%2/$1 [DPI] RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,QSA,L] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^domains/[^/]+/(.+[^/])$ /$1/ [R] And another is in my project folder. I am sure there will be just an easy htaccess rule. But I do not have any experience with it. I tried to use the solution from Mod Rewrite Hide Folder but it did not help. I tried to use it in both htaccess files. Any ideas? Thank you! A: You could try setting the TypoScript option config.absRefPrefix to /domain/www.example.com/ See http://buzz.typo3.org/people/soeren-malling/article/baseurl-is-dead-long-live-absrefprefix/ and http://wiki.typo3.org/TSref/CONFIG
{ "language": "en", "url": "https://stackoverflow.com/questions/19815671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set users.userid as a key in ndb I'm trying to write appengine python code that uses the built-in authentication 'users' object and using userid as an ndb key Here's my model: class UserAccounts(ndb.Model): UserID = ndb.KeyProperty(required=True) In my handler: I get the current user user = users.get_current_user() Instantiate an entry account = Models.UserAccounts() Set the userid to the ndb entry account.UserID = userid When I run it, I get this: Expected Key, got '113804764227149124198' Where am I going wrong? As much as possible, I'd like to use a KeyProperty instead of StringProperty for performance reasons. A: by: account.UserID = userid I assume you meant: account.UserID = user.user_id() The user id is a string, not a key, so you can't use a KeyProperty here. In fact, AFAIK, User objects as returned from users.get_current_user() don't have a key (at least not one that is documented) since they aren't datastore entries. There is an ndb.UserProperty, but I don't think it's use is generally encouraged. What performance reasons are you referring to? A: I think what you want is something like this UserAccounts(id=user_id), this way the user_id is the key. With this approach you can remove the userid field from the model definition
{ "language": "en", "url": "https://stackoverflow.com/questions/20651829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is React state not changing simultaneously with input change for a controlled component I don't think I missed anything in making the form a controlled component. Why doesn't the state doesn't change as characters are being input? class AddChores extends Component { state = { chore: "", }; handleChange = (evt) => { this.setState({ chore: evt.target.value }); }; handleSubmit = (evt) => { evt.preventDefault(); this.props.addChores(this.state); this.setState({ chore: "" }); }; render() { console.log(this.state); return ( <div> <form onClick={this.handleSubmit}> <input type="text" placeholder="New Chore" value={this.state.chore} onChange={this.handleChange} /> <button className="button">ADD CHORE</button> </form> </div> ); } }[![React dev tool showing no simultaneous update][1]][1] A: not sure why is this happening but try using the second form of setState this.setState(() => ({ chore: evt.target.value})) check this https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous A: I made some changes as below and it works fine for me. Hope it helps you too. class AddChores extends Component { constructor(props) { super(props); this.state = { chore: "" }; } handleChange = (event) => { this.setState({ chore: event.target.value }); }; handleSubmit = (evt) => { evt.preventDefault(); // this.props.addChores(this.state); this.setState({ chore: "" }); }; componentDidUpdate(){ console.log('the state', this.state.chore) } render() { return ( <div> <form onClick={this.handleSubmit}> <input type="text" placeholder="New Chore" value={this.state.chore} onChange={this.handleChange} /> </form> </div> ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/64472235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autofill is failing after creating a "local" alias in my ~/.bashrc file I added aliases to my .bashrc file. After I did that and ran source ~/.bashrc, auto fill started to throw errors in my Ubuntu command prompt. The error directs me to line 295 of my bash_completion file to look for incorrect syntax. When I open this file and go to line 295, I see no incorrect syntax. Here are the lines of code I'm adding and the errors I'm receiving. Alias I originally added to my .bashrc file: alias local='cd /mnt/c/Users/NYCZE/OneDrive/' Error thrown when I run source ~/.bashrc to implement this alias: bash: /usr/share/bash-completion/bash_completion: line 295: syntax error near unexpected token `(' bash: /usr/share/bash-completion/bash_completion: line 295: `(' Function which contains line 295 in my bash_completion file: __reassemble_comp_words_by_ref() { local exclude i j line ref # This line right here is the problem one # Exclude word separator characters? if [[ $1 ]]; then # Yes, exclude word separator characters; # Exclude only those characters, which were really included exclude="${1//[^$COMP_WORDBREAKS]}" fi # Default to cword unchanged printf -v "$3" %s "$COMP_CWORD" # Are characters excluded which were former included? if [[ $exclude ]]; then # Yes, list of word completion separators has shrunk; line=$COMP_LINE # Re-assemble words to complete for (( i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do # Is current word not word 0 (the command itself) and is word not # empty and is word made up of just word separator characters to # be excluded and is current word not preceded by whitespace in # original line? while [[ $i -gt 0 && ${COMP_WORDS[$i]} == +([$exclude]) ]]; do # Is word separator not preceded by whitespace in original line # and are we not going to append to word 0 (the command # itself), then append to current word. [[ $line != [[:blank:]]* ]] && (( j >= 2 )) && ((j--)) # Append word separator to current or new word ref="$2[$j]" printf -v "$ref" %s "${!ref}${COMP_WORDS[i]}" # Indicate new cword [[ $i == $COMP_CWORD ]] && printf -v "$3" %s "$j" # Remove optional whitespace + word separator from line copy line=${line#*"${COMP_WORDS[$i]}"} # Start new word if word separator in original line is # followed by whitespace. [[ $line == [[:blank:]]* ]] && ((j++)) # Indicate next word if available, else end *both* while and # for loop (( $i < ${#COMP_WORDS[@]} - 1)) && ((i++)) || break 2 done # Append word to current word ref="$2[$j]" printf -v "$ref" %s "${!ref}${COMP_WORDS[i]}" # Indicate new cword [[ $i == $COMP_CWORD ]] && printf -v "$3" %s "$j" # Remove optional whitespace + word separator from line copy line=${line#*"${COMP_WORDS[$i]}"} # Start new word if word separator in original line is # followed by whitespace. [[ $line == [[:blank:]]* ]] && ((j++)) # Indicate next word if available, else end *both* while and # for loop (( $i < ${#COMP_WORDS[@]} - 1)) && ((i++)) || break 2 done # Append word to current word ref="$2[$j]" printf -v "$ref" %s "${!ref}${COMP_WORDS[i]}" # Remove optional whitespace + word from line copy line=${line#*"${COMP_WORDS[i]}"} # Indicate new cword [[ $i == $COMP_CWORD ]] && printf -v "$3" %s "$j" done [[ $i == $COMP_CWORD ]] && printf -v "$3" %s "$j" else # No, list of word completions separators hasn't changed; for i in ${!COMP_WORDS[@]}; do printf -v "$2[i]" %s "${COMP_WORDS[i]}" done fi } A: local is a reserved keyword which is used extensively in many Bash completion packages, and generally in Bash code with functions. You really don't want to override it because that will break those packages. Call your alias something else. (Maybe also don't use an alias at all - shell functions are much more versatile - but that doesn't change the substance of your problem.) A: local is a shell builtin. You can see this from type local After your alias it has become a cd. The same type command will now give local is aliased to `cd /mnt/c/Users/NYCZE/OneDrive/' Now, line 295 in my /usr/share/bash-completion/bash_completion file is local cword words=() So, local is no longer behaving as expected by that file. The line in your file similarly uses local.
{ "language": "en", "url": "https://stackoverflow.com/questions/57168201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL error - trigger/function may not see it I was working on my project, here I got this error while inserting some values in a row: ERROR at line 1: ORA-04091: table SYSTEM.PRODUCTS is mutating, trigger/function may not see it ORA-06512: at "SYSTEM.PROD_TOTAL", line 2 ORA-04088: error during execution of trigger 'SYSTEM.PROD_TOTAL' This is my insert statement: insert into products values (1, 1001, 'Medical', 20, 4, 1, 1, 1); Products table : create table Products ( ProdId number primary key, ProdNum number not null unique, ProdType varchar2(15), ProdPrice int, ProdQuantity int, ProdCustId int references Customers, ProdOrdId int references Orders, ProdStoreId int references Stores ); Trigger code: create trigger PROD_TOTAL after insert ON Products for each row begin update Payments set ProdTotal = (select Products.ProdPrice * Products.ProdQuantity from Products); end; / And finally my Payment table: create table Payments ( PayId int primary key, PayDate date, ProdTotal int, FinalTotal int, PayOrdId int references orders, PayProdId int references Products, PayCustId int references Customers ); I don't know why I am getting this error, please help me in solving this issue... A: A statement level trigger (i.e. without FOR EACH ROW clause) will update always all records in Payments table, I don't think that's needed. For an update of only related products, use this trigger: create trigger PROD_TOTAL after insert ON Products for each row begin update Payments set ProdTotal = :new.ProdPrice * :new.ProdQuantity WHERE PayProdId = :new.ProdId ; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/65857565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to set options with PHP WkHtmlToPdf I try to use WkHtmlToPdf with Php using Michael Härtl wrapper called PHP WkHtmlToPdf but i can't declare any options. This code works fine use mikehaertl\wkhtmlto\Pdf; $pdf = new Pdf('http://www.example.com'); $pdf->binary ='/usr/local/bin/wkhtmltopdf'; if (!$pdf->send('pres.pdf')) { throw new Exception('Could not create PDF: '.$pdf->getError()); } Now if I try to set options I get a blank page $globaloptions = array( 'no-outline', 'encoding' => 'UTF-8', 'orientation' => 'Landscape', 'enable-javascript' => true ); use mikehaertl\wkhtmlto\Pdf; $pdf = new Pdf('http://www.example.com'); $pdf->setOptions($globaloptions); $pdf->binary ='/usr/local/bin/wkhtmltopdf'; if (!$pdf->send('pres.pdf')) { throw new Exception('Could not create PDF: '.$pdf->getError()); } A: Have you tried: $globaloptions = array( 'no-outline', 'encoding' => 'UTF-8', 'orientation' => 'Landscape', 'enable-javascript');
{ "language": "en", "url": "https://stackoverflow.com/questions/29066239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ds, es register I disassembled certain binary file(Linux elf). And I found this code : movsl %ds:(%esi),%es:(%edi) There are two registers 'ds' and 'es'. I know these are named 'Segment Register'. But, there isn't lines like 'mov addr, %es (or %ds)'. Where these registers point to ? A: The segment registers get initialized by the OS. For most modern OSes they point to the same Segment that is referring to the whole address-space, as most OSes use a Flat Memory model (i.e. no segmentation). The reason for not using only ds (the default for almost all memory accesses) here is that the operands for movs are implicit, and made sense in times of DOS. In times of DOS (Real Mode), there was an actual use of them, since registers where limited to 16Bit and so limited to 64K of address-space. The address space(1M) was divided into overlapping 64K segments.
{ "language": "en", "url": "https://stackoverflow.com/questions/9789652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Symfony try project in prod environment leads me to an error I was trying to run my project for the first time in a production environment I did not go how I expected. After following the instructions from here https://symfony.com/doc/current/deployment.html I got an error in my localhost/Symfony/web/app_dev.php page : ClassNotFoundException: Attempted to load class "SensioGeneratorBundle" from namespace "Sensio\Bundle\GeneratorBundle" in D:\logiciel\wamp\www\Symfony\app\AppKernel.php line 28. Do you need to "use" it from another namespace? Is it possible that composer made a mistake or something? I really don't know how to solve this A: I had the same problem and solved it by doing: export SYMFONY_ENV=prod A: To clarify, running composer update really solve the problem. A: It may be a bit out of scope, but I would like to add to Pogus's answer that if you are using Ansible for running composer, you have to provide this env variable like this: - name: "Install your app dependencies" composer: command: install no_dev: yes optimize_autoloader: yes working_dir: "/your/app/dir" environment: # <---- here SYMFONY_ENV: prod # <---/ ...or in a similar way, read the Ansible environment variables docs for details. Setting it places like /etc/profile.d/set-symfony-env-to-prod.sh scripts will be used by programs running on your server, but NOT by Ansible.
{ "language": "en", "url": "https://stackoverflow.com/questions/27008788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Use a constructor expression to create the DTO directly I want to implement DTO mapping after SQL query execution with JOIN: Query: public List<Businesses> findCompaniesBusinessesById(Integer id) { String hql = "SELECT bus FROM " + Businesses.class.getName() + " bus " + " INNER JOIN " + Companies.class.getName() + " comp " + " ON comp.id = bus.company_id " + " WHERE bus.business_owner_id = :id " + " AND bus.business_owner_type = 'Merchant' " + " ORDER BY bus.id ASC"; TypedQuery<Businesses> query = entityManager.createQuery(hql, Businesses.class).setParameter("id", id); List<Businesses> businesses = query.getResultList(); return businesses; } Entity Companies: @Entity @Table(name = "companies") public class Companies implements Serializable { @Id @Column(name = "id", unique = true, updatable = false, nullable = false) private int id; @Column(length = 255) private String name; @Column @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime created_at; @Column @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime updated_at; ... public Companies(String name) { super(); this.name = name; } } Entity Businesses: @Entity @Table(name = "businesses") public class Businesses { @Id @Column(name = "id", unique = true, updatable = false, nullable = false) private int id; @Column(length = 4) private Integer business_owner_id; @Column(length = 255) private String business_owner_type; @Column(length = 4) private Integer company_id; @Column @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime created_at; @Column @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime updated_at; ....... } !NOTE! In Businesses entity we don't have attribute name by design. DTO: public class BusinessesDTO { private Integer id; private String name; ....... } !NOTE! In BusinessesDTO we expect name by design and we want to map it. DTO Mapping: @Mapper(config = BaseMapperConfig.class) public interface BusinessesMapper { BusinessesDTO toDTO(Businesses company); ..... } Result from the query: As you can see there is a column name. I tried to use this code to get the mapping: @Autowired private BusinessesMapper businesses_mapper; List<BusinessesDTO> list = null; try { list = StreamSupport.stream(merchantService.findCompaniesBusinessesById(id).spliterator(), false) .map(businesses_mapper::toDTO) .collect(Collectors.toList()); } catch (Exception e) { e.printStackTrace(); } String joinedList = list.stream() .map(BusinessesDTO::getName) .collect(Collectors.joining(", ")); I tried to implement constructor expression to create the DTO directly like this: public List<Businesses> findCompaniesBusinessesById(Integer id) { String hql = "SELECT org.datalis.plugin.entity.Companies(comp.name) FROM " + Businesses.class.getName() + " bus " + " INNER JOIN " + Companies.class.getName() + " comp " + " ON comp.id = bus.company_id " + " WHERE bus.business_owner_id = :id " + " AND bus.business_owner_type = 'Merchant' " + " ORDER BY bus.id ASC"; TypedQuery<Businesses> query = entityManager.createQuery(hql, Businesses.class).setParameter("id", id); Do you know what is the proper wya to use constructor? java.lang.IllegalArgumentException: org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'org.datalis.plugin.entity.Companies' {originalText=org.datalis.plugin.entity.Companies} \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'companies1_.name' {propertyName=name,dereferenceType=PRIMITIVE,getPropertyPath=name,path=comp.name,tableAlias=companies1_,className=org. plugin.entity.Companies,classAlias=comp} +-[ALIAS_REF] IdentNode: 'companies1_.id' {alias=comp, className=org.datalis.plugin.entity.Companies, tableAlias=companies1_} \-[IDENT] IdentNode: 'name' {originalText=name} [SELECT org.datalis.plugin.entity.Companies(comp.name) FROM org.datalis.plugin.entity.Business
{ "language": "en", "url": "https://stackoverflow.com/questions/56496329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update Customer Information messages in Drupal :: Ubercart i recently installed Ubercart module and manged to configure most of the shopping cart. One of the issues i am having is finding a place to update the Customer Information message "Enter a valid email address for this order or click here to login with an existing account and return to checkout." to whatver i want. Could not figure out where i can find this piece of text so that i can update it. This message is appearing on /cart/checkout page: http://<<site>>/cart/checkout Any help would be very much appreciated. A: Oooold question, I know, but I did it with the following: In a custom module, you can add it to _form_alter, i.e. function mymodule_form_alter((&$form, $form_state, $form_id) { $form['panes']['customer']['primary_email']['#description'] = t('Your custom message goes here.'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/3614117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can't I display the result of this mysql query in PHP? $query = mysql_query("SELECT sum(rating) FROM stars WHERE post_id = 20"); echo $query; It outputs: Resource id #3 instead of 8, which is what the actual sum is. A: Try the below. mysql_query returns a 'resource' that represents the resultset, and to get values you need to use one of the mysql_fetch_ functions. $row = mysql_fetch_array($query); echo $row[0]; A: $query, after executing the query doesn't have just a number. It'll have a Resource just like any other query you would execute. In order to actually get the result, treat it like you would treat any other resource: $result = mysql_fetch_array($query); echo $result[0]; A: $result = mysql_fetch_array($query); echo $result[0]; A: As mentioned before, this is because the variable is a resource. Visit this link to learn more about PHP variable types. It is only possible to echo strings or types that can be cast to strings. Such as int, float and objects implementing the __toString magic function.
{ "language": "en", "url": "https://stackoverflow.com/questions/3535483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change UIButton BorderColor in Storyboard I Set CornerRadius and BorderWidth for UIbutton in User Defined Runtime Attributes. Without adding layer.borderColor it works Well and Display border in black color. But when add layer.borderColor does not work(does not show border). A: I got answer. Change borderColor instead of layer.borderColor: and add this code in .m file: #import <QuartzCore/QuartzCore.h> @implementation CALayer (Additions) - (void)setBorderColorFromUIColor:(UIColor *)color { self.borderColor = color.CGColor; } @end Tick properties in Attribute Inspector A: The explanation, perhaps being lost in some of the other answers here: The reason that this property is not being set is that layer.borderColor needs a value with type CGColor. But only UIColor types can be set via Interface Builder's User Defined Runtime Attributes! So, you must set a UIColor to a proxy property via Interface Builder, then intercept that call to set the equivalent CGColor to the layer.borderColor property. This can be accomplished by creating a Category on CALayer, setting the Key Path to a unique new "property" (borderColorFromUIColor), and in the category overriding the corresponding setter (setBorderColorFromUIColor:). A: Swift 4, Xcode 9.2 - Use IBDesignable and IBInspectable to build custom controls and live preview the design in Interface Builder. Here is a sample code in Swift, place just below the UIKit in ViewController.swift: @IBDesignable extension UIButton { @IBInspectable var borderWidth: CGFloat { set { layer.borderWidth = newValue } get { return layer.borderWidth } } @IBInspectable var cornerRadius: CGFloat { set { layer.cornerRadius = newValue } get { return layer.cornerRadius } } @IBInspectable var borderColor: UIColor? { set { guard let uiColor = newValue else { return } layer.borderColor = uiColor.cgColor } get { guard let color = layer.borderColor else { return nil } return UIColor(cgColor: color) } } } If you go to the Attributes inspectable of the view, you should find these properties visually, edit the properties: The changes are also reflected in User Defined Runtime Attributes: Run in build time and Voila! you will see your clear rounded button with border. A: For Swift: Swift 3: extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } } Swift 2.2: extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(CGColor: layer.borderColor!) } set { layer.borderColor = newValue?.CGColor } } } A: This works for me. Swift 3, Xcode 8.3 CALayer extension: extension CALayer { var borderWidthIB: NSNumber { get { return NSNumber(value: Float(borderWidth)) } set { borderWidth = CGFloat(newValue.floatValue) } } var borderColorIB: UIColor? { get { return borderColor != nil ? UIColor(cgColor: borderColor!) : nil } set { borderColor = newValue?.cgColor } } var cornerRadiusIB: NSNumber { get { return NSNumber(value: Float(cornerRadius)) } set { cornerRadius = CGFloat(newValue.floatValue) } } } A: There is a much better way to do this! You should use @IBInspectable. Check out Mike Woelmer's blog entry here: https://spin.atomicobject.com/2017/07/18/swift-interface-builder/ It actually adds the feature to IB in Xcode! Some of the screenshots in other answers make it appear as though the fields exist in IB, but at least in Xcode 9 they do not. But following his post will add them. A: In case of Swift, function doesn't work. You'll need a computed property to achieve the desired result: extension CALayer { var borderColorFromUIColor: UIColor { get { return UIColor(CGColor: self.borderColor!) } set { self.borderColor = newValue.CGColor } } } A: You have set the data values for the radius and the width set to be a string, but it should properly be to be set to a number, not a string When you get it working, this will not be visible while looking at the storyboard, but will be when the app is running unless you have taken steps to make it @IBDesigneable.
{ "language": "en", "url": "https://stackoverflow.com/questions/28854469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "86" }
Q: How to subtract the result of a query with a result of another query in c# linq? I want to get records from investment and calculate the sum of Amount from investment_Line where investment_Line.ParentID==investment.Investment. Subtract the Amount Calculte==d.Amount-Answer var a = (from investment in _entities.Investments where investment.StatusID == 4 select new { RefNo = investment.RefNo, InvestedAmount = investment.InvestedAmount, Amount = investment.InvestedAmount + investment.ProfitAmount, InvestmentID = investment.ID, UserID = investment.UserID, StatusID = investment.StatusID, }).ToList(); if (a.Count() != 0) { foreach (var row in a) { var count = (_entities.Investment_Line.Where(x => x.ParentID == row.InvestmentID)).Count(); if(count != 0) { var _group = _entities.Investment_Line.Where(x => x.ParentID == row.InvestmentID).GroupBy(g => g.ParentID).Select(s => new { SumAmount = s.Sum(sum => sum.Amount) }); double answer = double.ConvertToDouble(_group.Select(x => x.SumAmount)); var data = (from d in a select new Search.ReadyInvestmentList { RefNo = d.RefNo, InvestedAmount = d.InvestedAmount, TotalAmount = d.Amount, InvestmentID = d.InvestmentID, UserID = d.UserID, StatusID = d.StatusID, Calculate = d.Amount-answer }).ToList(); } } } Investment table +---+--------------------------+--------+-------------+----------------+--------+-------------+----------+ |ID | CreateDate | UserID | RefNo | InvestedAmount | Growth%| ProfitAmount|StatusID | +---+--------------------------+--------+-------------+----------------+--------+-------------+----------+ |1 | 2017-01-11 16:39:06.483 | 1 | BPWM57G2Q2 | 20000 | 30 | 6000 | 4 | |2 | 2017-01-11 16:49:18.850 | 2 | BPWM56H2T0 | 10000 | 30 | 3000 | 4 | |3 | 2017-01-11 17:15:02.667 | 3 | BPWM56G2L0 | 500 | 30 | 1500 | 1 | |4 | 2017-01-12 20:22:02.160 | 5 | BPWM68L2I0 | 500 | 30 | 150 | 2 | |5 | 2017-01-12 20:25:03.160 | 5 | BPWM63F2I5 | 2000 | 30 | 600 | 4 | +---+--------------------------+--------+-------------+----------------+--------+-------------+----------+ Investment_Line table +----+-------------+-----------+-----------+-------+------------+-----------+ | ID | InvestmentID| InvestorID| AssistorID| Amount| RefNo | ParentID | +----+-------------+-----------+-----------+-------+------------+-----------+ | 1 | 2 | 2 | 1 | 10000 | BPWM56H2T0 | 1 | | 2 | 3 | 3 | 1 | 5000 | BPWM56G2L0 | 1 | | 3 | 4 | 5 | 3 | 500 | BPWM68L2I0 | 3 | +----+-------------+-----------+-----------+-------+------------+-----------+ Required Output +----+---------+-----------+-------+---------------+------------+-----------+ | InvestmentID | RefNo | UserID| InvestedAmount| TotalAmount| Calculate | +--------------+--------------------+--------------+------------+-----------+ | 1 | BPWM57G2Q2| 1 | 20000 | 26000 | 15000 | | 2 | BPWM56H2T0| 2 | 10000 | 13000 | 0 | | 5 | BPWM63F2I5| 5 | 2000 | 2600 | 0 | +----+---------+-----------+-------+-------------- +------------+-----------+ What is the best way to do this? Please help. A: Your code will have bad performance if there will be many records in master detail table. Because you will have masterRecordCount * DetailRecordCount nested loop. So it will be better if you group and join in one query var calculatedlist = from I in _entities.Investments join IL in _entities.Investment_Line on I.ID equals IL.ParentID group IL by new { I.ID } into g select new { InvestmentID = g.Key, RefNo = g.Max(m => m.I.RefNo), UserID = g.Max(m => m.I.UserID) , InvestedAmount = g.Max(m => m.I.InvestedAmount) , TotalAmount = g.Max(m => m.I.InvestedAmount) + g.Max(m => m.I.ProfitAmount), Calculate = g.Max(m => m.I.InvestedAmount) + g.Max(m => m.I.ProfitAmount) - g.Sum(m => m.IL.Amount) };
{ "language": "en", "url": "https://stackoverflow.com/questions/41752992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: access vba hperling wont work Dim dbs As DAO.Database Dim rst As DAO.Recordset Set dbs = CurrentDb Set rst = dbs.OpenRecordset("יומן תקלות") Dim str As String rst.MoveFirst Do Until rst.EOF If IsNull(rst!אישור) Then str = rst![מס' תקלה] rst.Edit rst!אישור = "C:\test\pic\" + str + ".jpg" rst.Update End If rst.MoveNext Loop i have this code and it work perfect but when im trying to press the hyperlink nothing heppned the path is ok and also the file name i tried to rightClick->hyperling->open hyperling and nothng also please help me A: If clicking the link throws an error, it is because the link provided is incorrect, but since nothing happens, the problem is probably caused by a wrong datatype in your table. Go to the design view of your table, and set the datatype to Hyperlink.
{ "language": "en", "url": "https://stackoverflow.com/questions/27819719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setstate completes after even thou it's in a .then I'm very confused on this. I know it has to do with the async nature but I'm not able to get this to function the way I need it to. I need the firebase.set to run. When that is completed then this.setstate to run, once that is completed the next then to run. .then(keyUid => { let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]}; this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set( { first: firstHousehold, last: lastHousehold, phone: phone, email: email, address: address, address2: address2, city: city, zip: zip, headOfHousehold: headOfHousehold, }, (error) => { if(error){ console.log(error); } else{ this.setState({ family: updatedFamily }, () => console.log(1)); } }) }) .then(newHouseholdUid => { console.log(2); Object.keys(family).forEach(key => { this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + key ).update({ family: 'howdly' }) }); }) Currently console.log(2) runs BEFORE console.log(1). I would expect for this.setstate to resolve before it moves on to the next .then How can achieve this? A: React batches state updates for performance reasons. In your case the state you are setting to updatedFammily, you can use a locally scoped object to get the intermediate results let res = {} ... .then(keyUid => { let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]}; res.updatedFamily = updatedFamily; this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set( { first: firstHousehold, last: lastHousehold, phone: phone, email: email, address: address, address2: address2, city: city, zip: zip, headOfHousehold: headOfHousehold, }, (error) => { if(error){ console.log(error); } else{ this.setState({ family: updatedFamily }, () => console.log(1)); } }) }) .then(() => { console.log(2); Object.keys(res.updatedFamily).forEach(key => { this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + key ).update({ family: 'howdly' }) }); }) You can also use async await to get around this but that would require changing bit more, Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/58334588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete a key/value pair from an unordered_map C++ I have two questions. First I have an std::unordered_map<int,Object*> where Object looks like this: // Object.hpp class Object { public: Object(); ~Object(){}; int Id(); void setId(int i); private: int id; }; This unordered_map is put in a class called DataSet which is used as a container to hold all of these objects. In DataSet I want to be able to properly erase a key/value pair given an integer id from Object. To do this I tried to create an iterator that finds the key by id, and then deletes the pointer to the iterator, and finally erases the key/value pair. It looks like this: int DataSet::deleteObject(int id) { std::unordered_map<int,Object*>::iterator found_it = objects.find(id); if(found_it != objects.end()) { delete *found_it; objects.erase(found_it); } return 1; } However, when I compile it I get this error: dataset.cpp:44:9: error: cannot delete expression of type 'value_type' (aka 'pair<key_type, mapped_type>') delete *found_it; Is there a correct way to erase the Object at that location? Second, when writing a clear() method, I realize I can't just do objects.clear(), so I was wondering if there was a way to actually clear the unordered_map. For example when I used a std::vector I was able to do this: std::vector<Object *>::reverse_iterator object; for(object = objects.rbegin(); object < objects.rend(); object++) delete(*object); objects.clear(); But that won't work now for an unordered_map, so what is the right way to do this? The requirements that I am under make it so I can't change Object, or how the unordered_map is set up. A: The first part of the question is quite simple: the iterator reference the value and a given location which is of type std::pair<int const, Object*>. You can't delete such an object. You'll get the pointer using the second part of the object, e.g.: delete found_it->second; However, it is actually quite uncommon and error-prone to take care of this kind of maintenance. You are much better off not storing an Object* but rather a std::unique_ptr<Object>: the std::unique_ptr<Object> will automatically release the object upon destruction. That would also simplify removing an element: int DataSet::deletObject(int id) { return objects.erase(id); } When storing std::unique_ptr<Object> you'll probably need to be a bit more verbose when inserting elements into the container, though, e.g.: objects.insert(std::make_pair(key, std::unique_ptr<Object>(ptr))); Given that your Object class doesn't have any virtual functions you could probably just store an Object directly, though: std::unordered_map<int, Object> objects; A: Dereferencing an unordered_map::iterator produces a unordered_map::value_type&, i.e. pair<const Key, Value>&. You want delete found_it->second; objects.erase(found_it); Stepping back a bit, are you sure you even need std::unordered_map<int,Object*> instead of std::unordered_map<int,Object>? If you use the latter you wouldn't have to worry about deleteing anything. If you do need the mapped_type be an Object* you should use std::unordered_map<int,std::unique_ptr<Object>>. Again, this makes it unnecessary to manually delete the values before erasing an entry from the map. Also, if Object is the base class for whatever types you're going to be adding to the map, don't forget that it needs a virtual destructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/29178127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CUDA atomicAdd failed The following CUDA kernel is supposed to do image slices addition for an 3D image, i.e., you collapse the 3D volume along one dimension and produce one 2D image through doing pixel-wise additions. The image_in data pointer has size 128 * 128 * 128, which was obtained from an ITK::Image using the function GetOutputBuffer(). After reading the ITK documentation, I think we can safely assume that the data pointer points to an segment of continuous memory of the image data, without padding. The image_out is just a 2D image of size 128 * 128, also produced from an ITK::Image. I included the info about the images just for completeness but the question is more about CUDA atomic and might be very elementary. The code compute the thread id first and project the id into the range of 128 * 128, which means all pixels in the same line along the dimension we perform addition will have the same idx. Then using this idx, atomicAdd was used to update the image_out. __global__ void add_slices(int* image_in, int* image_out) { int tid = threadIdx.x + blockIdx.x * blockDim.x; int idx = tid % (128 * 128); int temp = image_in[tid]; atomicAdd( &image_out[idx], temp ); } The way I initialized the image_out is through the following, there are two ways I tried with the similar results: int* image_out = new int[128 * 128]; for (...) { /* assign image_out to zeros */ } and the one using ITK interface: out_image->SetRegions(region2d); out_image->Allocate(); out_image->FillBuffer(0); // Obtain the data buffer int* image_out = out_image->GetOutputBuffer(); Then I setup CUDA as the following: unsigned int size_in = 128 * 128 * 128; unsigned int size_out = 128 * 128; int *dev_in; int *dev_out; cudaMalloc( (void**)&dev_in, size_in * sizeof(int) ); cudaMalloc( (void**)&dev_out, size_out * sizeof(int)); cudaMemcpy( dev_in, image_in, size_in * sizeof(int), cudaMemcpyHostToDevice ); add_slices<<<size_in/64, 64 >>>(dev_in, dev_out); cudaMemcpy( image_out, dev_out, size_out * sizeof(int), cudaMemcpyDeviceToHost); Is there any problem to the above code? The reason why I am seeking help here comes from the frastration that the above code sometimes might produce the right result (once every 50 times I run the code, maybe, I swear I have seen the correct result at least twice), while the rest of the time just produced some garbages. Does the issue comes from the atomicAdd() function? At the beginning my image type was of double, which CUDA doesn't support atomicAdd(double*, double) so I used the code provided by Nvidia as the following __device__ double atomicAdd(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int*)address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __double_as_longlong(val + __longlong_as_double(assumed))); } while (assumed != old); return __longlong_as_double(old); } Then just for testing purpose I switched all my image to int then the situation was still the same that most of the time garbages while once in a blue moon correct result. Do I need to turn on some compiling flag? I am using CMAKE to build the project using find_package(CUDA QUIET REQUIRED) for the CUDA support. The following is the way I setup the CUDA_NVCC_FLAGS set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -arch=sm_30"), maybe I missed something? Any suggestion will be greatly appreciated and I will update the question if more info of the code is needed. A: So it turns out that the solution to this problem is adding the following line to initialize the memory pointed by dev_out. cudaMemcpy( dev_out, image_out, size_out * sizeof(int), cudaMemcpyHostToDevice ); I forgot to initialize it since I was thinking that it is a output variable and I initialized it on the host. Just like that talonmies said, it has nothing to do with atomicAdd at all. Both int version and double version of atomicAdd works perfectly. Just remember to initialize your variable on device.
{ "language": "en", "url": "https://stackoverflow.com/questions/36417066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET Core 2.1 Referring to ApplicationDbContext from Class Library I have these 2 projects App.ClassLibrary and App.Data I followed this tutorial https://garywoodfine.com/using-ef-core-in-a-separate-class-library-project/ to move my migrations and models to App.ClassLibrary. One of those steps was to create an ApplicationDbContext in the class library: public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Users> Users { get; set; } public DbSet<UserRoles> UserRoles { get; set; } public DbSet<Applications> Applications { get; set; } public DbSet<Roles> Roles { get; set; } public DbSet<EventLogs> EventLogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema(schema: DatabaseGlobals.SchemaName); modelBuilder.Entity<Users>(); modelBuilder.Entity<UserRoles>(); modelBuilder.Entity<Applications>(); modelBuilder.Entity<Roles>(); modelBuilder.Entity<EventLogs>(); base.OnModelCreating(modelBuilder); } public override int SaveChanges() { Audit(); return base.SaveChanges(); } public async Task<int> SaveChangesAsync() { Audit(); return await base.SaveChangesAsync(); } private void Audit() { var entries = ChangeTracker.Entries().Where(x => x.Entity is Users && (x.State == EntityState.Added || x.State == EntityState.Modified)); foreach (var entry in entries) { if (entry.State == EntityState.Added) { ((Users)entry.Entity).CreatedOn = DateTime.UtcNow; } ((Users)entry.Entity).UpdatedOn = DateTime.UtcNow; } } } In App.Data, I am trying to reference ApplicationDbContext but so far this isn't working private ApplicationDbContext dbContext = new ApplicationDbContext(); I used to have a similar project in ASP.NET MVC 5 with an ApplicationDBContext like this: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public virtual DbSet<AspNetUsersExtendedDetails> AspNetUsersExtendedDetails { get; set; } public virtual DbSet<AspNetApplications> AspNetApplications { get; set; } public virtual DbSet<AspNetEventLogs> AspNetEventLogs { get; set; } public virtual DbSet<AspNetRolesExtendedDetails> AspNetRolesExtendedDetails { get; set; } public virtual DbSet<AspNetUserRolesExtendedDetails> AspNetUserRolesExtendedDetails { get; set; } public virtual DbSet<AspNetUserAccessTokens> AspNetUserAccessTokens { get; set; } public ApplicationDbContext() : base("ManagementStudio") { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } I could use private ApplicationDbContext dbContext = new ApplicationDbContext(); without any issues but now I'm guessing because of the different versions and framework its not working. Not sure what I can do to get the dbcontext. EDIT: This is the error I get in my .Net Core 2.1 App There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions)' A: Your DbContext is fine, but you have to register it with dependency injection and inject it into your classes instead of using new. Your startup.cs ConfigureServices method should have your database with the connection string. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); Then, on the classes you want to use them (like a Controller) you inject it into the constuctor. public class HomeController : Controller { private readonly ApplicationDbContext _db; public HomeController(ApplicationDbContext db) { _db = db; } } A: Your ApplicationDbContext should be: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public virtual DbSet<AspNetUsersExtendedDetails> AspNetUsersExtendedDetails { get; set; } public virtual DbSet<AspNetApplications> AspNetApplications { get; set; } public virtual DbSet<AspNetEventLogs> AspNetEventLogs { get; set; } public virtual DbSet<AspNetRolesExtendedDetails> AspNetRolesExtendedDetails { get; set; } public virtual DbSet<AspNetUserRolesExtendedDetails> AspNetUserRolesExtendedDetails { get; set; } public virtual DbSet<AspNetUserAccessTokens> AspNetUserAccessTokens { get; set; } public ApplicationDbContext(DbContextOptions options) : base(options) { } } And your should register it like that, depending on the DB server you use, for SqlServer: services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbContext"))
{ "language": "en", "url": "https://stackoverflow.com/questions/52557962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between physical and programmatically click on ListView I am clicking ListView item programmatically on onCreate method like below: // setting listener for ListView item click listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { changeView(i); } }); // Clicking ListView first position programmatically. listview.performItemClick(listview.getChildAt(0), 0, listview.getAdapter().getItemId(0)); In above code when i debug the code changeView(i); is calling properly for both programmatic and physical click. I am using changeView() to change colour of ListView item views (TextView and ImageView) like below: private void changeView(int position) { for (int i = 0; i < adapter.getCount(); i++) { View v = getViewByPosition(i, listview); ImageView imgIcon = (ImageView) v.findViewById(R.id.icon); TextView txtTitle = (TextView) v.findViewById(R.id.title); if (i == position) { imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.app_red)); txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.app_red)); } else { imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.colorWhite)); txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.colorWhite)); } } lvSlideMenu.setItemChecked(position, true); lvSlideMenu.setSelection(position); } Where getViewByPosition() method is used to get view of ListView item: public View getViewByPosition(int pos, ListView listView) { final int firstListItemPosition = listView.getFirstVisiblePosition(); final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1; if (pos < firstListItemPosition || pos > lastListItemPosition) { return listView.getAdapter().getView(pos, null, listView); } else { final int childIndex = pos - firstListItemPosition; return listView.getChildAt(childIndex); } } PROBLEM : Above code is changing colour of TextView and ImageView of list item when i click physically (by hand) but not programmatically. Thanks in advance. A: Try sending view in chnageView() changeView(view); And in chnageView() ImageView imgIcon = (ImageView) v.findViewById(R.id.icon); TextView txtTitle = (TextView) v.findViewById(R.id.title); A: Analyzing the code, I can deduce that, when you are changing color programmatically and changeView() is called, your color change code part is not executed : for (int i = 0; i < adapter.getCount(); i++) { View v = getViewByPosition(i, listview); ImageView imgIcon = (ImageView) v.findViewById(R.id.icon); TextView txtTitle = (TextView) v.findViewById(R.id.title); if (i == position) { imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.app_red)); txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.app_red)); } else { imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.colorWhite)); txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.colorWhite)); } } Can you please check if for block is executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/41477692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kafka commits transaction after LeaveGroup due to max.poll.interval.ms is exceeded I am using transaction in kafka. I have provided my consumer container with a ChainedKafkaTransactionManager which consist of JpaTransactionManager and KafkaTransactionManager. I am trying to learn how transactions are affected when a consumer is stuck and therefore send LeaveGroup and disables heartbeat thread. I have set max.poll.interval.ms to 10 seconds. I have not changed session.timeout.ms. It is 10 seconds per default. I have two applications with one consumer each. Both consumers are transactional. Consumer A is rigged to process for 30 seconds and Consumer B process it within 1 second. Both consumers read from the same topic, which as 3 partitions. * *Send a record to Kafka *Consumer A receives the record. *Consumer A starts to process the record. *Consumer A processing time exceed max.poll.interval.ms *Consumer A send LeaveGroup and heartbeat stops. *Kafka rebalances. All partitions are now assigned to Consumer B. *Consumer B receives the same record and process it. *Consumer B commits the transaction. *Consumer A has now finished processing(30 seconds). *Consumer A commits the transaction. *Kafka rebalances. Partitions are reassigned to both consumers. The transaction is processed and committed twice. Both consumers should be idempotent to ensure processing the same record have no consequences. My hypothesis was that Consumer A would throw an exception due to LeaveGroup and stopping the heartbeat. This is however not the case. I have tested this with unique transaction IDs and transaction ID being identical in both applications - same result. Why does Consumer A commit the transaction after LeaveGroup has been sent? I am not entirely sure if this is a bug. I have however submitted this odd behaviour or bug to Apache Kafka Log for Consumer A 2018-07-11 11:59:22.365 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Received: 1 records 2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-1, transactionalId=transactionId420] Transition from state READY to IN_TRANSACTION 2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager : Created Kafka transaction on producer [brave.kafka.clients.TracingProducer@631071b0] 2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction 2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.h.e.t.internal.TransactionImpl : begin 2018-07-11 11:59:22.367 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@4eef56f0] 2018-07-11 11:59:22.427 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] l.a.BatchMessagingMessageListenerAdapter : Processing [GenericMessage [payload=[data], headers={kafka_offset=[34], kafka_consumer=brave.kafka.clients.TracingConsumer@1484643f, kafka_timestampType=[CREATE_TIME], kafka_receivedMessageKey=[null], kafka_receivedPartitionId=[1], kafka_receivedTopic=[trans-topic], kafka_receivedTimestamp=[1531299912221], kafka_batchConvertedHeaders=[{X-B3-SpanId=[B@1e664339, X-B3-ParentSpanId=[B@73f2c38a, X-B3-Sampled=[B@5f0ca155, X-B3-TraceId=[B@68ac877c}]}]] ... 2018-07-11 11:59:30.503 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-1, groupId=mygrp42] Sending Heartbeat request to coordinator localhost:9092 (id: 2147483647 rack: null) 2018-07-11 11:59:30.608 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-1, groupId=mygrp42] Received successful Heartbeat response 2018-07-11 11:59:32.256 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-1, groupId=mygrp42] Sending LeaveGroup request to coordinator localhost:9092 (id: 2147483647 rack: null) 2018-07-11 11:59:32.256 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-1, groupId=mygrp42] Disabling heartbeat thread 2018-07-11 11:59:37.458 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Sending offsets to transaction: {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} 2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-1, transactionalId=transactionId420] Begin adding offsets {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} for consumer group mygrp42 to transaction 2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-1, transactionalId=transactionId420] Enqueuing transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42) 2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.clients.producer.internals.Sender : [Producer clientId=producer-1, transactionalId=transactionId420] Sending transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42) to node localhost:9092 (id: 0 rack: null) 2018-07-11 11:59:37.467 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-1, transactionalId=transactionId420] Successfully added partition for consumer group mygrp42 to transaction 2018-07-11 11:59:37.467 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.clients.producer.internals.Sender : [Producer clientId=producer-1, transactionalId=transactionId420] Sending transactional request (type=TxnOffsetCommitRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42, offsets={trans-topic-0=CommittedOffset(offset=408, metadata='')}) to node localhost:9092 (id: 0 rack: null) 2018-07-11 11:59:37.469 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-1, transactionalId=transactionId420] Successfully added offsets {trans-topic-0=CommittedOffset(offset=408, metadata='')} from consumer group mygrp42 to transaction. Log for Consumer B 2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Received: 1 records 2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-2, transactionalId=transactionId421] Transition from state READY to IN_TRANSACTION 2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager : Created Kafka transaction on producer [brave.kafka.clients.TracingProducer@30b6dff4] 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.h.e.t.internal.TransactionImpl : begin 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@2b0eff5d] 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] l.a.BatchMessagingMessageListenerAdapter : Processing [GenericMessage [payload=[data], headers={kafka_offset=[407], kafka_consumer=brave.kafka.clients.TracingConsumer@103b53ce, kafka_timestampType=[CREATE_TIME], kafka_receivedMessageKey=[null], kafka_receivedPartitionId=[0], kafka_receivedTopic=[trans-topic], kafka_receivedTimestamp=[1531299562360], kafka_batchConvertedHeaders=[{X-B3-SpanId=[B@38658f41, X-B3-ParentSpanId=[B@2faeb13a, X-B3-Sampled=[B@29e18244, X-B3-TraceId=[B@75496432}]}]] 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Sending offsets to transaction: {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-2, transactionalId=transactionId421] Begin adding offsets {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} for consumer group mygrp42 to transaction 2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-2, transactionalId=transactionId421] Enqueuing transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42) 2018-07-11 11:59:33.779 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.clients.producer.internals.Sender : [Producer clientId=producer-2, transactionalId=transactionId421] Sending transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42) to node localhost:9092 (id: 0 rack: null) 2018-07-11 11:59:33.780 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-2, transactionalId=transactionId421] Successfully added partition for consumer group mygrp42 to transaction 2018-07-11 11:59:33.780 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.clients.producer.internals.Sender : [Producer clientId=producer-2, transactionalId=transactionId421] Sending transactional request (type=TxnOffsetCommitRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42, offsets={trans-topic-0=CommittedOffset(offset=408, metadata='')}) to node localhost:9092 (id: 0 rack: null) 2018-07-11 11:59:33.781 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.c.p.internals.TransactionManager : [Producer clientId=producer-2, transactionalId=transactionId421] Successfully added offsets {trans-topic-0=CommittedOffset(offset=408, metadata='')} from consumer group mygrp42 to transaction.
{ "language": "en", "url": "https://stackoverflow.com/questions/51284626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }