text
stringlengths
15
59.8k
meta
dict
Q: Google Apps Script refresh sheet while function is running I have some script in my Google Sheets/ It can take a lot of time to finish all this script (up to 5 minutes I think). And I want to show some message that user should just wait a little. So I have some code like: function test(){ var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var cell = sheet.getRange("A1"); sheet.clear(); cell.setValue('WAIT!!!!'); DATA = UrlFetchApp.fetch(url); // And some action that takes a lot of time .... cell.setValue('DONE!!!!'); But it doesn't show "WAIT" it only shows me "DONE" when everything is ok. It can only show me "WAIT" if there was any error and function crashed. It looks like I need to refresh it somehow. A: Call the flush()method after you set the cell value to wait. SpreadsheetApp.flush(); //Applies all pending Spreadsheet changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/42256376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: IE11 moves cursor to beginning of input when editing value I have a really odd problem on a project. Long Story Short, I have input fields that record interest rate, so a % is appended on blur and removed on focus. It works fine on every browser except for IE11. For some reason, it moves the cursor to the beginning of the input, which is annoying for people tabbing through and typing in values quickly. Here is a simplified example in: $('#test').val('default'); $('#test').focus(function() { var value = $(this).val().slice(0, -1); $(this).val(value); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test" /> Again, this only happens in IE11 (works fine in older versions of IE). Has anyone run into this issue before? I tried forcing focus again after the value is reassigned, but that didn't solve the issue. Any tips are appreciated. A: You could try to set caret position manually when appending/removing % mark, using those two functions (those are pretty generic and should work for every browser if you need setting caret positions for all browsers some other time): function getCaretPosition(element) { var caretPos = 0; if (element.type === 'text' || element.type === 'tel') { if (document.selection) { // IE Support element.focus(); var Sel = document.selection.createRange(); Sel.moveStart('character', -element.value.length); caretPos = Sel.text.length; } else if (element.selectionStart || element.selectionStart === '0') {// Firefox support caretPos = element.selectionStart; } } return caretPos; } function setCaretPosition(element, position) { if (element.type === 'text' || element.type === 'tel') { if (element.setSelectionRange) { element.focus(); element.setSelectionRange(position, position); } else if (element.createTextRange) { var range = element.createTextRange(); range.collapse(true); range.moveEnd('character', position); range.moveStart('character', position); range.select(); } } } And call them only when using IE11 :) Also, if you want, you could make those functions more specific, removing parts for FF :) A: This issue can be solved by: * *getting a reference to the input element *adding an onfocus event handler Then setting the selection range in the onfocus handler to the end of the input value, like so: const onFocus = (el) => { const { value } = el.value el.setSelectionRange(value.length, value.length); } <input type='text' onfocus='onFocus(this)' /> If you are using ReactJS, here is that solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/31322576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get the constructor name in Node.js from super class I have a "super" module in my Node.js application with a constructor and some prototype functions. var parser = function(options, util, cache, url) { this.options = options; this.util = util; this.cache = cache; this.url = url; } parser.prototype.start = function() { console.log("I am a default start function"); console.log(this.constructor.name); } module.exports = parser; I have a handful of other modules that inherit from this module. Now, when i invoke the start function i would like to get the name of that module's constructor. For some reason this is not working for me. var parser = require('../parser'); var util = require('util'); var DKAN = function(options, util, cache, url) { parser.apply(this,arguments); } util.inherits(DKAN, parser); DKAN.prototype.check = function($) { var DKANParser = this; if ($('meta[content*="Drupal"]').length !== 0 ) { DKANParser.start(); return true; } else return false; } module.exports = DKAN; When invoking the DKANParser.start() i only get the first console.log with "I am a default start function" and cannot get the name of constructor whih is supposed to be DKAN
{ "language": "en", "url": "https://stackoverflow.com/questions/26131251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overwriting HDFS file/directory through Spark Problem I have a file saved in HDFS and all I want to do is to run my spark application, calculate a result javaRDD and use saveAsTextFile() in order to store the new "file" in HDFS. However Spark's saveAsTextFile() does not work if the file already exists. It does not overwrite it. What I tried So I searched for a solution to this and I found that a possible way to make it work could be deleting the file through the HDFS API before trying to save the new one. I added the Code: FileSystem hdfs = FileSystem.get(new Configuration()); Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename); if(hdfs.exists(newFolderPath)){ System.out.println("EXISTS"); hdfs.delete(newFolderPath, true); } filerdd.saveAsTextFile("/hdfs/" + filename); When I tried to run my Spark application, the file was deleted but I get a FileNotFoundException. Considering the fact, that this exception occurs when someone is trying to read a file from a path and the file does not exist, this makes no sense because after deleting the file, there is no code that tries to read it. Part of my code JavaRDD<String> filerdd = sc.textFile("/hdfs/" + filename) // load the file here ... ... // Transformations here filerdd = filerdd.map(....); ... ... // Delete old file here FileSystem hdfs = FileSystem.get(new Configuration()); Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename); if(hdfs.exists(newFolderPath)){ System.out.println("EXISTS"); hdfs.delete(newFolderPath, true); } // Write new file here filerdd.saveAsTextFile("/hdfs/" + filename); I am trying to do the simplest thing here but I have no idea why this does not work. Maybe the filerdd is somehow connected to the path?? A: The problem is you use the same path for input and output. Spark's RDD will be executed lazily. It runs when you call saveAsTextFile. At this point, you have already deleted the newFolderPath. So filerdd will complain. Anyway, you should not use the same path for input and output.
{ "language": "en", "url": "https://stackoverflow.com/questions/37284156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: lambda function does not update the reference array I have a method which basically updates each value of the passed reference array by 5. Initially I tried the below options but it wouldn't update the reference array. Option 1: void Int_Array_Update(std::vector<int>& param) { auto f1 = [](int n) { return n + 5; }; std::for_each(param.begin(), param.end(), f1); } Option 2: void Int_Array_Update(std::vector<int>& param) { auto f1 = [&](int n) { return n + 5; }; std::for_each(param.begin(), param.end(), f1); } Option 3: void Int_Array_Update(std::vector<int>& param) { auto f1 = [&param](int n) { return n + 5; }; std::for_each(param.begin(), param.end(), f1); } The workaround I have currently is as below: void Int_Array_Update(std::vector<int>& param) { for (int i = 0; i < param.size(); ++i) param[i] = param[i] + 5; } I am not able to find any answers why the lambda function is not updating the reference vector or maybe I am doing something wrong. Any help is appreciated. A: std:.for_each does not update the elements in the range the way you expect. std::for_each applies the lambda to each element, but does not care about the return value from the lambda. You want std::transform for that: std::transform(param.begin(), param.end(), param.begin(), f1); // ^^^^^^^^^^^^^ // | // it starts writing the result here To work with std::for_each you would need to receive the argument by-reference in the lambda and make the update to the argument directly instead of returning it: auto f1 = [](int& n) { n += 5; }; // int& and add to n directly std::for_each(param.begin(), param.end(), f1);
{ "language": "en", "url": "https://stackoverflow.com/questions/67383799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: phpseclib - Parse mysql query to array I do a mysql select query over ssh2 with phpseclib. I get my result back. If I add nl2br(), it's kind of readable (every row is on a seperate line). But I still can't access the columns of the rows. How can I properly parse the output of a phpseclib ssh2 mysql query into a recursive array? This is how I do my query: $output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"'); A: Doing str_replace("\t", ',', $output) would probably work. Here's how you'd get it into an associative array (not what you asked but it could prove useful to helping you understanding how the output is formatted): $output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"'); $output = explode("\n", $output); $colNames = explode("\t", $output[0]); $colValues = explode("\t", $output[1]); $cols = array_combine($colNames, $colValues);
{ "language": "en", "url": "https://stackoverflow.com/questions/27847042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AWS EBS volume attachement using snapshot I am trying with AWS EBS volume. I created an EC2 Server using the AMI rancheros-v0.7.1-hvm-1. Then I attached volume and mounted to /var/lib/docker folder. Then I run few docker images on that server and I am able to access those applications also. Later I created a snapshot of the volume. and launched another server using the same AMI and attached an EBS volume from the snapshot I created earlier and mounted to /var/lib/docker folder. After that I ssh to the second server and did docker PS. But no docker Images are running there. When I do df -kh command on first server the output was: Filesystem Size Used Available Use% Mounted on /dev/xvdb 29.4G 1.2G 26.7G 4% /var/lib/docker /dev/xvdb 29.4G 1.2G 26.7G 4% /var/lib/docker/overlay overlay 29.4G 1.2G 26.7G 4% /var/lib/docker/overlay ......... And followed by the docker images running. But when I did the same command on the second server I got the output like this: Filesystem Size Used Available Use% Mounted on /dev/xvdb 29.4G 44.1M 27.8G 0% /var/lib/docker /dev/xvdb 29.4G 44.1M 27.8G 0% /var/lib/docker/overlay No docker images running also. In both servers the use% are different. Can any one tell me how can I check both are similar, and the snapshot contains all the data in the EBS volume? If the snapshot contains the similar data in the volume, then the second server should contain the docker images. But in my case its not happening. This is the user data I gave while creating the EC2 server. #!/bin/sh sudo mkfs.ext4 /dev/xvdb mkdir -p /var/lib/docker echo "/dev/xvdb /var/lib/docker ext4 defaults 0 0" >> /etc/fstab mount /dev/xvdb /var/lib/docker -t ext4 chown -R 1000 /var/lib/docker Can anyone tell me a solution for this? A: It worked now. the server which I created from snapshot I should not create the file system. I have to remove this command sudo mkfs.ext4 /dev/xvdb from the user data. just create the folder and mount it. then it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/40630049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add text into along the object using three.js I have added text into my object (a shirt model) using a text geometry. Here is my code: var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = 'italic 18px Arial'; ctx.textAlign = 'center'; ctx. textBaseline = 'middle'; ctx.fillStyle = 'red'; ctx.fillText('Your Text', 150, 50);` My output looks like this: The text does not fit into the shirt model. If I rotate the shirt model means text showing irrelevant view. I want to fit the text into the shirt model like this: How can I fit my dynamic text into the shirt model using three.js. A: if you are searching for " How to fit a 3D text in a 3D object" I will explain how to do this, lets begin with the theory, Imagine having a flag with the form of the flag given sin(2*pi) if your camera is watching from y axis (three js axes) then you gonna add a text that exactly fits the function sin(2*pi), right? so, as you can see the idea of this is trying to get some tangets of sin(x) function, the secret of this is to cut the text in the number of tangents that will fit your text... for the text, "Montiel Software" it will be now ["Mon","tiel","Soft","Ware"] Flag: function flag(u,v,vector) { var x = 10*u; var y = 10*v; var z = Math.sin(2*Math.PI*u) ; vector.set(x,y,z);} Create the Geometry: var geometry_sin = new THREE.ParametricGeometry(flag, 100, 100); var material_sin = new THREE.MeshPhongMaterial({map:groundTexture,side:THREE.DoubleSide, color:0x000000} ); var flag = new THREE.Mesh( geometry_sin, material_sin ); Now add the text to flag (choose your tangents here) then the flag to scene: var loader = new THREE.FontLoader(); loader.load('js/examples/fonts/helvetiker_regular.typeface.json',function(font){ var geometry = new THREE.TextGeometry( 'Mon', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 0.2; txt_mesh.position.y = 5; txt_mesh.rotation.y = -Math.PI/8; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( 'tiel', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 1.2; txt_mesh.position.x = 2.5; txt_mesh.position.y = 5; txt_mesh.rotation.y = Math.PI/12; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( '$oft', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 0.28; txt_mesh.position.x = 4.5; txt_mesh.position.y = 5; txt_mesh.rotation.y = Math.PI/7; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( 'Ware', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = -1; txt_mesh.position.x = 7; txt_mesh.position.y = 5; txt_mesh.rotation.y = -Math.PI/8; flag.add(txt_mesh); } ); scene.add(flag); that's the only way I can imagine to do this in three JS, if you are just searching to make a 3D objet, I suggest you to install 3D builder and try options there then load the object to THREE js. A: Simply drawing the text to your 2D canvas will most likely never give you a satisfactory result. You have three possibilities to tackle this issue. * *Using textures loaded with a THREE.TextureLoader. * *several examples here: http://threejs.org/examples *tutorial: http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm *Using THREE.TextGeometry: * *an example: https://threejs.org/docs/index.html?q=textgeo#api/en/geometries/TextGeometry *Using a CSS3D solution. * *a nice blog post on this topic: http://learningthreejs.com/blog/2013/04/30/closing-the-gap-between-html-and-webgl/ Check also the UI example on the THREE.TextGeometry documentation page:
{ "language": "en", "url": "https://stackoverflow.com/questions/38074263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Git deployment of October CMS site I set up Git deployment for most of my sites and it work really well. I have recently started to work with October, and for main pages which I create myself, I would like to work locally and then use Git to deploy new and updated pages to the live server. It is my understanding that (apart from blog plugins for instance) October uses flat files for it's content. If I create files locally within my local install of October, can I safely Git push only the files I have worked on (html, css, js etc.) up to the site along with front matter and have them work on the remote deployment server? Will October just integrate them? A: Yes, you can use git to deploy your site content and manage it via version control. You can set your .gitignore to the following folders .DS_Store *.log /vendor /storage /plugins/october /modules/**/* /config /bootstrap /themes/demo artisan index.php .htaccess And it will upload the text/theme files you add/commit. After the git pull you might wish to do a cache refresh php artisan cache:clear or install the cache clear widget(https://octobercms.com/plugin/romanov-clearcachewidget)
{ "language": "en", "url": "https://stackoverflow.com/questions/48081778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to shrink the storage size limit of IPFS? I am using IPFS and trying to understand its structure. ISSUE: 1 The issue I am facing is that when I am trying to shrink the storage size of IPFS (for testing it is taking so long time, hence I just want to shrink File System for a while) but is unable to shrink. I tried to configure the config file by changing the StorageMax limit using this command ipfs config Datastore.StorageMax 1GB but still it does not work, it accepting (ipfs add ) the files after the 1GB also, why he is not limiting the file-storage? anyone, please suggest me How to reduce file-system size? ISSUE: 2 Even in case of IPFS's default storage limit (Which is 10 GB), I saw when I am adding the files on IPFS it is not stopping to store files after crosses 10GB (which was limit). It should not be cross after the limit ends, for this what to do? below is the config file { "API": { "HTTPHeaders": {} }, "Addresses": { "API": "/ip4/0.0.0.0/tcp/5001", "Announce": [], "Gateway": "/ip4/0.0.0.0/tcp/8080", "NoAnnounce": [], "Swarm": [ "/ip4/0.0.0.0/tcp/4001", "/ip6/::/tcp/4001" ] }, "Bootstrap": [ "/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMWUQJyrVwtbZg5gBMjTezGAJN", "/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChGNJchTbq5TbXJJ16u19uLTa", "/dnsaddr/bootstrap.libp2p.io/ipfs/QmbLHAnMoJPWSCR5Zhtx6BX9KiKNN6tpvbUcqanj75Nb", "/dnsaddr/bootstrap.libp2p.io/ipfs/QmcZf59bWwK5XFi76CZX8cbBhTzzA3gU1ZjYZcYW3dwt", "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEQAwe3N8SzbUtfsmvsqQLuvuJ", "/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2MULpjvfd3aZ6ha4oFGL1KrGM", "/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXDQVcqN88CNLHXMkTNwMKPnu", "/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZCy3U6aXMJDAbzgu2fzaDs64", "/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPakiS1J6DifTC88f5uVQKNAd", "/ip6/2604:a880:1:20::203:d001/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M7Lpjvfd3aZ6ha4oFGL1KrGM", "/ip6/2400:6180:0:d0::151:6001/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctVcqN88CNLHXMkTNwMKPnu", "/ip6/2604:a880:800:10::4a:5001/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64", "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd" ], "Datastore": { "BloomFilterSize": 0, "GCPeriod": "1h", "HashOnRead": false, "Spec": { "mounts": [ { "child": { "path": "blocks", "shardFunc": "/repo/flatfs/shard/v1/next-to-last/2", "sync": true, "type": "flatfs" }, "mountpoint": "/blocks", "prefix": "flatfs.datastore", "type": "measure" }, { "child": { "compression": "none", "path": "datastore", "type": "levelds" }, "mountpoint": "/", "prefix": "leveldb.datastore", "type": "measure" } ], "type": "mount" }, "StorageGCWatermark": 0, "StorageMax": "1GB" }, "Discovery": { "MDNS": { "Enabled": true, "Interval": 10 } }, "Experimental": { "FilestoreEnabled": false, "Libp2pStreamMounting": false, "P2pHttpProxy": false, "QUIC": false, "ShardingEnabled": false, "UrlstoreEnabled": false }, "Gateway": { "APICommands": [], "HTTPHeaders": { "Access-Control-Allow-Headers": [ "X-Requested-With", "Range" ], "Access-Control-Allow-Methods": [ "GET" ], "Access-Control-Allow-Origin": [ "*" ] }, "PathPrefixes": [], "RootRedirect": "", "Writable": false }, "Identity": { "PeerID": "QmfB8xVzjndgMWHuxszYADGrwBo1Zx6zjBQQCsqARDupsW" }, "Ipns": { "RecordLifetime": "", "RepublishPeriod": "", "ResolveCacheSize": 128 }, "Mounts": { "FuseAllowOther": false, "IPFS": "/ipfs", "IPNS": "/ipns" }, "Pubsub": { "DisableSigning": false, "Router": "", "StrictSignatureVerification": false }, "Reprovider": { "Interval": "12h", "Strategy": "all" }, "Routing": { "Type": "dht" }, "Swarm": { "AddrFilters": null, "ConnMgr": { "GracePeriod": "20s", "HighWater": 900, "LowWater": 600, "Type": "basic" }, "DisableBandwidthMetrics": false, "DisableNatPortMap": false, "DisableRelay": false, "EnableRelayHop": false } } A: It looks like StorageMax does not actually limit the size of the IPFS node, instead it's used to determine whether or not to run garbage collection. IPFS will write until the disk is full.
{ "language": "en", "url": "https://stackoverflow.com/questions/55494711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading data into json file How can i update json file from model in sap ui5? var oModel = new sap.ui.model.json.JSONModel(); oModel.loadData("json/Product.json"); I have to update my product.json file. Please give me your suggestion... Thank you very much in advance. A: You cannot update a JSON file stored on your server with UI5 or any client side library. You will need a server-side script with some file writing code to do it. You should use an OData service and perform any read/write operations to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/42490023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to fix Signal Handler assignment For Linux C programming, I have this handler and main method: void handler(int number, signinfo_t, void *ignore){ printf("Signaling %d\n", si->si_pid); } int main(){ struct sigaction sig; sig.sa_flags = SA_SIGINFO; sigemptyset(&sig.sa_mask); sig.sa_handler = handler // This line has error If I make the handler with just 1 parameter void handler(int num) it works fine; however, I will not be able to use si->si_pid. The warning I am getting is : warning: assignment to __sighandler_t from an incompatible pointer type -Wincompatible-pointer-types sig.sa_handler = handler; Do I make it sig.sa_action instead? I want to fix the warning A: You're assigning the handler function to the wrong member of sig. The declaration of struct sigaction is: struct sigaction { void (*sa_handler)(int); void (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer)(void); }; sig.sa_handler is a function with only one argument, the signal number. When you use the SA_SIGINFO flag, you need to assign the 3-argument function to sig.sa_sigaction instead. int main(){ struct sigaction sig; sig.sa_flags = SA_SIGINFO; sigemptyset(&sig.sa_mask); sig.sa_sigaction = handler;
{ "language": "en", "url": "https://stackoverflow.com/questions/55034028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: loading div only visible on referrer I've got a minor problem I'm trying to resolve on my website. I have it currently so that a loading screen div appears above the page when the user visits and then fades away after a set time/the page is loaded, whichever comes latest. I want this div only to appear on first visit and would prefer to avoid cookies or anything server side. From what I understand I want to utilize session storage or referrer but have not had success with implementing that. Also, subsequent pages have a less prominent and faster loading screen that will have to go away only when each individual page has been visited once during the session. The applicable code is: css: .js div#preloader { position: fixed; left: 0; top: 0; z-index: 1000; width: 100%; height: 100%; overflow: visible; background-color: #202020;} #preloader { z-index: 1000; } js: jQuery(document).ready(function ($) { $(window).load(function () { setTimeout(function(){ $('#preloader').fadeOut(1500, function () { }); },5000); }); }); So it's likely obvious that I'm not well informed; I'm teaching myself as I go and needless to say I have a lot to learn about javascript. If I've done something horribly wrong here, which is entirely plausible, or a working demo is required, please let me know. Thanks! A: You can probably accomplish what you want using the sessionStorage object. In that object, you can track which pages have been visited in the current session. The issue you can run into with JavaScript (and the reason I said it may not be the best approach) is that, when using a library, there is always a finite amount of time that passes while the library is loaded, parsed, and executed. This makes your "only appear on the first visit" requirement somewhat difficult to accomplish in JavaScript. If you show it by default and hide it with library code, it will show briefly each time you go to the page. If you hide it by default and show it with library code, it will be briefly hidden the first time you go to the page. One way to handle this is to use embedded JavaScript that is executed immediately after the DOM for the preloader is defined. The downside to this is that you have to know how to write cross-browser JavaScript without assistance from a library like jQuery. In your case, the JavaScript required to simply hide the preloader is simple enough that it shouldn't have any cross-browser issues. I created a simple page that demonstrates the technique. The source for this page is: <html> <head> <style> #preloader { position: fixed; left: 0; top: 0; z-index: 1000; width: 100%; height: 100%; overflow: visible; color: white; background-color: #202020; } </style> </head> <body> <div id="preloader">Preloader</div> <script> if (sessionStorage[location.href]) { document.getElementById('preloader').style.display = 'none'; } sessionStorage[location.href] = true; </script> <p>This is the text of the body</p> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script> $(function () { setTimeout(function(){ $('#preloader').fadeOut(1500); }, 5000); }); </script> </body> </html> I also created a fiddle for it: http://jsfiddle.net/cdvhvwmm/
{ "language": "en", "url": "https://stackoverflow.com/questions/32358447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to upgrade to mysql 5.6 in ubuntu 12.04 I was needed to upgrade mysql 5.5 to 5.6, to avoid some issues on importing sql files. ERROR 1293 (HY000) at line 231: Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause How do you upgrade it? A: Just run the following commands: apt-get -y remove mysql-server apt-get -y autoremove apt-get -y install software-properties-common add-apt-repository -y ppa:ondrej/mysql-5.6 apt-get update apt-get -y install mysql-server
{ "language": "en", "url": "https://stackoverflow.com/questions/30044517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sorting string value in a case-insensitive manner in Java 8 How do I sort string values in case-insensitive order in the following? List<Employee> listofEmployees = Arrays.asList( new Employee(1, "aaa", Arrays.asList(123, 345, 678)), new Employee(1, "bbb", Arrays.asList(91011, 121314, 1516117)), new Employee(2, "ccc", Arrays.asList(181920, 212223, 242526)), new Employee(3, "ddd", Arrays.asList(272829, 303132, 333435)), new Employee(4, "BBB", Arrays.asList(29, 332, 33)) ); I wrote like this: listofEmployees.stream().sorted(Comparator.comparing(Employee::getName).reversed()) .forEach(s -> System.out.println(s.getName())); How do I pass a string case insensitive option here? A: This is one of many ways: listofEmployees.stream() .sorted((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())) .forEach(s -> System.out.println(s.getName())); A: As @Tree suggested in comments, one can use the java.text.Collator for a case-insensitive and locale-sensitive String comparison. The following shows how both case and accents could be ignored for US English: Collator collator = Collator.getInstance(Locale.US); collator.setStrength(Collator.PRIMARY); listOfEmployees.sort(Comparator.comparing(Employee::getName, collator.reversed())); When collator strength is set to PRIMARY, then only PRIMARY differences are considered significant during comparison. Therefore, the following Strings are considered equivalent: if (collator.compare("abc", "ABC") == 0) { System.out.println("Strings are equivalent"); } A: You can specify it as the second argument to ignore cases: Comparator.comparing(Employee::getName, String::compareToIgnoreCase).reversed() A: Try this Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER) A: It looks like there is a Comparator that orders String objects as by compareToIgnoreCase, you can read the documentation here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER A: You can lowercase or uppercase it like this: listofEmployees.stream() .sorted(Comparator.comparing((Employee e) -> e.getName() .toLowerCase()) // or toUpperCase .reversed()) .forEach(s -> System.out.println(s.getName()));
{ "language": "en", "url": "https://stackoverflow.com/questions/49821774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: installing libjpeg for pil and Google app engine on mac Mountain Lion I'm sure there's a duplicate of this somewhere out there but I looked and am about at the end of my rope. I'm trying get PIL working on my mac OS X 10.8 so that I can use dev_appserver.py to test an imaging feature. First I had trouble installing PIL until I got Homebrew and installed it using brew install pil. I was under the opinion that brew installed all the necessary dependencies but when I tried to resize a jpeg in my app, it says IOError: decoder jpeg is not available. So I looked online and most places said I needed to (1) uninstall PIL, (2) install libjpeg from source and (3) reinstall PIL. So, I brew uninstall PIL, and then curl -O www.ijg.org/files/jpegsrc.v7.tar.gz tar zxvf jpegsrc.v7.tar.gz cd jpeg-7d/ ./configure make make install and finally brew install pil. I restart dev_appserver.py and reload the page on localhost, but same error. I tested pil out from the python command-line with >>> from PIL.Image import Image >>> f = open("someimagefile", "rb") >>> i = Image() >>> i.fromstring(f.read(), decoder_name="jpeg") Traceback blah blah blah IOError: decoder jpeg not available I don't have much experience installing utilities from command-line, so I probably missed something obvious. Again, sorry if there are duplicates, but like I said, I looked and couldn't find anything that seemed to work. A: Finally got it working! Thanks to @zgoda and this link. Here are the steps I ended up with for those of you who have the same problem: First make sure PIL is not installed. Download libjpeg from http://www.ijg.org/files/jpegsrc.v8c.tar.gz, unpacked it, ./configure, and make. When I tried to make install it couldn't find the directory to store the man pages so installation failed. I looked at the information on the above link and decided to cp -r ~/Downloads/jpeg-6d/ /usr/local/jpeg I suspect if the installation goes fine than that line isn't necessary. Then edit the following line in PIL's setup.py: JPEG_ROOT = None to JPEG_ROOT = "/usr/local/jpeg" finally: $ python setup.py build $ python setup.py install A: PIL did not found libjpeg headers during compilation. Consult your build system documentation on how to specify headers ("includes") location, eg. as environment variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/14132890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Boost asio to receive commands and execute them I'm trying to make a boost server, which will receive commands and do certain things. Now I would like to create a function, that will receive a file and save it to a specific location. The problem is with serialization. I don't know how can I recognize a command in a stream in an efficint way. I tried with boost::asio::read_until. And actually my code works. First file is being sent and received perfectly. But I am getting an error (The file handle supplied is not valid) when client sends second file. I would be very grateful for every advice. Thanks in an advance! bool Sync::start_server() { boost::asio::streambuf request_buf; std::istream request_stream(&request_buf); boost::system::error_code error; try { tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port)); acceptor.accept(socket); //socket is a member of class Sync while (true) { error.clear(); size_t siz = boost::asio::read_until(socket, request_buf, "\n\n"); std::cout << "request size:" << request_buf.size() << "\n"; string command; string parameter; size_t data_size = 0; request_stream >> command; request_stream >> parameter; request_stream >> data_size; request_buf.consume(siz);//And also this //cut filename from path below size_t pos = parameter.find_last_of('\\'); if (pos != std::string::npos) parameter = parameter.substr(pos + 1); //cut filename from path above //command = "save";// constant until I make up other functions //execute(command, parameter, data_size); save(parameter,data_size);//parameter is filename } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } And function to save file to a hard drive: bool Sync::save(string filename, size_t filesize) { boost::array<char, 1024> buf; cout << "filesize is" << filesize; size_t data_size = 0; boost::system::error_code error; std::ofstream output_file(filename.c_str(), std::ios_base::binary); if (!output_file) { std::cout << "failed to open " << filename << std::endl; return __LINE__; } while (true) { size_t len = socket.read_some(boost::asio::buffer(buf), error); if (len>0) output_file.write(buf.c_array(), (std::streamsize)len); if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)filesize) { output_file.close(); buf.empty(); break; // file was received } if (error) { socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); socket.close(error); output_file.close(); buf.empty(); break;//an error occured } } } A: * *read_until might read beyond the delimiter (therefore request_buf.size() can be more than siz). This is a conceptual problem when you implement save because you read data_size bytes from the socket, which ignores any data already in request_buf *These things are code smells: if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)filesize) { (never use C-style casts). And return __LINE__; // huh? just `true` then And buf.empty(); (That has no effect whatsoever). I present here three versions: * *First Cleanup *Simplify (using tcp::iostream) *Simplify! (assuming more things about the request format) First Cleanup Here's a reasonable cleanup: Live On Coliru #include <boost/asio.hpp> #include <boost/array.hpp> #include <iostream> #include <fstream> namespace ba = boost::asio; using ba::ip::tcp; struct Conf { int def_port = 6767; } s_config; struct Request { std::string command; std::string parameter; std::size_t data_size = 0; std::string get_filename() const { // cut filename from path - TODO use boost::filesystem::path instead return parameter.substr(parameter.find_last_of('\\') + 1); } friend std::istream& operator>>(std::istream& is, Request& req) { return is >> req.command >> req.parameter >> req.data_size; } }; struct Sync { bool start_server(); bool save(Request const& req, boost::asio::streambuf& request_buf); ba::io_service& io_service; tcp::socket socket{ io_service }; Conf const *conf = &s_config; }; bool Sync::start_server() { boost::asio::streambuf request_buf; boost::system::error_code error; try { tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port)); acceptor.accept(socket); // socket is a member of class Sync while (true) { error.clear(); std::string req_txt; { char const* delim = "\n\n"; size_t siz = boost::asio::read_until(socket, request_buf, delim, error); // correct for actual request siz auto b = buffers_begin(request_buf.data()), e = buffers_end(request_buf.data()); auto where = std::search(b, e, delim, delim+strlen(delim)); siz = where==e ? std::distance(b,e) : std::distance(b,where)+strlen(delim); std::copy_n(b, siz, back_inserter(req_txt)); request_buf.consume(siz); // consume only the request text bits from the buffer } std::cout << "request size:" << req_txt.size() << "\n"; std::cout << "Request text: '" << req_txt << "'\n"; Request req; { std::istringstream request_stream(req_txt); request_stream.exceptions(std::ios::failbit); request_stream >> req; } save(req, request_buf); // parameter is filename } } catch (std::exception &e) { std::cerr << "Error parsing request: " << e.what() << std::endl; } return false; } bool Sync::save(Request const& req, boost::asio::streambuf& request_buf) { auto filesize = req.data_size; std::cout << "filesize is: " << filesize << "\n"; { std::ofstream output_file(req.get_filename(), std::ios::binary); if (!output_file) { std::cout << "failed to open " << req.get_filename() << std::endl; return true; } // deplete request_buf if (request_buf.size()) { if (request_buf.size() < filesize) { filesize -= request_buf.size(); output_file << &request_buf; } else { // copy only filesize already available bytes std::copy_n(std::istreambuf_iterator<char>(&request_buf), filesize, std::ostreambuf_iterator<char>(output_file)); filesize = 0; } } while (filesize) { boost::array<char, 1024> buf; boost::system::error_code error; std::streamsize len = socket.read_some(boost::asio::buffer(buf), error); if (len > 0) { output_file.write(buf.c_array(), len); filesize -= len; } if (error) { socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); // ignore error socket.close(error); break; // an error occured } } } // closes output_file return false; } int main() { ba::io_service svc; Sync s{svc}; s.start_server(); svc.run(); } Prints with a client like echo -ne "save test.txt 12\n\nHello world\n" | netcat 127.0.0.1 6767: request size:18 Request text: 'save test.txt 12 ' filesize is: 12 request size:1 Request text: ' ' Error parsing request: basic_ios::clear: iostream error SIMPLIFY However, since everything is synchronous, why not just use tcp::iostream socket;. That would make start_server look like this: tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port)); acceptor.accept(*socket.rdbuf()); while (socket) { std::string req_txt, line; while (getline(socket, line) && !line.empty()) { req_txt += line + "\n"; } std::cout << "request size:" << req_txt.size() << "\n"; std::cout << "Request text: '" << req_txt << "'\n"; Request req; if (std::istringstream(req_txt) >> req) save(req); } And save even simpler: void Sync::save(Request const& req) { char buf[1024]; size_t remain = req.data_size, n = 0; for (std::ofstream of(req.get_filename(), std::ios::binary); socket.read(buf, std::min(sizeof(buf), remain)), (n = socket.gcount()); remain -= n) { if (!of.write(buf, n)) break; } } See it Live On Coliru When tested with for f in test{a..z}.txt; do (echo -ne "save $f 12\n\nHello world\n"); done | netcat 127.0.0.1 6767 that prints: request size:18 Request text: 'save testa.txt 12 ' request size:18 Request text: 'save testb.txt 12 ' [... snip ...] request size:18 Request text: 'save testz.txt 12 ' request size:0 Request text: '' Even Simpler If you know that the request is a single line, or whitespace is not significant: struct Sync { void run_server(); void save(Request const& req); private: Conf const *conf = &s_config; tcp::iostream socket; }; void Sync::run_server() { ba::io_service io_service; tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port)); acceptor.accept(*socket.rdbuf()); for (Request req; socket >> std::noskipws >> req; std::cout << req << " handled\n") save(req); } void Sync::save(Request const& req) { char buf[1024]; size_t remain = req.data_size, n = 0; for (std::ofstream of(req.get_filename(), std::ios::binary); socket.read(buf, std::min(sizeof(buf), remain)), (n = socket.gcount()); remain -= n) { if (!of.write(buf, n)) break; } } int main() { Sync().run_server(); } That's the entire program in ~33 lines of code. See it Live On Coliru, printing: Request {"save" "testa.txt"} handled Request {"save" "testb.txt"} handled Request {"save" "testc.txt"} handled [... snip ...] Request {"save" "testy.txt"} handled Request {"save" "testz.txt"} handled
{ "language": "en", "url": "https://stackoverflow.com/questions/48853393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: change directory with python I coincidentally found out that I cannot change the actual directory from within a python-code. My Test-Program is as follows: from os import system def sh(script): system("bash -c '%s'" % script) sh("cd /home") sh("pwd") The output of pwd is not /home, but the directory where the code above lives. Can someone explain why this happens? A: The problem is that you execute shell commands instead of actually changing the directory using os.chdir() Each os.system() call executes the given command in a new shell - so the script's working directory is not affected at all. A: The directory actually is changed, but in another process, the child of your script. There's one simple rule to remember: a child can never affect the environment (PATH, CWD etc) of its parent. A: sh("cd /home") sh("pwd") ^ this spawns 2 separate shells, try: sh("cd /home; pwd") A: When you run sh function you spawn a new bash process which then changes current directory and exits. Then you spawn a new process which knows nothing about what happened to the first bash process. Its current directory is, again, set to the home directory of the current user. To change Python process' current working directory use os.chdir("blah")` A: Each sh( ) call is generating a different shell, so you are affecting the shell's working directory, not python's. To change pythons working directory, use chdir()
{ "language": "en", "url": "https://stackoverflow.com/questions/13732221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Delete link for user isn't showing up I am new to web development (I have been coding for about 6/7 months now) in hopes of building my own app. I have been reading and working of the Ruby on Rails tutorial by Michael Hartl. I am on the chapter 9 section deleting users and am stuck. Everything works for the most part except that the user link. It just doesn't show on the display page. The users and their avatars fine. I just can't figure out a way to get the user delete link to show. Below is the code for the user model, the user controller, the session controller where the code current user lives and the view. Also, when ever i take out the if statement from the user partial the delete link shows. I am not sure whats wrong since I already defined admin, and the current_user. I would be entirely grateful for any kind of guidance. My project is also on github if the information below isn't sufficient enough https://github.com/krischery2150/Try2150-master/tree/updating-users class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update] before_action :admin_user, only: :destroy def new @user = User.new end def show @user = User.find(params[:id]) end def create @user = User.new(user_params) if @user.save log_in @user flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update_attributes(user_params) flash[:success] = "Profile Updated" redirect_to @user else render 'edit' end end def index @users = User.paginate(page: params[:page]) end def destroy User.find(params[:id]).destroy flash[:success] = "Your profile was deleted" redirect_to users_url end private def user_params params.require(:user).permit(:username, :email, :password, :password_confirmation, :user_about_me, :birthday, :avatar, :gender) end ##Before filters method # Confirms that a given user is logged in. Only when these conditions are met the user will # be able to update or edit their page def logged_in_user unless logged_in? store_location flash[:danger]= "Please Log In" redirect_to login_url end end # Confirms the correct user. def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end # Confirms an admin user. def admin_user redirect_to(root_url) unless current_user.admin? end end . class User < ActiveRecord::Base before_save {self.email = email.downcase} attr_accessor :remember_token has_attached_file :avatar, styles: { medium: "300x300>", thumb: "50x50>" }, default_url: "/images/:thumb/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/ # this before_save is a callback method. What it does is before it saves the email #address it calls back and transforms all the letters into lower case. Had to do the indexing #in active record in order for the method to work validates :username , presence: true, length: {maximum: 250} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i #code that ensures that a user puts the right format for emails in signup #fields validates :email, presence: true, length:{maximum: 50}, format:{with: VALID_EMAIL_REGEX }, uniqueness:{ case_sensitive: false } #rails still assumes that uniquess is true #whether the user types CAMELcase or lowercase validates :password, presence: true, length:{maximum: 50}, allow_nil: true validates :user_about_me, presence: true validates :birthday, presence:true has_secure_password # Returns the hash digest of the given string. def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end ## returns a random user token def User.new_token SecureRandom.urlsafe_base64 end # Remember a given user to the database for use of persistent sessions def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end ##returns true if given token matches the digest def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end def forget update_attribute(:remember_digest, nil) end def log_out forget(current_user) session.delete(:user_id) @current_user = nil end end This is the code in the partial rendering on the index page where all users show up. <div class="col-md-9 col-offset-3" id="index-profile"> <li class="users"> <div class="col-xs-3 profilepic-container"> <%= image_tag user.avatar.url %> </div> <%= link_to user.username, user %> <% if current_user.admin? && !current_user?(user) %> | <%= link_to "delete", user, method: :delete, data: { confirm: "You sure?" } %> <% end %> </li> A: The delete link in your partial has two conditions that are required to be true. The user must be an admin, and the profile must not be their own profile. So if the admin user is the only user, then no delete link will show up. Try creating a second user and see if the delete link shows up for that user.
{ "language": "en", "url": "https://stackoverflow.com/questions/36346113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the best way to update some properties of an object immutably in JavaScript? Say we have an object like: const obj = { foo: { a: { type: 'foo', baz: 1 }, b: { type: 'bar', baz: 2 }, c: { type: 'foo', baz: 3 } } } Now I want to update all properties' baz to 5 if the type of the property in foo is foo. And I would like to modify it in an immutable way, that means it would not modify the origin object but returns a new object. A: I normally write Object.create() for shallow copy ,but deep copy (nested object) I do with JSON.parse(JSON.stringify(nestedObject)) const obj = { foo: { a: { type: 'foo', baz: 1 }, b: { type: 'bar', baz: 2 }, c: { type: 'foo', baz: 3 } } } var temp = JSON.parse(JSON.stringify(obj)) for(var i in temp.foo) { if(temp.foo[i].type == "foo") { temp.foo[i].baz = 5; } } console.log(temp); console.log(obj); A: Object.assign is perfect for this, from the docs: The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. And you can use it like this : Object.assign( {}, obj, { foo: { a: { baz: obj.foo.a.type === 'foo' ? 5 : obj.foo.a } } } ); A: You can use Object.entries(), Array.prototype.map(), spread element, computed property, Object.assign() const obj = { foo: { a: { type: 'foo', baz: 1 }, b: { type: 'bar', baz: 2 }, c: { type: 'foo', baz: 3 } } } let key = Object.keys(obj).pop(); let res = {[key]: Object.assign({}, ...Object.entries(obj[key]) .map(([prop, {type,baz}]) => ({[prop]: {type,baz:type === "foo" ? 5 : baz}}) ))}; console.log(res, obj);
{ "language": "en", "url": "https://stackoverflow.com/questions/45093736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do certain variables/equations affect lists? def list(a, b): for k in range(len(a)): a[k] = a[k] + b[len(b)-1-k] return a When it comes to manipulating lists, how does python execute a function like this one from a line by line basis. Specifically when i'm presented with an len() or [k] in this code how does it affect a list presented by a user? An example could be when a = [1,3,5,7,9], b = [1,4,9,8,6] the returned (a) value is [7, 11, 14, 11, 10] I'm unsure how this process is completed in Python. A: I am mostly confused by the introduction of [k] in the equation as I don't know how it changes the list. someList[k] is an item accessor for the kth item of the list. So for a list a = [2, 3, 5, 7], a[k] will return the kth number. For example: >>> a = [2, 3, 5, 7] >>> a[0] 2 >>> a[1] 3 >>> k = 3 >>> a[k] 7 Using the accessor alone will just read the value without affecting the list. Python however does allow you to also assign a value to it. Doing so will change the list’s item at that index: >>> a = [2, 3, 5, 7] >>> a[2] 5 >>> a[2] = 13 # we change the value >>> a[2] 13 >>> a # the original list was modified [2, 3, 13, 7] So in your loop, when you have a[k] = a[k] + something, you get the value at the kth index, add something to it, and then update the original list at the same index. Since function parameters are passed by references, this updates your original list (and you later return the identical list object from your function). As for the “something” part, you are doing this: b[len(b)-1-k]. Again, you are using an index to access a single item of the list b. But this time, the index is not a constant or a single variable, but a more complex expression: len(b) - 1 - k. len(b) will return the length of the list b, so ultimaltely, as you iterate through the a list from the beginning, you are iterating b from the end (assuming the same length for both lists). Python will execute the expression first, so in the end it will access b’s item at the index that results from that expression.
{ "language": "en", "url": "https://stackoverflow.com/questions/28872421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to write numeric expressions in Makefile? I want to write statements about Podman in Makefile. A UID mapping is used here. But I found that I was always unable to do numerical calculations. Below is my Makefile. But here ${uid}+1 and similar operations will become empty strings. How should I solve this problem? Thanks! HOST_GEM5 := /mnt/disk/cuiyujie/workspace/workGem5/gem5 SIM := ${HOST_GEM5}/X86/gem5.opt SHELL := /bin/bash DOCKER_GEM5 := /usr/local/src/gem5 subuidSize=$(shell $(( $(podman info --format "{{ range .Host.IDMappings.UIDMap }}+{{.Size }}{{end }}" ) - 1 ))) subgidSize=$(shell $(( $(podman info --format "{{ range .Host.IDMappings.GIDMap }}+{{.Size }}{{end }}" ) - 1 ))) uid := $(shell id -u) gid := $(shell id -g) DOCKER_DIRS_MAP := \ -v ${HOST_GEM5}/runScripts:${DOCKER_GEM5}/runScripts MAP_CMD := \ --user ${uid}:${gid} \ --uidmap ${uid}:0:1 \ --uidmap 0:1:${uid} \ --uidmap $(($uid+1)):$(($uid+1)):$(($subuidSize-$uid)) \ --gidmap ${gid}:0:1 \ --gidmap 0:1:${gid} \ --gidmap $(($gid+1)):$(($gid+1)):$(($subgidSize-$gid)) .PHONY: default clean run build default: build build: podman run -it --rm ${DOCKER_DIRS_MAP} --security-opt seccomp=unconfined \ ${MAP_CMD} \ gerrie/gem5:v1 "/bin/bash" clean: rm -rf ${HOST_GEM5}/build/* A: Make always uses /bin/sh as the shell it invokes, both for recipes and for $(shell ...) functions. /bin/sh is a POSIX-conforming shell. The syntax you're using is not POSIX shell syntax: it's special enhanced syntax that is only available in the bash shell. You can either rewrite your scripting to work in POSIX shells (probably by using the expr program to do the math), or add this to your makefile to tell it you want to use bash instead of /bin/sh: SHELL := /bin/bash Note, of course, that your makefile will now no longer work on any system that doesn't have a /bin/bash shell.
{ "language": "en", "url": "https://stackoverflow.com/questions/72646657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I refer to what called a function in C++? I was wondering if there is a way in C++ to know what called a function? Like the this keyword in Java or JavaScript. For example, I have a function called insert, which inserts an item into a linked list, I want the linked-list that called those the function insert to call two other functions. How would I do that? I have this right now, is this valid? bool linked_list::insert( int i ) { bool inserted = false; if( this.is_present(i) ) /* function is_present is defined earlier checks if an int is already in the linked-list. */ { inserted = true // already inside the linked-list } else { this.Put( 0, i ); /* function Put is defined earlier and puts an int in a linked-list at a given position (first param.). */ inserted = true; // it was put it. } return inserted; } A: For historical reasons, this is a pointer. Use -> instead of .. bool linked_list::insert(int i) { bool inserted = false; if(this->is_present(i)) { inserted = true; // fixed syntax error while I was at it. } else { this->put(0, i); // fixed inconsistent naming while I was at it. inserted = true; } return inserted; } Usually it is not needed to use this-> at all; you can just do if(is_present(i)). A: this works in c++ the same as it does in Java. The only difference is that you need to use this-> instead of this. this is a pointer than therefor you cannot use the dot operator to access it's members. A: why don't you just call the other functions in linked_list::insert(int)? And no, it is not valid, you should put this -> something instead of this.something
{ "language": "en", "url": "https://stackoverflow.com/questions/13408767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split the string at the word before the next colon? I am trying to split this string between the first colon entry and the next word that includes a colon. The string is a long text. It can have a period or comma between the colons. For example, if I have the following string. String s = "Description: This is the description. Observation: This is the description."; String[] parts = s.split("REGULAR_EXPRESSION"); The result would be: This is the description. For example if the string is "Description: This is. The, description. Words: words words" The result would be: This is. The, description. A: If you want what you ask, you need a regex that splits by colon and period. Something like this? :.+\. EDIT: Here is a breakdown of this regular expression (as requested by Roman C) : matches the colon character (:) literally .+ matches any character one and unlimited times, greedy (except newline) \. matches the period character (.) literally A: This splits the string on both the colon or period. Element index 1 (the second element) is what you want. Just trim it. String description = "Description: This is the description. Observation: This is the description.". split("[\\.:]")[1].trim(); You could also pre-trim it: String description = "Description: This is the description. Observation: This is the description.". split("[\\.:] +")[1]; Use "[\\.:]\\s+" if there might be non-space whitespace. A: Split is not the best method to use. This code gets you the part you want: String part = string.replaceAll("\\w+:\\s+(.*?)\\s+\\w+:.*", "$1"); This also trims the part extracted. Some test code: String string = "Description: This is the description. Observation: This is the description."; String part = string.replaceAll("\\w+:\\s+(.*?)\\s+\\w+:.*", "$1"); System.out.println(part); Output: This is the description. A: What about the next?: String string = "Description: This is the description. Observation: This is the description."; String str = string.replaceFirst(".*:\\s+(.*)", "$1");
{ "language": "en", "url": "https://stackoverflow.com/questions/23163925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: BPEL Apache ODE .deployed file I have created a basic helloworld.bpel process file in eclipse in BPEL project and tried to deploy it Apache ODE. So I followed the steps in this link Apache ODE Eclipse BPEL guide. But in the later stages, after putting the relevant files in WEB-INF folder and running the APACHE ODE the expected .deployed file was not created. And Apache ODE is not detecting the same in ODE browser when I use localhost:8080/ode/processes. When I tried to launch ODE server in eclipse, I am getting the following errors. Firstly, this was the error that I got. "Another instance of derby may have booted into the database" Then I restarted Apache Tomcat in services.msc. Then that error stopped showing. Now this is the error I am stuck with. "Schema SA does not exist" Database Class Loader started - derby.database.classpath='' 13:54:26,099 WARN [GeronimoConnectionEventListener] connectionErrorOccurred called with null java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source) at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source) A: Looks like there are some problems with the embedded derby database. I'd try to completely redeploy ODE so that the database is extracted from the .war again. A: You have to execute Eclipse or NetBeans as Administrator.
{ "language": "en", "url": "https://stackoverflow.com/questions/12577258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Django assign user to group during registration based on choice in another field I would like to automatically assign users to a group based on their choice in another field in the user registration field. I am new to Django and I am not sure of the best way to achieve this. I want to assign the group based on the choice of the "business_location_county" field in the model. In simple terms the group should be the group id where the group "forum_id" equals the id of the business_location_county choice. The group "forum_id" is a custom column added to the Group model. The models.py: from django.contrib.auth.models import AbstractUser from django.db import models from machina.core.db.models import get_model from django.db.models import Q from django.contrib.auth.models import Group Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) business_location_state = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft":1}) business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2)))) Group.add_to_class('forum_id', models.PositiveIntegerField(null=True, blank=True)) views.py: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm from .models import CustomUser from django.shortcuts import render from machina.core.db.models import get_model from django.db.models import Q Forum = get_model("forum", "Forum") class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def load_counties(request): parent_id = request.GET.get('business_location_state') counties = Forum.objects.filter(parent_id=parent_id).order_by('name') return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties}) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state', 'business_location_county') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['business_location_county'].queryset = CustomUser.objects.none() class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'age','business_location_state', 'business_location_county') I am attempting to use post_save signal to accomplish this. However before I tackle trying to save the user to the group, I need to figure out how to get the Group id where business_location_state id is equal to Group forum_id. I tried (unsuccessfully) adding this to the models.py from django.db.models.signals import ( post_save ) def user_addgroup_handler(sender, instance, created, *args, **kwargs): g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county))) print (g) post_save.connect(user_addgroup_handler, sender=CustomUser) Any suggestions on how to achieve this? A: With help from an expert the following works: def user_addgroup_handler(sender, instance, created, *args, **kwargs): # g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county))) # group = Group.objects.get(name=instance.business_location_county.name) # for g in CustomUser.objects.all(): # print(g.business_location_county_id) if created: # Get or create group new_group, created = Group.objects.get_or_create( name=instance.business_location_county.name, forum_id=instance.business_location_county.id) # add new group to user instance.groups.add(new_group) post_save.connect(user_addgroup_handler, sender=CustomUser)
{ "language": "en", "url": "https://stackoverflow.com/questions/67964203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NodeJS, ExpressJS & Jade - passing model to knockout? I'm trying to get my expressJS-Model to my .jade-template, but the way I can access the Model with JS on the client-machine. The idea is simple: I want to use the Model with Knockout - so I need to give the Model-Object as it is to the client. If I do the obvious - var t = #{customer} - I ending up with the rendered output var t = [object Object] So how can I use the object on the client-side? Thanks! A: JSON.stringify the object on the server, and JSON.parse it on the client (will only work in IE >= 8, if you need to support older i3-browsers you could provide json-js from douglas crockford: https://github.com/douglascrockford/JSON-js
{ "language": "en", "url": "https://stackoverflow.com/questions/13643421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get Bootstrap timepicker date object? Currently using bootstrap timepicker with Angularjs http://jdewit.github.com/bootstrap-timepicker The control is displaying well but when i set the ng-model and get the startTime <div class="col-md-3"> <div class="form-group"> <input type="text" class="form-control timepicker" ng-disabled="!useTime" data-template="dropdown" data-show-seconds="true" data-default-time="11:25 AM" data-show-meridian="true" data-minute-step="5" ng-model="startTime" /> </div> </div> The startTime assigned is a string like "11:25 AM" instead of a date object i can manipulate in javascript. How can i get date object? Do i need to convert it manually? A: Think this answer seems to be similar to your question.Hope it provides some insight. Time Binding issue in Bootstrap timepicker
{ "language": "en", "url": "https://stackoverflow.com/questions/27956284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nested filters in angular for hierarchical data model I have an hierarchical data model with lines of products and then sublines, and then sublines of sublines etc. What I am trying to do is isolate only the sublines that are directly descendants (sons not grandchildren) of a particular line or subline. Here is my existing data model: items:[ { "_id": "1", "description": "sth1", "name": "smname1", "level_type": "line", "ancestor": "", "descendant": "smname2" } }, { "_id": "2", "description": "sth2", "name": "smname1", "level_type": "subline", "ancestor": "smname1", "descendant": "" } }, ] Also for the example above another thing I'm trying to accomplish is to get the children of all the product lines. What I have tried but is not working so far is: Controller $scope.prodClassIsALine = function(item) { return item.level_type=='line'; }; $scope.prodClassIsASubLineof = function(item) { return item.ancestor==$scope.prodClassIsALine.name; }; Tragic proposal just to show you that I need all children of all lines i.e. all items with ancestor names of items that are lines. Html <div ng-repeat="item in items | filter:prodClassIsALine:prodClassIsASubLineof"> <p>{[{item.name}]}</p> </div> Is this the way we are nesting filters in AngularJS? It seems that filters are iterating over the list that are given as attribute but further than that I can't understand in detail how they work. Please help. Solution In script.js //product is my ng-module //filter to get all product classes that are lines product.filter('prodClassIsALine', function() { return function(input) { var out = []; for (var i = 0; i < input.length; i++) { if (input[i].level_type=='line') { out.push(input[i]) }; }; return out; }; }); //filter to get all children of product classes that are lines product.filter('prodClassLineChild', function() { return function(input) { var out = []; var out2 = []; for (var i = 0; i < input.length; i++) { if (input[i].level_type=='line') { out2.push(input[i]) }; }; for (var i = 0; i < out2.length; i++) { for (var j = 0; j < input.length; j++) { if (input[j].ancestor==out2[i].name) { out.push(input[j]) }; }; }; return out; }; }); Html <div ng-repeat="item in items | prodClassIsALine"> <!-- or <div ng-repeat="item in items | prodClassLineChild"--> <p>{[{item.name}]}</p> </div> A: do u mean this? <div ng-repeat="item in items | filter1 | filter2"> more info here http://docs.angularjs.org/guide/dev_guide.templates.filters.using_filters EDIT: now i got that u didnt wrote filters but scope function, u need something like this myModule.filter('iif', function () { return function (input, trueValue, falseValue) { return input ? trueValue : falseValue; }; }); my use is class="{{ catalogItem.IS_FINAL | iif : 'IsFinalCatalogItem' : '' }}" should look like this myModule.filter('prodClassIsALine', function() { return function(item) { return item.level_type=='line'; }; }); p.s. in angular 1.2 they added the standard iif syntax
{ "language": "en", "url": "https://stackoverflow.com/questions/18478236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I save my resized image to my Azure Blob Storage in my ASP.NET Core Application? I'm using the ImageSharp library to rescale my images before they are uploaded to Azure, the application hangs with no errors when it reaches the UploadBlob action and I think it's the stream causing it. When the image is uploaded the information is gathered from the image stream, I create an empty MemoryStream, resize the image using ImageSharp, stuff the MemoryStream with my newly scaled image and try to upload that MemoryStream to Azure and I don't think it likes it as that is where it hangs. Is MemoryStream the correct thing to use in this instance or is it something else? CarController.cs [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Car car) { // Define the cancellation token. CancellationTokenSource source = new CancellationTokenSource(); CancellationToken token = source.Token; if (ModelState.IsValid) { //Access the car record _carService.InsertCar(car); //Get the newly created ID int id = car.Id; //Give it a name with some virtual directories within the container string fileName = "car/" + id + "/car-image.jpg"; string strContainerName = "uploads"; //I create a memory stream ready for the rescaled image, not sure this is right. Stream outStream = new MemoryStream(); //Access my storage account BlobServiceClient blobServiceClient = new BlobServiceClient(accessKey); BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(strContainerName); //Open the image read stream var carImage = car.ImageFile.OpenReadStream(); //Rescale the image, save as jpeg. using (Image image = Image.Load(carImage)) { int width = 250; int height = 0; image.Mutate(x => x.Resize(width, height)); image.SaveAsJpeg(outStream); } var blobs = containerClient.UploadBlob(fileName, outStream); return RedirectToAction(nameof(Index)); } return View(car); } A: It's not got anything to do with the ImageSharp library. You need to reset your outStream position after saving. BlobContainerClient is trying to read from the end of the stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/61062906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can an untrusted client prove that an ID isn't human meaningful? I have a situation where an untrusted client is generating string IDs, but I don't want them to be human readable. They don't need to be crytographically random or even unique, I just don't want IDs like "idiot" to be accepted. How can I go about preventing this? EDIT: It would be nice if the IDs were "aspirationally-unique", like GUIDs. A: Here are some ideas: * *Convert the supplied ID to a hash or encrypt it. This will result in meaningless strings *Create a dictionary of words you don't want used, and when the supplied ID contains one of those words, reject it... a PHP example can be found at https://scvinodkumar.wordpress.com/2009/06/17/bad-word-filter-and-replace/ *Require that the IDs not contain sequences where two (or however many) alpha characters are next to each other If you have any additional info/preference/requirements, let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/38811116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fill List with strings from Regex.Matches I'm writing a WPF client for an online browser game as a learning project for C#. I want to import the data that is shown on the website, store it in a model and display it through binding. Usually, i go about it this way: Retreive data with HttpWebRequest, perform Regex to receive the wanted data, and then store it for further use in the Models. With this particular item, a list of cars and their properties in a table, i need 6 properties of the cars, which i can retrieve with 1 Regex query: var carInfos = Regex.Matches(HTMLBody, @"(?<== }"">).*(?=</td>)"); I get 42 matches from that string, which means there are 7 CarModels to be filled. Now, if i want to fill the models i would go about it this way: Cars.AllCars.Add(new CarModel{ Plate = carInfos[0].Value, Type = carInfos[1].Value, NetWorth = int.Parse(carInfos[3].Value, etc, etc.. }); This is my CarModel: public class CarModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _plate; public string Plate{ get { return _plate; } set{ if (value == _plate) return; _plate = value; OnPropertyChanged(); } public string Type { get; set; } public int NetWorth { get; set; } public State CurrentWorth { get; set; } public State Location { get; set; } public int Condition { get; set; } public int Issues { get; set; } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } How can i do this dynamically? Every 6th property is the car type, location etc. I want to be able to bind hundreds of cars eventually. Let's say, for instance, i get 12 matches from the Regex, i.e. two cars. the carInfos[0].value would be a Plate, and the carInfos[6].value would also contain a plate. How can i loop through the results in such a manner that these models will be filled accordingly? A: This should work for you then - for (int index = 0; index < carInfos.Count/6; index++) { int offest = index * 6; Cars.AllCars.Add(new CarModel{ Plate = carInfos[0 + offest].Value, Type = carInfos[1 + offest].Value, NetWorth = int.Parse(carInfos[3 + offest].Value, etc, etc.. }); } Since you have total of 7 items that's why (42/6) = 7 and item is at offset of multiple of 6 hence the logic for calculation of offset (offest = index * 6)
{ "language": "en", "url": "https://stackoverflow.com/questions/15719708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: overpass-turbo.eu find all cities on maps maybe someone can help me with a overpass-turbo.eu-query. I'd like to highlight (center of it) all cities of a country or region (or current map). Is there maybe an "simple" example on web? (Google was not a good friend with this special request, yet. But I am sure someone must tried to search this way already.) Many thanks for every idea. A: Here is an example for finding all cities, towns, villages and hamlets in the country Andorra: [out:json][timeout:25]; // fetch area “Andorra” to search in {{geocodeArea:Andorra}}->.searchArea; // gather results ( node[place~"city|town|village|hamlet"](area.searchArea); ); // print results out body; >; out skel qt; You can view the result at overpass-turbo.eu after clicking the run button. Note: When running this query for larger countries you might need to increase the timeout value. Also rendering the result in the browser might not be possible due to performance reasons. In this case use the export button and download the raw data instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/60724687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Download multiple MP3 files in the background in Android LEVEL: Beginner Language: Java IDE: Android Studio CASE: Downloading multiple MP3 files from multiple URL's in a row in the background. ISSUE: download task in the loop to download all the urls. the songs did download in the following path but aren't fully downloaded (every song is downloaded for 3 seconds/4 seconds basically very less). don't know what's the problem, It'll be great if i can get any help * *receive mp3 url's from API *download them using the following code. (ISSUE) *get the path of all and store them in the Database *fetch the path and play one by one continuously. private class DownloadTask extends AsyncTask<SongDetails, Integer, String> { Context context; public DownloadTask(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); Utilities.showProgressDialog(getActivity(), getFragmentManager()); } @Override protected String doInBackground(SongDetails... songDetails) { for (SongDetails songs : songDetails ) { donwloadsong(songs); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Utilities.dismissProgressDialog(); } } for (SongDetails songs : songDetails ) { downloadTask(songs); } public void downloadTask(SongDetails songs){ HttpURLConnection httpURLConnection = null; try { URL url = new URL(songs.getUrl()); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); int fileLength = httpURLConnection.getContentLength(); InputStream inputStream = new BufferedInputStream(url.openStream(), 8192); OutputStream outputStream1; outputStream1 = new FileOutputStream(Environment.getExternalStorageDirectory() + "/gbeduwarssongs/" + songDetails.getTitle().trim() + ".mp3"); int count = 0; byte data[] = new byte[1024]; int buffer_length; while ((buffer_length = inputStream.read(data)) != -1) { outputStream1.write(data, 0, count); count += buffer_length; } outputStream1.flush(); outputStream1.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); Log.e("Error", "Download Error Exception " + e.getMessage()); } finally { if (httpURLConnection != null) httpURLConnection.disconnect(); } } A: Rather calling iteration inside a new thread, use iteration first and then start new thread in every iteration. I hope it will help you. I am posting code for your help. for (SongDetails songs : songDetails) { new DownloadTask(pass your song object in constructor).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } and in doInBackground call your downloading method stuff. A: I offer to use DownloadManager or workmanager for it. AsyncTask has used a bad idea. It has a problem with a memory leak. The asyncTask use only one thread The same question
{ "language": "en", "url": "https://stackoverflow.com/questions/55515961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing Shared Calendars with Exchange Web Services I'm trying to access shared calendars from exchange using exchange web services, can someone provide me with info on how I can do this? I have tried: ExchangeService myService = new ExchangeService (ExchangeVersion.Exchange2007_SP1); myService.Credentials = new NetworkCredential ("user@domain.com", "12345"); But I may not always have the passwords for these accounts and the account I'm logged into does has shared calendar access. A: I have managed to get it working now Dim _cal As New Microsoft.Exchange.WebServices.Data.FolderId(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Calendar, New Microsoft.Exchange.WebServices.Data.Mailbox(_otherAddress)) Dim _calendarView As New Microsoft.Exchange.WebServices.Data.CalendarView(_startTime.Date, _endTime.Date.AddDays(1)) For Each appointmentItem As Microsoft.Exchange.WebServices.Data.Appointment In _ service.FindAppointments( _ _cal, _ _calendarView) Next
{ "language": "en", "url": "https://stackoverflow.com/questions/5139408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access WPF Treeview selected index through a TreeViewItem object I have a treeview with checkboxes for each item using a DataTemplate. <TreeView ItemsSource="{Binding}"> <DataTemplate DataType="{x:Type local:MatchDataLeaf}"> <Grid Margin="3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="240"/> <ColumnDefinition Width="100"/> <ColumnDefinition Width="150"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="60"/> </Grid.ColumnDefinitions> <StackPanel Grid.Column="0" Orientation="Horizontal"> <CheckBox x:Name="selectCheckBtn" Grid.Column="0" IsChecked="True" Click="select_Click" Tag="{Binding}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"/> <TextBlock Grid.Column="1" Margin="5,0,0,0" Text="{Binding Path=Name}" FontFamily="Arial" FontSize="12" FontWeight="Bold" Foreground="Black" VerticalAlignment="Center"/> </StackPanel> </Grid> </DataTemplate> In the checkbox click event, I'm trying to figure out the selected index in the main tree's binded list. The closest I got is passing the TreeViewItem object along in the CommandParameter, but I can't do anything with it. I was able to the the parent ItemsControl using: ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(selectedItem); int s = parent.Items.IndexOf(selectedItem); But s = -1 here. I also have the Tag on the checkbox that has the underlying object in it. Sure, I can do a Find on my list for the object, but it just seems like there must be a simpler way to find the index. A: The ItemsControl you are fetching might be the StackPanel, or the Grid. You should be able to access the Checkbox through the event sender, and navigate up to the TreeViewItem and TreeView and use IndexOf. private void CheckBox_Click(object sender, RoutedEventArgs e) { CheckBox cb = (CheckBox)sender; StackPanel sp = (StackPanel)cb.Parent; Grid g = (Grid)sp.Parent; ContentPresenter cp = (ContentPresenter)VisualTreeHelper.GetParent(g); IList l = (IList)myTreeView.ItemsSource; object o = cp.Content; MessageBox.Show(l.IndexOf(o).ToString()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/4190004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS 9 simulator can't show the whole screen For some reason, when I run some old projects, the simulator can't load the full screen: Any suggestion?
{ "language": "en", "url": "https://stackoverflow.com/questions/32750510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure FreeRtos middleware and DPS, on ESP32 I am working on a project, where I am using the Azure FreeRTOS Middleware Stack on ESP32. I would like to introduce DPS to provision all my 3K upcoming devices. The Stack has got a DPS option, but I would like some advice as I would like to generate one global bin file, for all 3K devices. I would like DPS to create the device on IoT Hub and also provide the necessary keys to the device so it can generate the SAS token for each device id. The device ID will be either the serial number or mac number of the ESP32 device. What i want to avoid is creating a seperate bin file for each device. Can this be possible? or am i miss understanding DPS? A: DPS will not provide you neccessary keys for each device. To work with Azure IoT (either DPS or Hub), you must have per-device credential flash to your device, this is usually done during manufacturing phase. When you use DPS group enrollment, you get a group key from DPS and use a formula to generate per-device key (hash the group key and enrollment/device id), you need a method to flash 3k keys to 3k devices on production line. A: DPS do actually provision a device AUTOMATICALLY. You don't extra step. Let me explain how. Step 1: Things you have to do once from the Azure portal: * *You create/you have an Azure IoT Hub up and running; *Your create/you have azure DPS up and running; *You create/you have a group enrolment with symmetric key from within DPS; *You keep the primary key of your group enrolment for use in a bit. Let’s call the primary key “KEY” Step 2: programming From your firmware source code: * *Write a code function that returns a device ID that’s unique for a device. You can use a string followed by the device MAC address, that you usually get from the Wifi interface (or Ethernet interface). For example: “3Kdevice-3454e210228c” the prefix will be the same for all devices you’ll have, but the hex numeric suffix will be different for each device. Let’s call this string REG_ID. *Write a code function that creates for the device it runs on, the symmetric key from both the primary key (aka KEY) of your enrolment and the registration ID (aka REG_ID). You do that by doing a SHA256 (see DPS doc for that). Let’s call the computed symmetric key “SYM_KEY”; *Use the azure SDK to get the credentials from DPS by presenting the registration ID (aka REG_ID) and the computed symmetric key (SYM_KEY) to it; *You can connect to the IoT Hub with the credentials you got at point 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/71870217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading multiple cookie I would like to know how do I detect multiple cookies. I have two button with class- .attack_enabled and .restore_enabled, both create cookie called attackcompletecookie and restorecompletecookie, respectively. How do I detect both cookies and add a class to .territory_middle_complete Here's my code: $(".attack_enabled").click(function(){ createCookie('attackcompletecookie','attack_cookie'); }); $(".restore_enabled").click(function(){ createCookie('attackcompletecookie','restore_cookie'); var atkcomplete = readCookie('attackcompletecookie'); }); if(atkcomplete){ console.log(atkcomplete); $(".territory_middle_complete").addClass("displayblockzindex2"); } A: Try to use id instead class to refer in jQuery, leave the classes for CSS. Check it here http://jsfiddle.net/hbzqnrm8/5/ I hope it helps you. <button id="attack_enabled">ATTACK</button> <button id="restore_enabled">RESTORE</button> <div class="territory_middle_complete">ADD A CLASS HERE</div> I've edited your jQuery code, and add what I think you want to achieve. Of course if you want to check the existance of the cookie when clicking the "restore" button, if not, just move the if condition wherever you needed, but not outside the click function, because it will be executed only on loading the file. $("#attack_enabled").click(function(){ createCookie('attackcompletecookie','attack_cookie'); }); $("#restore_enabled").click(function(){ createCookie('restorecompletecookie','restore_cookie'); var atkcomplete = readCookie('attackcompletecookie'); if(atkcomplete) { alert(atkcomplete); $(".territory_middle_complete").addClass("displayblockzindex2"); } }); function createCookie(cookieName, cookieId) { document.cookie = cookieName + '=' + cookieId; } function readCookie(name) { var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/28363084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error Code:1262 when loading to mySQL I have a little bit of an issue when trying to load tsv file 2gb to mysql database. Error Code:1262 As this is quite big file how can i open/change so i can load it into the system? A: this will be csv file and as you aware that it is to big. if you are in local server you can change in .ini file and increase the limit for uploading file and if you are using web server add in .htaccess file in the .htcaccess file add the following: php_value upload_max_filesize 500M php_value post_max_size 500M in php.ini add: upload_max_filesize = 500M post_max_size = 500M or you can split your csv file
{ "language": "en", "url": "https://stackoverflow.com/questions/21854236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Putting regex into a variable REG=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g (echo "1.2.3" | grep -Eq "$REG" ) && echo "matched" || echo "did not match" I get the error: test.sh: line 2: syntax error near unexpected token `(' test.sh: line 2: `REG=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g' Not very much to go on here. Trying to see if 1.2.3 meets the regex expression. The expression I got from here: https://github.com/mojombo/semver/issues/232 A: Use quotes so the shell doesn't barf on special characters. REG='/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g' Note that this regex will not work with grep. POSIX regex syntax is different and more limited than Perl syntax, which is what you've got. A: You ran into two major problems * *Bash handling special characters, escapes, and anything else it found in your string before storing it. This is solved by single quoting your string to prevent bash expansion/interpretation. *The Regex was written in Perl syntax, which grep does not support, it uses POSIX which is slightly different from Perl even though the two are similar. This is solved by removing the surrounding / /g and replacing all instances of \d which is not recognized by POSIX with [0-9]. Result: REG='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$'
{ "language": "en", "url": "https://stackoverflow.com/questions/45883345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: C# tableAdapter.Update() won't change the database record I want my program to be able to change one row in my Access database with the data from my form. The problem is that the update-function doesn't do anything. There are no error messages and the program compiles correct. Nothing changes in the database. Here is the code: private void btnTallenna_Click(object sender, EventArgs e) { string[] vanhat = new string[9]; lueVanhatTiedot(vanhat); hevosetTableAdapter.Connection.Close(); hevosetTableAdapter.Connection.Open(); try { hevosetTableAdapter.Update(txtNimi.Text, txtIka.Text, cmbPaino.Text, cmbKaytto.Text, cmbRotu.Text, cmbSukupuoli.Text, cmbKunto.Text, cmbRehunkayttokyky.Text, int.Parse(vanhat[0]), vanhat[1], vanhat[2],vanhat[3], vanhat[4], vanhat[5], vanhat[6], vanhat[7], vanhat[8]); this.hevosetBindingSource.EndEdit(); hevosetTableAdapter.Update(this.dsHevonen.Hevoset); hevosetTableAdapter.Connection.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } hevosetTableAdapter.Connection.Close(); } lueVanhatTiedot() function gets the original data for the record. Still learning to program so there may be stupid mistakes which I just can't notice. :) A: Have you called the "AcceptChanges" method on the DataSet?
{ "language": "en", "url": "https://stackoverflow.com/questions/19786010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mongoose ignores $ne while updating document I'm building a persistent html fields framework using Node, Mongoose, and Socket.io for the backend. I've run into what seems like a bug in Mongoose's update method. The documents in mongo look like this: { "_id" : "pickable_qty", "currently_connected" : [ ], "locks" : [ { socket_id: 'eQYVyz1z28rJZRPpAAAB', unique_values:{ merchant_warehouse_id: 11.1, product_item_id: 5555 } }, { socket_id: 'eQYVyz1z28rJZRPpAAAB', unique_values:{ merchant_warehouse_id: 11.2, product_item_id: 5555 } }, { socket_id: 'eQYVyz1z28rJZRPpAAAB', unique_values:{ merchant_warehouse_id: 11.1, product_item_id: 1234 } } ], "definition" : { "ajax_url" : "/persistent-fields/pickable_qty", "unique_keys" : [ "product_item_id", "merchant_warehouse_id" ], "max_idle_seconds" : 30, "field_type" : "text" }, "__v" : 0 } The problem arises when I start inserting subdocuments into the locks array. I insert them using Mongoose's update method like so: FieldSchema.update( { _id: 'pickable_qty', 'locks.unique_values': { '$ne': { merchant_warehouse_id: 11.1, product_item_id: 5334 } }, 'definition.unique_keys': { '$all': [ 'merchant_warehouse_id', 'product_item_id' ] } }, { '$push': { locks: { socket_id: 'eQYVyz1z28rJZRPpAAAB', unique_values: { merchant_warehouse_id: 11.1, product_item_id: 5334 } } } }, function(err, count, res){ console.log('err:', err, 'count:', count, 'res:', res); //err: null count: 1 res: { ok: true, n: 1, updatedExisting: true } } ); The first insert works exactly as expected, there were no locks in the array containing the unique values {merchant_warehouse_id: 11.1,product_item_id: 5334} so the document was found and the lock subdocument was inserted. However running this same update the second time should not insert a new locks subdocument because one already exists with the same unique_values and the $ne part of the query should cause it to return no matches to update. I have confirmed that doing a find with the same query returns no documents both on the MongoDB command line and using Mongoose's own Schema.find method, but the Schema.update method still finds a document and inserts a duplicate lock subdoc. Am I just going crazy or is there a reason why Mongoose's find method won't retrieve the document while update will? A: The problem is that you are querying whether or not an object matches a subdocument, and this can be tricky. What you want to do use a combination of $elemMatch and $ne in your query. var query = { _id: 'pickable_qty', 'locks': { $elemMatch: { merchant_warehouse_id: { $ne: 11.1 }, product_item_id: { $ne: 5334 } } }, 'definition.unique_keys': { '$all': [ 'merchant_warehouse_id', 'product_item_id' ] } } It's basically a query for a document inside of an array. A: After using MongoDB's query profiler, I figured out that Mongoose was switching the order of the keys in the lock's unique_values object while doing the update query. Then it was inserting the duplicate subdocuments with the keys in the correct order. So apparently MongoDB's $ne operator will match nested subdocument arrays only if the keys in the subdocument are in the same order as your query.
{ "language": "en", "url": "https://stackoverflow.com/questions/28375353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my SURF.detectAndCompute returns none before the array? I am trying to extract key point and descriptors but my SURF.detectAndCompute returns None in front of the array and because of that I cannot do the clustering. Below is my code: image_paths = [] image_group_id = [] image_group_names = os.listdir(train_path) descriptors = [] SURF = cv2.xfeatures2d.SURF_create() SURF.setHessianThreshold(5000) for group_id, train_group_path in enumerate(os.listdir(train_path)): image_path = train_path + '/' + train_group_path for path in os.listdir(image_path): full_image_path = image_path + '/' + path image_paths.append(full_image_path) image_group_id.append(group_id) _, des = SURF.detectAndCompute(cv2.imread(full_image_path), None) descriptors.append(des) And this is the of the descriptors that I tried to print: [None, array([[ 0.00140431, 0.00414569, 0.00156097, 0.00508978, -0.01072729, 0.03109567, 0.01673188, 0.04477221, -0.04659119, 0.0652261 , 0.04661125, 0.08301401, -0.00103816, 0.0069982 , 0.00168295, 0.00876924, 0.01606237, -0.00151245, 0.01966742, 0.01294267, -0.2951115 , -0.14716513, 0.32090443, 0.18698329, 0.21934257, -0.02404423, 0.29070902, 0.17538053, -0.03951943, 0.02635496, 0.04406727, 0.02923489, 0.03092461, -0.04000381, 0.03236163, 0.04539306, -0.26897454, -0.112547 , 0.33476326, 0.29709056, 0.2916087 , -0.01106649, 0.351532 , 0.19272245, -0.07418256, -0.04663706, 0.07452377, 0.04671762, 0.00109221, 0.00404389, 0.0019812 , 0.0101865 , 0.00381939, -0.01452297, 0.05944061, 0.05199388, 0.0035292 , -0.04607308, 0.03296318, 0.04701661, -0.00757545, -0.00286426, 0.00760168, 0.00306828]], dtype=float32) The None isn't supposed to be there. What can I do to fix this? I am new in this field, any advice is very appreciated. Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/71014359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reset scrollbar state on switching content I have a sample code with one button and 2 images that are shown conditionally. I need to scroll to the top of the content div, where images are shown but it stays in the same position as the previous content. I tried to separate buttons and content between separate divs but it didn't help. Is there a way to achieve this with only CSS. Here is the code and working example in codesandbox: https://codesandbox.io/s/upbeat-sutherland-9r0kh?file=/src/styles.css:0-206 The page: import { useState } from "react"; import "./styles.css"; export default function App() { const [isOpen, setIsOpen] = useState(true); return ( <div className="App"> <div className="buttonContainer"> <button onClick={() => setIsOpen(!isOpen)}>switch</button> </div> <div> {isOpen ? ( <img src="https://images.unsplash.com/photo-1574285013029-29296a71930e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=927&q=80" /> ) : ( <img src="https://images.unsplash.com/photo-1558064340-601a5c6ac442?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=987&q=80" /> )} </div> </div> ); } CSS: .App { font-family: sans-serif; text-align: center; display: flex; align-items: center; } .buttonContainer { position: fixed; height: 100vh; } button { position: absolute; height: 100px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/70212365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xpath - Extracting multiple specific differnt parts of text strings from one text node I have three samples of text nodes that and I want to extract three different parts of the text, using a universal x-path. First <p class="product-summary"> This is an amazing game from the company Midway Games. Excellent gameplay. Very good game. </p> Second <p class="product-summary"> New Line Cinema distributed this movie in 1995. </p> Third <p class="product-summary"> New game from 2011, with new 3D graphics. This game was made by NetherRealm Studios. </p> The extraction should be either Midway Games or New Line Cinema or NetherRealm Studios Note that the text node allways include just one company, never two or three (just one). My try is from this question but the problem is that it dosen't work nor include all three companies. substring('Midway Games',1,12*contains(//p[@class='product-summary']/following-sibling::text()[1], 'Midway Games')) A: As the input will only contain one of them, you can use concat to join the results. concat( substring('Midway Games', 1, 12*contains(//p[@class='product-summary'], 'Midway Games')), substring('Line Cinema', 1, 11*contains(//p[@class='product-summary'], 'Line Cinema')), substring('NetherRealm Studios', 1, 19*contains(//p[@class='product-summary'], 'NetherRealm Studios')) ) You can remove the line breaks that I added for readability as you want. I had to fix the query you provided: the text nodes are no following-siblings, but children. Your XPath processor will query the (concatenated) text nodes below that element anyway as contains works on strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/21662638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you create a read-only user in PostgreSQL? I'd like to create a user in PostgreSQL that can only do SELECTs from a particular database. In MySQL the command would be: GRANT SELECT ON mydb.* TO 'xxx'@'%' IDENTIFIED BY 'yyy'; What is the equivalent command or series of commands in PostgreSQL? I tried... postgres=# CREATE ROLE xxx LOGIN PASSWORD 'yyy'; postgres=# GRANT SELECT ON DATABASE mydb TO xxx; But it appears that the only things you can grant on a database are CREATE, CONNECT, TEMPORARY, and TEMP. A: Grant usage/select to a single table If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so: GRANT CONNECT ON DATABASE mydb TO xxx; -- This assumes you're actually connected to mydb.. GRANT USAGE ON SCHEMA public TO xxx; GRANT SELECT ON mytable TO xxx; Multiple tables/views (PostgreSQL 9.0+) In the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to type them one by one: GRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx; This only affects tables that have already been created. More powerfully, you can automatically have default roles assigned to new objects in future: ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO xxx; Note that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow. Multiple tables/views (PostgreSQL versions before 9.0) To avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required GRANT SELECT to each table/view: SELECT 'GRANT SELECT ON ' || relname || ' TO xxx;' FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace WHERE nspname = 'public' AND relkind IN ('r', 'v', 'S'); This should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created. A: From PostgreSQL v14 on, you can do that simply by granting the predefined pg_read_all_data role: GRANT pg_read_all_data TO xxx; A: Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that: test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser; A: If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser) db=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser; GRANT db=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser; GRANT db=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser; GRANT If your database is using customschema, execute the above but add one more command: db=> ALTER USER readonlyuser SET search_path=customschema, public; ALTER ROLE A: The not straightforward way of doing it would be granting select on each table of the database: postgres=# grant select on db_name.table_name to read_only_user; You could automate that by generating your grant statements from the database metadata. A: Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer): $ sudo -upostgres psql postgres postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE'; postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly; Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run: $ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf $ sudo service postgresql reload A: By default new users will have permission to create tables. If you are planning to create a read-only user, this is probably not what you want. To create a true read-only user with PostgreSQL 9.0+, run the following steps: # This will prevent default users from creating tables REVOKE CREATE ON SCHEMA public FROM public; # If you want to grant a write user permission to create tables # note that superusers will always be able to create tables anyway GRANT CREATE ON SCHEMA public to writeuser; # Now create the read-only user CREATE ROLE readonlyuser WITH LOGIN ENCRYPTED PASSWORD 'strongpassword'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonlyuser; If your read-only user doesn't have permission to list tables (i.e. \d returns no results), it's probably because you don't have USAGE permissions for the schema. USAGE is a permission that allows users to actually use the permissions they have been assigned. What's the point of this? I'm not sure. To fix: # You can either grant USAGE to everyone GRANT USAGE ON SCHEMA public TO public; # Or grant it just to your read only user GRANT USAGE ON SCHEMA public TO readonlyuser; A: Reference taken from this blog: Script to Create Read-Only user: CREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234' NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity'; \connect YourDatabaseName; Assign permission to this read-only user: GRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User; GRANT USAGE ON SCHEMA public TO Read_Only_User; GRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User; GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User; REVOKE CREATE ON SCHEMA public FROM PUBLIC; Assign permissions to read all newly tables created in the future ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User; A: I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default. A: I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!! user@server:~$ sudo su - postgres create psql user: postgres@server:~$ createuser --interactive Enter name of role to add: readonly Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) n Shall the new role be allowed to create more new roles? (y/n) n start psql cli and set a password for the created user: postgres@server:~$ psql psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14) Type "help" for help. postgres=# alter user readonly with password 'readonly'; ALTER ROLE connect to the target database: postgres=# \c target_database psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14) You are now connected to database "target_database" as user "postgres". grant all the needed privileges: target_database=# GRANT CONNECT ON DATABASE target_database TO readonly; GRANT target_database=# GRANT USAGE ON SCHEMA public TO readonly ; GRANT target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ; GRANT alter default privileges for targets db public shema: target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; ALTER DEFAULT PRIVILEGES A: Taken from a link posted in response to despesz' link. Postgres 9.x appears to have the capability to do what is requested. See the Grant On Database Objects paragraph of: http://www.postgresql.org/docs/current/interactive/sql-grant.html Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)." This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES". Also present is information about how GRANT functionalities compare to SQL standards. A: CREATE USER username SUPERUSER password 'userpass'; ALTER USER username set default_transaction_read_only = on;
{ "language": "en", "url": "https://stackoverflow.com/questions/760210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "580" }
Q: MongoDB Conditional Projection based on existence of query of subdocument in Array I have a schema in which properties can have respective "override" documents stored in an Array("overrides") E.g. { foo:'original foo', overrides: [ {property:'foo', value:'foo override'}, {property:'bar', value:'bar override'}, ] } I want to project a field for the override value if it exists, otherwise, the original property. So something like this project: { overrideOrOriginal: {$cond: fooOverrideExists ? fooOverrideValue : originalFooValue } So in this example, I would expect overrideOrOriginal to equal 'foo override' . If - {property:'foo', value:'foo override'} subDoc didn't exist in the overrides array (or if overrides array itself didn't even exist)...then I'd expect overrideOrOriginal = 'original foo' How can I do this? I was thinking I'd need $exists in tandem with $cond. But the complication here is that I'm searching for a subDoc in an Array based on a query Thanks! A: * *$ifNull to check if field is null then return empty array *$in to check "foo" is in overrides.property array *$indexOfArray to get index of array element in overrides.property array *$arrayElemAt to get element by specific index return from above operator let fooOverrideExists = "foo"; db.collection.find({}, { overrideOrOriginal: { $cond: [ { $in: [ fooOverrideExists, { $ifNull: ["$overrides.property", []] } ] }, { $arrayElemAt: [ "$overrides.value", { $indexOfArray: ["$overrides.property", fooOverrideExists] } ] }, "$foo" ] } }) Playground A: Query * *find the property , key-value(kv) (it works for all property names) (assumes your schema with only string value the value of that property) *checks if that it exists in the overrides array *if it exists, takes the value from the array *else keeps the original *checks also cases where override doesnt exists, or its empty array, or property doesn't exist *in case you want to do it only for a specific "foo" ignore the big first $set and use this code Test code here db.collection.aggregate([ { "$set": { "kv": { "$arrayElemAt": [ { "$filter": { "input": { "$objectToArray": "$$ROOT" }, "cond": { "$eq": [ { "$type": "$$this.v" }, "string" ] } } }, 0 ] } } }, { "$set": { "index": { "$indexOfArray": [ "$overrides.property", "$kv.k" ] } } }, { "$project": { "_id": 0, "overrideOrOriginal": { "$cond": [ { "$or": [ { "$eq": [ "$index", -1 ] }, { "$not": [ "$overrides" ] } ] }, "$kv.v", { "$arrayElemAt": [ "$overrides.value", "$index" ] } ] } } } ])
{ "language": "en", "url": "https://stackoverflow.com/questions/69365036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using OpenCV to take a particular amount of images without pressing any key I wish to write a program for face recognition. I want my program to automatically take a specific number of images(say,5). Here is what I am currently doing: import cv2 cam=cv2.VideoCapture(0) a=0 count=0 for a in range(5): ret,img=cam.read() cv2.imshow("Test",img) if not ret: break k=cv2.waitKey(1) print("Image"+str(count)+"saved") file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg' cv2.imwrite(file,img) a+=1 cam.release() cv2.destroyAllWindows() cam.release() cv2.destroyAllWindows() It shows "Image 0 saved" five times but in the folder(ad2), there is only a single image. Need some guidance. Thank you A: Lets start interpreting the code line-by-line: * * * *Variable initialization * * import cv2 cam=cv2.VideoCapture(0) a=0 count=0 *You load the opencv library and initialize the cam variable for webcam display. Then both a and count are intialized to 0. Now count variable is understandable, most probably count count the frames. What does a do? * *Display and save frames * *First-part * for a in range(0, 5): ret,img=cam.read() cv2.imshow("Test",img) if not ret: break *variable a declared again so we don't need to intialize at the beginning. Then current web-frame is being fetched. The frame is given as an input to imshow without even the current frame returned or not. The correct logic should be: * for a in range(5): ret,img=cam.read() if ret: cv2.imshow("Test",img) *Second-part * k=cv2.waitKey(1) print("Image"+str(count)+"saved") file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg' cv2.imwrite(file,img) a+=1 *Now, the k variable is initialized as a key for quiting the program when a key is pressed. Say, when q is pressed program terminates. * k=cv2.waitKey(1) & 0xFF if k == ord('q'): break *But if you break during the process, then you can't save the images. Therefore break should be at the end of the line. *For the rest of the code, you can use a as a counter. If you specify the start and end values. For each value a is increased by one. Then you can use it to discriminate the frames. Code: # Load the library import cv2 # Initialize webcam cam = cv2.VideoCapture(0) # Save the frames for a in range(0, 5): # Get current frame ret, img=cam.read() # If frame is returned if ret:  # Set the file-name file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2' + str(a) + '.jpg' # Write the frame cv2.imwrite(file, img) # Inform the user print("Image" + str(a) + "saved") # Display the frame cv2.imshow("Test", img) # If q is pressed quit k=cv2.waitKey(1) & 0xFF if k == ord('q'): break # Release the object cam.release() # Close the window cv2.destroyAllWindows()
{ "language": "en", "url": "https://stackoverflow.com/questions/66437449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Gradle Script To call a REST Web service without any 3rd party plugins, any pointers? Hi I need to call a REST service as part of the buildscript (Gradle) without any 3rd party plugins, how could I use Groovy to do that? (My first attempt) repositories { mavenCentral() } dependencies { complie "org.codehaus.groovy.modules.http-builder:http-builder:0.5.2" } task hello { def http = new HTTPBuilder("http://myserver.com:8983/solr/select?q=*&wt=json") http.auth.basic 'username', 'password' http.request(GET, JSON ) { req -> } } A: I'm using the JsonSlurper it looks quite simple and OS independent: import groovy.json.JsonSlurper String url = "http://<SONAR_URL>/api/qualitygates/project_status?projectKey=first" def json = new JsonSlurper().parseText(url.toURL().text) print json['projectStatus']['status'] A: Can't you just do new URL( 'http://username:password@myserver.com:8983/solr/select?q=*&wt=json' ).text A: Java has had a proper HTTP Client in the standard library since Java 9. Here's how you can use that from a Gradle script (Groovy): import groovy.json.JsonSlurper import java.net.http.* import static java.nio.charset.StandardCharsets.UTF_8 tasks.register('hello') { def url = new URL("http://myserver.com:8983/solr/select?q=*&wt=json") def req = HttpRequest.newBuilder(url.toURI()).GET().build() def res = HttpClient.newHttpClient() .send(req, HttpResponse.BodyHandlers.ofString(UTF_8)) def parsedJson = new JsonSlurper().parseText(res.body()) println parsedJson } A: this is working guys import java.io.* import groovyx.net.http.HTTPBuilder import groovyx.net.http.EncoderRegistry import static groovyx.net.http.Method.* import static groovyx.net.http.ContentType.* buildscript { repositories { mavenCentral() } dependencies { classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2' } } task hello { def http = new groovyx.net.http.HTTPBuilder("http://local.com:8983/solr/update/json") http.request(POST, JSON ) { req -> req.body{ } response.success = { resp, reader -> println "$resp.statusLine Respond rec" } } } A: This question is ranking so well on search engines that I keep stumbling on it. However, as others commented, I don't really like the accepted answer because it relies on curl. So here is a complete example w/o any prerequisite (no plugin, no curl, ...): import groovy.json.JsonSlurper import groovy.json.JsonOutput task getExample { doLast { def req = new URL('https://jsonplaceholder.typicode.com/posts/1').openConnection() logger.quiet "Status code: ${req.getResponseCode()}" def resp = new JsonSlurper().parseText(req.getInputStream().getText()) logger.quiet "Response: ${resp}" } } task postExample { doLast { def body = [title: "foo", body: "bar", userId: 1] def req = new URL('https://jsonplaceholder.typicode.com/posts').openConnection() req.setRequestMethod("POST") req.setRequestProperty("Content-Type", "application/json; charset=UTF-8") req.setDoOutput(true) req.getOutputStream().write(JsonOutput.toJson(body).getBytes("UTF-8")) logger.quiet "Status code: ${req.getResponseCode()}" // HTTP request done on first read def resp = new JsonSlurper().parseText(req.getInputStream().getText()) logger.quiet "Response: ${resp}" } } You can run this on your box as they use a public development API. A: The easiest way to call REST from groovy without external libraries is executing CURL. Here's an example of calling Artifactory, getting JSON back and parsing it: import groovy.json.JsonSlurper task hello { def p = ['curl', '-u', '"admin:password"', "\"http://localhost:8081/api/storage/libs-release-local?list&deep=1\""].execute() def json = new JsonSlurper().parseText(p.text) } A: The solution using Kotlin DSL and Fuel HTTP Client: import com.github.kittinunf.fuel.httpPost import com.github.kittinunf.result.Result buildscript { dependencies { "classpath"("com.github.kittinunf.fuel:fuel:2.3.1") } } tasks { register("post") { val (request, response, result) = "https://httpbin.org/post".httpPost().responseString() if (result is Result.Success) { println(result.get()) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/24058926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Quickly finding custom class in xib file I am in a kind of situation to check if any of components (say UILabel) in my nib file specified custom class in identity inspector. Currently the only way to find out is to go and check each component in every xib, is there any way we can search for it, similar to way where we can search for the occurrence of particular class in the Xcode, and the Xcode will quickly tell us which xib file contains the UILabel of that specific custom classes. A: Currently I would suggest to use command grep in terminal(Xcode could not search .xib file): grep -i -r --include=*.xib "TextToFindHere" /PathToSearchHere Another way is to right click your .xib file and Open As Source Code and use Command+F to search. But this method can only search one file a time.
{ "language": "en", "url": "https://stackoverflow.com/questions/20992246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TypeError: Cannot read property 'quote' of undefined React js Just to summarise, I'm creating a quote-generator using React js. The data is getting fetched from a mock API using React axios. However, when I'm trying to display the quote it gives me that above error line where I get error: {quotes[quoteIndex].quote} (quotes) gets populated with the data (quoteIndex) is basically an index in an array (.quote) is the attribute from the data Please find the relevant code // sample from .json file data "quotes": [ { "id":0, "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.", "author": "Thomas Edison" }, { "id":1, "quote": "You can observe a lot just by watching.", "author": "Yogi Berra" } ] } const [quotes, setQuotes] = useState([]); const [quoteIndex, setQuoteIndex] = useState(0); // fetching the data const getData = async() =>{ try{ const response = await Axios.get("/quotes"); if(response && response.data){ setQuotes(response.data); console.log(response.data); } }catch(error){ console.log(error); } } //this inside the return statement <div className="styleQuote"> <h3 className="styleText" >{quotes[quoteIndex].quote}</h3> </div> A: This is a very common problem when dealing with data that is loaded asynchronously. Here's how I would suggest debugging this to understand your problem: * *Remove the offending code so that you can observe what's happening. *Add console.log(quotes) in your component. You will see that it logs [] and then again with your array. *Next add console.log(quotes[quoteIndex]). Notice that it logs undefined and then an object. Consider that while the value is undefined, you cannot treat it like an object and attempt to access properties on it. *Add a check to make sure the value is an object before using it: // Nullsafe operator quotes[quoteIndex]?.quote // Or ternary quotes[quoteIndex] ? quotes[quoteIndex].quote : null Here is a simulated example: const async_quotes = [ { "id":0, "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.", "author": "Thomas Edison" }, { "id":1, "quote": "You can observe a lot just by watching.", "author": "Yogi Berra" } ] const {useState, useEffect} = React; const index = 1; const Example = () => { const [quotes, setQuotes] = useState([]); useEffect(() => { setTimeout(() => { setQuotes(async_quotes); }, 3000); }, []); console.log("quotes:", quotes); console.log("single quote:", quotes[index]); return <div>{quotes[index] ? quotes[index].quote : ''}</div> } ReactDOM.render(<Example />, document.getElementById('root')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/68718351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stop the Banner and Profile picture get change on MouseOver I have a MVC project which has a Banner in _Layout.cshtml <img src="../../SitePics/NewBanner.jpg") class="BannerSize" /> and a Img tag to get the Profile Pic according to the currect logges user <img src="../../@Model.TripPic" class="TripImage" align="left" /> and I have implemented Rating with Jason <script language="javascript" type="text/javascript" src="../../Scripts/jquery-1.4a2.js"></script> <script language="javascript" type="text/javascript"> $(function () { $("img").mouseover(function () { giveRating($(this), "FilledStar.png"); $(this).css("cursor", "pointer"); }); $("img").mouseout(function () { giveRating($(this), "EmptyStar.png"); }); $("img").click(function () { $("img").unbind("mouseout mouseover click"); // call ajax methods to update database var url = "/Rating/PostRating?rating=" + parseInt($(this).attr("id")); $.post(url, null, function (data) { $("#result").text(data); }); }); }); function giveRating(img, image) { img.attr("src", "/Content/Images/" + image) .prevAll("img").attr("src", "/Content/Images/" + image); } </script> <p> <img src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="1" /> <img src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="2" /> <img src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="3" /> <img src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="4" /> <img src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="5" /> </p> <div id="result"></div> My Issue Is whe I run the Program My Banner and Profile picture also get changed into Empty or Filled Starts when it runs over/Out mouse pointer.. Please help me to stop the Banner and Profile picture get change on MouseOver A: Short Answer : Add a class to the images for rating, say a class "rating" and then replace $("img") with $("img.rating") Long Answer : Ok, the jquery selector you are using is this $("img") which says select all images from the page. Hence the problem. Now what you should do, As you want to have the jquery run only for the 5 Rating images, you can have all the images have a common class like as shown below.. <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="1" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="2" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="3" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="4" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="5" /> and Now you can use your code like this... <script language="javascript" type="text/javascript"> $(function () { $("img.rating").mouseover(function () { giveRating($(this), "FilledStar.png"); $(this).css("cursor", "pointer"); }); $("img.rating").mouseout(function () { giveRating($(this), "EmptyStar.png"); }); $("img.rating").click(function () { $("img.rating").unbind("mouseout mouseover click"); // call ajax methods to update database var url = "/Rating/PostRating?rating=" + parseInt($(this).attr("id")); $.post(url, null, function (data) { $("#result").text(data); }); }); }); function giveRating(img, image) { img.attr("src", "/Content/Images/" + image) .prevAll("img").attr("src", "/Content/Images/" + image); } </script> A: Brilliant..... Thanks a lot Yasser... Code required a bit fixes but thanks to u now its working. Bellow I have given the working code.. its almost the same code u hv corrected for me but with capital letters in necessary places. <script> $(function () { $("img.Rating").mouseover(function () { giveRating($(this), "FilledStar.png"); $(this).css("cursor", "pointer"); }); $("img.Rating").mouseout(function () { giveRating($(this), "EmptyStar.png"); }); $("img.Rating").click(function () { $("img.Rating").unbind("mouseout mouseover click"); // call ajax methods to update database var url = "/Rating/PostRating?rating=" + parseInt($(this).attr("id")); $.post(url, null, function (data) { $("#result").text(data); }); }); }); function giveRating(img, image) { img.attr("src", "/Content/Images/" + image) .prevAll("img.Rating").attr("src", "/Content/Images/" + image); } </script> <p> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="1" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="2" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="3" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="4" /> <img class="Rating" src="../../Content/Images/EmptyStar.png" alt="Star Rating" align="middle" id="5" /> </p> <div id="result"></div> Yahooo .. Thanks a lot
{ "language": "en", "url": "https://stackoverflow.com/questions/12130839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Stream_get_contents() not working with Cron Job I have a script called index.php "public_html" folder in my host (see below for script content). A cronjob executes the "index.php" file once per minute. $handle = fopen('example.com', 'r'); $source= stream_get_contents($handle); echo $source; fclose($handle); The problem is every time "index.php" is executed using the cronjob, $source will be '' (an empty string)! But when I manually execute index.php using Firefox and refreshing it's tab, $source will be a string including the html source codes of example.com Is there any restriction settings in my web-host or somewhere else, preventing stream_get_contects() to log websites information?
{ "language": "en", "url": "https://stackoverflow.com/questions/56399865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Server 2003: Any disadvantages to moving website outside of wwwroot? My boss recently asked me if I could move our website outside of the wwwroot folder and place it into "C:\MySite", on windows server 2003. I tried doing so, and setting this up in IIS 6, but had no luck. The website wouldn't start up, so I placed the site back into wwwroot. So I have 2 questions: One, is there any disadvantage to moving a website outside of the wwwroot folder? I found it peculiar the site works fine in wwwroot, but won't start outside of it...and two, if there's no disadvantage, how can I get IIS to run the website properly if outside wwwroot? Thanks. A: Site can be anywhere, especially on local machine. Check if * *you copied all files to new location *you changed location of the root of the site in IIS Manager (Start->run->inetmgr) *check event log for any errors *check if accoutn app pool for the site runs under have permissions to read from new folder. A: It is quite simple and easy. Follow the steps here: http://support.microsoft.com/kb/172138 or http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5adfcce1-030d-45b8-997c-bdbfa08ea459.mspx?mfr=true
{ "language": "en", "url": "https://stackoverflow.com/questions/9695841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Rails, how do I output my date as a time in milliseconds in my CSV file? I'm using Rails 5.0.1. I use the following code to output my table data to CSV form ... def self.to_csv(from_date, to_date) attributes = %w{index_date value} #customize columns here values = CryptoIndexValue.where('index_date >= ? and index_date <= ?', from_date, to_date) .order(index_date: :desc) CSV.generate(headers: true) do |csv| csv << attributes values.each do |value| csv << attributes.map{ |attr| value.send(attr) } end end end The problem is, when my date (a PostGres 9.5 timestamp column) is output, it is output as 2017-08-01 20:00:09 UTC I would like it to get output as the time in milliseconds. How can I adjust the above to output my time as a time in milliseconds rather than the default date format? A: You can simply call .to_i on a DateTime object: timestamp = DateTime.now.to_i # => 1501617998 DateTime.strptime(timestamp.to_s, '%s') # => Tue, 01 Aug 2017 20:07:10 +0000 The timestamp is the seconds since Epoch. Multiply it by a thousand and you get milliseconds. In your case, you must make a hook for this case: attr_values = attributes.map do |attr| attr_value = value.send(attr) attr_value = attr_value.to_i * 1000 if attr_value.is_a?(DateTime) attr_value end csv << attr_values This means everytime an attribute returns a DateTime object, it will be converted to a timestamp * 1000. If you want to filter only few attrs to convert DateTime -> Timestamp, test the attr with a whitelist instead of testing attr_value's class.
{ "language": "en", "url": "https://stackoverflow.com/questions/45446738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what login should I keep for app (for appstore approval) I have created an app for Real estate where there are 4 sections. * *Home (where list of rent and sale are shown) *Admin (admin can login and enter data) *Search *More Now I will be uploading this app on the app store. For Admin section, what username and password should I keep so that Apple team can login into those for review purpose. Once approved, I will delete that user. Is there default username and password for Apple for review purpose? I am asking as while submitting the app, I cannot write username and password anywhere so that we can tell to Review team. A: You need to decide yourself what is the username and password you want Apple to use for review. When you submit the app or update the app, there is a section where you can supply those information, under App Review Information:
{ "language": "en", "url": "https://stackoverflow.com/questions/17510563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding extenal library to compiler toolchain for ARM I have downloaded compiler tool chain for ARM Target. My host machine: Linux Target H/w : ARM7 But i need to add some additional library with that tool chain. I need to know how to add new library to existing tool chain? Thanks Hari
{ "language": "en", "url": "https://stackoverflow.com/questions/34782421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Django field does not return Enum instances from query I have a simple custom field implemented to utilize Python 3 Enum instances. Assigning enum instances to my model attribute, and saving to the database works correctly. However, fetching model instances using a QuerySet results in the enum attribute being a string, instead of the respective Enum instance. How do I get the below EnumField to return valid Enum instances, rather than strings? fields.py: from enum import Enum from django.core.exceptions import ValidationError from django.db import models class EnumField(models.CharField): description = 'Enum with strictly typed choices' def __init__(self, enum_class, *args, **kwargs): self._enum_class = enum_class choices = [] for enum in self._enum_class: title_case = enum.name.replace('_', ' ').title() entry = (enum, title_case) choices.append(entry) kwargs['choices'] = choices kwargs['blank'] = False # blank doesn't make sense for enum's super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() args.insert(0, self._enum_class) del kwargs['choices'] return name, path, args, kwargs def from_db_values(self, value, expression, connection, context): return self.to_python(value) def to_python(self, value): if value is None or isinstance(value, self._enum_class): return value else: return self._parse_enum(value) def _parse_enum(self, value): try: enum = self._enum_class[value] except KeyError: raise ValidationError("Invalid type '{}' for {}".format( value, self._enum_class)) else: return enum def get_prep_value(self, value): if value is None: return None elif isinstance(value, Enum): return value.name else: msg = "'{}' must have type {}".format( value, self._enum_class.__name__) if self.null: msg += ', or `None`' raise TypeError(msg) def get_choices(self, **kwargs): kwargs['include_blank'] = False # Blank is not a valid option choices = super().get_choices(**kwargs) return choices A: After a lot of digging, I was able to answer my own question: SubfieldBase has been deprecated, and will be removed in Django 1.10; which is why I left it out of the implementation above. However, it seems that what it does is still important. Adding the following method to replaces the functionality that SubfieldBase would have added. def contribute_to_class(self, cls, name, **kwargs): super(EnumField, self).contribute_to_class(cls, name, **kwargs) setattr(cls, self.name, Creator(self)) The Creator descriptor is what calls to_python on attributes. If this didn't happen, querys on models would result in the EnumField fields in the model instances being simply strings, instead of Enum instances like I wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/34912460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flutter: How to draw a star I am trying to custom my container shape to look like this: I tried to do it with customPaint but I don't know very well this widget so I need help. How can I draw a shape like this? Is customPaint the right solution? A: You can copy paste run full code below modified code of package https://pub.dev/packages/flutter_custom_clippers 's StarClipper https://github.com/lohanidamodar/flutter_custom_clippers/blob/master/lib/src/star_clipper.dart code snippet class StarClipper extends CustomClipper<Path> @override Path getClip(Size size) { ... double radius = halfWidth / 1.3; ... Container( height: 200, width: 200, child: ClipPath( clipper: StarClipper(14), child: Container( height: 150, color: Colors.green[500], child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)), ), ), ), working demo full code import 'package:flutter/material.dart'; import 'dart:math' as math; class StarClipper extends CustomClipper<Path> { StarClipper(this.numberOfPoints); /// The number of points of the star final int numberOfPoints; @override Path getClip(Size size) { double width = size.width; print(width); double halfWidth = width / 2; double bigRadius = halfWidth; double radius = halfWidth / 1.3; double degreesPerStep = _degToRad(360 / numberOfPoints); double halfDegreesPerStep = degreesPerStep / 2; var path = Path(); double max = 2 * math.pi; path.moveTo(width, halfWidth); for (double step = 0; step < max; step += degreesPerStep) { path.lineTo(halfWidth + bigRadius * math.cos(step), halfWidth + bigRadius * math.sin(step)); path.lineTo(halfWidth + radius * math.cos(step + halfDegreesPerStep), halfWidth + radius * math.sin(step + halfDegreesPerStep)); } path.close(); return path; } num _degToRad(num deg) => deg * (math.pi / 180.0); @override bool shouldReclip(CustomClipper<Path> oldClipper) { StarClipper oldie = oldClipper as StarClipper; return numberOfPoints != oldie.numberOfPoints; } } void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 200, width: 200, child: ClipPath( clipper: StarClipper(14), child: Container( height: 150, color: Colors.green[500], child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)), ), ), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } } A: I was trying to create Turkish flag for fun. Creating crescent was easy but creating star is not look easy. so I just tried to use my geometric and trigonometric knowledge to draw but no success. while continuing searching I encountered this link . Yeess I found what I look for. of course it was about different topic but functions was useful. so I reach my goal at the end of night. So creating custom stars are possible with CustomPainter since now. Because I m sleepy and tired of being awake whole night I share all of code block with no further explanation. You can adjust offsetts according to your need. if any question. I m ready to answer. Enjoy coding. class TurkishFlagPaint extends CustomPainter { @override void paint(Canvas canvas, Size size) { // x and y coordinates of starting point final bx = 95; final by = 0; final paint = Paint(); paint.color = Colors.white; final innerCirclePoints = 5; //how many edges you need? final innerRadius = 80 / innerCirclePoints; final innerOuterRadiusRatio = 2.5; final outerRadius = innerRadius * innerOuterRadiusRatio; List<Map> points = calcStarPoints(bx, by, innerCirclePoints, innerRadius, outerRadius); var star = Path()..moveTo(points[0]['x'], points[0]['y']); points.forEach((point) { star.lineTo(point['x'], point['y']); }); canvas.drawPath( Path.combine( PathOperation.union, //this combine for crescent Path.combine( PathOperation.difference, Path()..addOval(Rect.fromCircle(center: Offset(-20, 0), radius: 80)), Path() ..addOval(Rect.fromCircle(center: Offset(2, 0), radius: 60)) ..close(), ), star,// I also combine cresscent with star ), paint, ); } //This function is life saver. //it produces points for star edges inner and outer. if you need to //rotation of star edges. // just play with - 0.3 value in currX and currY equations. List<Map> calcStarPoints( centerX, centerY, innerCirclePoints, innerRadius, outerRadius) { final angle = ((math.pi) / innerCirclePoints); var angleOffsetToCenterStar = 0; var totalPoints = innerCirclePoints * 2; // 10 in a 5-points star List<Map> points = []; for (int i = 0; i < totalPoints; i++) { bool isEvenIndex = i % 2 == 0; var r = isEvenIndex ? outerRadius : innerRadius; var currY = centerY + math.cos(i * angle + angleOffsetToCenterStar - 0.3) * r; var currX = centerX + math.sin(i * angle + angleOffsetToCenterStar - 0.3) * r; points.add({'x': currX, 'y': currY}); } return points; } @override bool shouldRepaint(CustomPainter oldDelegate) => true; } now you can use painter in a widget; Center( child: CustomPaint( painter: TurkishFlagPaint(), ), ), and the result will be like this : A: Yes, CustomPaint is the right solution. You can calculate the Path (series of points around the Container) and then paint it with the drawPath method of the canvas. For example, the path of a triangle would look like this: return Path() ..moveTo(0, y) ..lineTo(x / 2, 0) ..lineTo(x, y) ..lineTo(0, y); The Path starts at (0,y) (top-left), then a line to (x/2,0) (bottom-center) gets added and so on. This snipped was taken from this answer. A: This code will help you build a centered star, to use it you just have to instantiate it in a ClipPath import 'package:flutter/material.dart'; import 'dart:math' as math; const STAR_POINTS = 5; class StarClipper extends CustomClipper<Path> { @override Path getClip(Size size) { var centerX = size.width / 2; var centerY = size.height / 2; var path = Path(); var radius = size.width / 2; var inner = radius / 2; var rotation = math.pi / 2 * 3; var step = math.pi / STAR_POINTS; path.lineTo(centerX, centerY - radius); for (var i = 0; i < STAR_POINTS; i++) { var x = centerX + math.cos(rotation) * radius; var y = centerY + math.sin(rotation) * radius; path.lineTo(x, y); rotation += step; x = centerX + math.cos(rotation) * inner; y = centerY + math.sin(rotation) * inner; path.lineTo(x, y); rotation += step; } path.lineTo(centerX, centerY - radius); path.close(); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => false; } /// Instance ClipPath( clipper: StarClipper(), child: Container( color: Colors.red, width: 80, height: 80, ), )
{ "language": "en", "url": "https://stackoverflow.com/questions/63700728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to avoid file content repetition zipfile I need to compress multiple xml files and I achieved this with lxml, zipfile and a for loop. My problem is that every time I re run my function the content of the compressed files are repeating (being appended in the end) and getting longer. I believe that it has to do with the writing mode a+b. I thought that by using with open at the end of the code block the files would be deleted and no more content would be added to them. I was wrong and with the other modes I do not get the intended result. Here is my code: def compress_package_file(self): bytes_buffer = BytesIO() with zipfile.ZipFile(bytes_buffer, 'w') as invoices_package: i = 1 for invoice in record.invoice_ids.sorted('sin_number'): invoice_file_name = 'Invoice_' + invoice.number + '.xml' with open(invoice_file_name, 'a+b') as invoice_file: invoice_file.write(invoice._get_invoice_xml().getvalue()) invoices_package.write(invoice_file_name, compress_type=zipfile.ZIP_DEFLATED) i += 1 compressed_package = bytes_buffer.getvalue() encoded_compressed_file = base64.b64encode(compressed_package) My xml generator is in another function and works fine. But the content repeats each time I run this function. For example if I run it two times, the content of the files in the compressed file look something like this (simplified content): <?xml version='1.0' encoding='UTF-8'?> <invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="invoice.xsd"> <header> <invoiceNumber>9</invoiceNumber> </header> </facturaComputarizadaCompraVenta><?xml version='1.0' encoding='UTF-8'?> <invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="invoice.xsd"> <header> <invoiceNumber>9</invoiceNumber> </header> </facturaComputarizadaCompraVenta> If I use w+b mode, the content of the files are blank. How should my code look like to avoid this behavior? A: I suggest you do use w+b mode, but move writing to zipfile after closing the invoice XML file. From what you wrote it looks as you are trying to compress a file that is not yet flushed to disk, therefore with w+b it is still empty at time of compression. So, try remove 1 level of indent for invoices_package.write line (I can't format code properly on mobile, so can't post whole section).
{ "language": "en", "url": "https://stackoverflow.com/questions/72178397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: odbc_exec error with progress I am using Codeigniter Database Active Record (ODBC Driver). The application run well. But starting this day, there are error when trying to fetch data from Progress database (connected via odbc). The error message: Severity: Warning --> odbc_exec() [function.odbc-exec]: SQL error: [DataDirect][ODBC Progress OpenEdge Wire Protocol driver]Unexpected Network Error. ErrNum = 10054, SQL state 08S01 in SQLExecDirect D:\xampp\htdocs\wavinet2-permana\system\database\drivers\odbc\odbc_driver.php 153 Error is in odbc_exec command. When I try to fetch data without using Codeigniter Active Record, it work. Data fetched. Trying to var_dump($this->db_odbc->conn_id) it return Resource. Network error ? I try to set up LinkedServer on my SQLServer and run the query generated by ActiveRecord, it work, data fetched successfully. I'm confuse, what is another posibilities that cause the error ? A: First make certain that you have started up your database properly. There is a fairly substantial thread that has what sounds like it may be your problem here: http://www.progresstalk.com/showthread.php?116855-102B-ODBC-connection-Problem Also something else to look at if you are running over SSL: Change the data source PacketSize setting. The correct setting is 32. PacketSize=32 On Windows this will require a registry edit to make this change. See: http://knowledgebase.progress.com/articles/Article/8500
{ "language": "en", "url": "https://stackoverflow.com/questions/7790934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to avoid outside of request scope exception in silex application? After restructuring my silex1.2 application, I am now getting hit by: exception 'RuntimeException' with message 'Accessed request service outside of request scope. Try moving that call to a before handler or controller.' in ../vendor/silex/silex/src/Silex/Application.php:150 I used to setup the appilcation's config this way: $app = new Silex\Application(); $app->register(new ServiceControllerServiceProvider()); $app->register(new ConfigServiceProvider($configFile)); $fileFinder = new \Symfony\Component\Finder\Finder(); foreach ($fileFinder->in($configPath . 'country') as $file) { /* @var SplFileInfo $file */ $app->register(new ConfigServiceProvider($file->getRealPath())); } I now wanted to replace the foreach loop by injecting a specific value which I get from the user's request. So I wanted to access $request->query->get('country'); yet I cannot since app['request'] is out of scope at that point. I don't understand the error message, as in: * *When and why are request objects out of scope in silex? *How am I supposed to move the call before handler and controllers when it is the very first thing I do on setting up my application? Basically, I want to access request data early on on in order to get one value. How can I achieve that in order to bootstrap application accordingly? A: You try to use Request before it is initialized, before $app->run(). You can manually initialize Request: $app = new \Silex\Application(); $app['request'] = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); ..... $app->run($app['request']); or make lazy loading in service providers: $app['object1'] = $app->share(function ($app) { return new Object1($app['request']->query->get('country')); }); ... and somewhere in controller get these variable as $app['object1']
{ "language": "en", "url": "https://stackoverflow.com/questions/35323386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Login page is not appearing when the session expires I have one project developed using codeigniter In that when session expires I need to redirect to the login page. controller file //inherit the parent constructor parent::__construct(); //check whether it is an ajax call or not if($this->input->is_ajax_request()) { //check the session exist or not $status = $this->common_functions->verify_session('ajax_call'); //if session doesnot exist if(! $status) { //return the json echo json_encode(array("session_timeout"=>"true", "msg"=>"<h3>Session timed out.</h3> Please login once again.")); //exit exit; } } else { //Initialize the private property $this->_section = ''; //check the session exist or not $this->common_functions->verify_session(); } And in common function I have the code to redirect into login page
{ "language": "en", "url": "https://stackoverflow.com/questions/26139011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Auth Popup not working for React 17 App; Getting React warning is this why or how to fix? As shown in description, I am working on a React project and utilizing Firebase for Auth and popup is not firing but I think it might have to do with this warning from React. The warning I am getting from React is that Warning: Expected onClick listener to be a function, instead got a value of object type. I have been researching this and trying to problem solve for 2 days. Any pointers would be greatly appreciated :) Thank you!! Here is my Firebase Utils code for the auth: const config = { My config info }; firebase.initializeApp(config); const provider = new firebase.auth.GoogleAuthProvider(); provider.setCustomParameters({ prompt: 'select_account' }); export const signInWithGoogle = () => auth.signInWithPopup(provider) .then(function (result) { }).catch(error => { console.log(error); }) export default firebase; Now my Custom Button Component in React 17 import React from 'react'; import './custom-button.styles.scss'; const CustomButton = ({children, isGoogleSignIn, ...otherProps}) => ( <button className={`${isGoogleSignIn ? 'google-sign-in' : ''} custom-button`} {...otherProps}> {children} </button> ); export default CustomButton; Lastly my signin component in React lass SignIn extends React.Component { constructor(props) { super(props); this.state = { email: '', password: '' } } handleSubmit = event => { event.preventDefault(); this.setState({ email: '', password: '' }) } handleChange = event => { const { value, name } = event.target; this.setState({ [name]: value }) } render() { return ( <div className='sign-in'> <h2>I already have an account</h2> <span>Sign in with your email and password</span> <form onSubmit={this.handleSubmit}> <FormInput name='email' type='email' handleChange={this.handleChange} value={this.state.email} label='email' required /> <FormInput name='password' type='password' value={this.state.password} handleChange={this.handleChange} label='password' required /> <div className='buttons'> <CustomButton type='submit'> Sign in </CustomButton> <CustomButton onClick={signInWithGoogle} isGoogleSignIn> Sign in with Google </CustomButton> </div> </form> </div> ); } } export default SignIn; A: I finally figured this out. The firebase config file should have had a .then and .catch for the promise. Once I added this, it works fine now. I researched 3 days to figure this out. Taking a course, and the guy who produced this course didn't add this, although it was two years ago maybe it wasn't required then, but it is now.
{ "language": "en", "url": "https://stackoverflow.com/questions/66414770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upload JAR to Nexus OSS 3 I have just installed Nexus OSS 3.0.1-01 on my server and I don't know how to upload artifacts to my maven repository. I need to upload JDBC and other dependencies to it, but I cannot find how! It seems there is no section "Upload artifacts" as Nexus 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/38354033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: In Grails, is "property" a reserved word? In Grails, is "property" a reserved word? That is, can I name a domain class Property and have its owner reference it by properties? Example: class Thing { static hasMany = [properties: Property] } class Property { static belongsTo = [thing: Thing] } When I try to add a Property to a Thing I get the error: Exception thrown: No signature of method: org.codehaus.groovy.grails.web.binding.DataBindingLazyMetaPropertyMap.add() is applicable for argument types: (Property) values: [Property : null] groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.grails.web.binding.DataBindingLazyMetaPropertyMap.add() is applicable for argument types: (Property) values: [Property : null] at ConsoleScript10.run(ConsoleScript10:3) Is there a list of all Grails reserved words? A: I'm not sure that Property is reserved, but properties is treated specially for domain classes since it's used for data binding. What happens when you change: static hasMany = [properties: Property] to something like static hasMany = [myProperties: Property] A: Grails is a web framework. In general, only languages really have reserved words. The reserved words of Groovy are all those reserved by Java, plus a few others. The complete list is shown here. You'll notice that it does include "property", which was a big surprise to me, as I've no idea what it's used for, and I think/thought I know Groovy reasonably well. Perhaps it's reserved for future use? A: While I cant find any file with the name Property in grails, it is wise not to use such a common word - who knows when it might become reserved in the future? What would happen if you just prepended your classname with something, like BlahProperty?
{ "language": "en", "url": "https://stackoverflow.com/questions/1496240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to write to a file in assembly running under DOSBox I've made a procedure that writes to file, and made a label for writing into code, but the string i'm filling isn't being written to the file. Write procedure: proc WriteToFile mov ah,40h mov bx,[filehandle] mov cx,255 lea dx,[WriteStr] int 21h ret endp WriteToFile Writing label: WritingToFile: mov dx,offset w mov ah,9h int 21h mov dx,offset filenameStr mov bx,dx mov [byte ptr bx],13 ;8+1+3+1 mov ah,0Ah int 21h mov dx,offset filenameStr + 2 mov ah,9h int 21h mov [byte ptr filenameStr+2+8],0 call OpenFile xor bx,bx call WipeClean mov dx,offset filereaderline mov ah,9h int 21h mov dx,offset WriteStr mov bx,dx mov [byte ptr bx],100 ;8+1+3+1 mov ah,0Ah int 21h call WriteToFile call CloseFile call DisplayWriteStr jmp GetCommandLetter i've found out that on this procedure: CreatingFile: mov dx,offset c mov ah,9h int 21h mov dx,offset filenameStr mov bx,dx mov [byte ptr bx],13 ;8+1+3+1 mov ah,0Ah int 21h mov dx,offset filenameStr + 2 mov ah,9h int 21h mov [byte ptr filenameStr+2+8],0 call CreateFile ; call WriteToFile -it wrote,an accident call DisplayFileName xor bx,bx call CloseFile jmp GetCommandLetter it wrote this in the file: i $$$$$$$$$$$$$ HELP LIST: ----------- Commands are: /e-Exit /h-help /1-Says: 'Hello World!' $ Error $file name consists of 4 letters MUST!! (dont forget to add '.txt' at the end of the name: 'xmpl.txt')$ /r/ $ /c/ $ /w/ $ i $$$$$$$$$$$$$ HELP LIST: ----------- Commands are: /e-Exit /h-help /1-Says: 'Hello World!' $ Error $file name consists of 4 letters MUST!! (dont forget to add '.txt' at the end of the name: 'xmpl.txt')$ /r/ $ /c/ $ /w/ $ " in the file it created, than i saw my variable for writing a file is: WriteStr db 105,0,13 dup("$") it explains the duplicated $,i understood there is a problem with this variable mostly i suppose,how and to what can i change it so it would work? Full code: IDEAL MODEL small STACK 100h DATASEG szMsg1 db "Hi! What do you want to do?",10,13,10,13,"/h-help(see all the commands)",10,13,"/e-Exit",10,13,10,13,"$" szHelloWorld db 10,13,"Hello World!",10,13,"$" ErrorMsg db 10,13,"Illegal Command,Try again!",10,13,"$" filenameStr db 13,0,13 dup("$") WriteStr db 105,0,13 dup("$") help db 10,13,"HELP LIST:",10,13,"-----------",10,13,"Commands are:",10,13," /e-Exit",10,13," /h-help",10,13," /1-Says: 'Hello World!'",10,13,"$" filename db ?,0 filehandle dw 0 ErrorOpenMsg db 'Error',10,13,'$' FileNameLength db "file name consists of 4 letters MUST!! (dont forget to add '.txt' at the end of the name: 'xmpl.txt')","$" r db 10,13,"/r/ ","$" c db ,10,13,"/c/ ","$" w db ,10,13,"/w/ ","$" fileString db 255 dup (0) space db " ","$" CommandMsg db 10,13,"Enter your command:",10,13,"Command: ","$",10,13 filereaderline db "file's text:","$" CODESEG proc Exitp mov ax, 4c00h int 21h endp Exitp proc WipeClean mov [byte ptr fileString + bx], 0 inc bx cmp bx, 255 jb WipeClean ret endp WipeClean proc OpenFile ;Open file mov ah,3Dh xor al,al lea dx,[filenameStr+2] int 21h jc openerror mov [filehandle],ax ret openerror: mov dx,offset ErrorOpenMsg mov ah,9h int 21h ret endp OpenFile proc CreateFile mov ah,3ch mov cx,00000000b lea dx,[filenameStr+2] int 21h jc CreateError mov [filehandle],ax ret CreateError: mov dx,offset ErrorOpenMsg mov ah,9h int 21h ret endp CreateFile proc ReadFile mov ah,3fh mov bx,[filehandle] mov cx,255 lea dx,[fileString] int 21h ret endp ReadFile proc DeleteFile mov ah,41h lea dx,[filenameStr+2] int 21h endp DeleteFile proc DisplayFileString mov ah,09h lea dx,[fileString] int 21h endp DisplayFileString proc DisplayWriteStr mov ah,09h lea dx,[WriteStr] int 21h endp DisplayWriteStr proc DisplayFileName mov ah,09h lea dx,[filenameStr] int 21h endp DisplayFileName proc KeyStroke xor ax,ax int 16h endp KeyStroke proc WriteToFile mov ah,40h mov bx,[filehandle] mov cx,255 lea dx,[WriteStr] int 21h ret endp WriteToFile proc CloseFile mov ah,3Eh mov bx,[filehandle] int 21h ret endp CloseFile start: mov ax, @data mov ds, ax mov ah,0 mov al,2 int 10h mov dx,offset szMsg1 mov ah,9h int 21h jmp GetCommandLetter PrintLine: mov dx, offset szHelloWorld mov ah, 9h int 21h jmp GetCommandLetter _Error: mov dx,offset ErrorMsg mov ah,9h int 21h GetCommandLetter: mov dx,offset CommandMsg mov ah,9h int 21h mov ah, 1h int 21h mov bl,al mov ah, 1h int 21h mov bh,al compare: cmp bl,'/' jne _Error cmp bh,'h' je _help cmp bh,'H' je _help cmp bh,'1' je PrintLine cmp bh,'e' je _Exitp cmp bh,'E' je _Exitp mov dx,offset space mov ah,9h int 21h mov dx,offset FileNameLength mov ah,9h int 21h cmp bh,'c' je CreatingFile cmp bh,'C' je CreatingFile cmp bh,'r' je GetFileName cmp bh,'R' je GetFileName cmp bh,'w' je WritingToFile cmp bh,'W' je WritingToFile jmp _Error _Exitp: call Exitp _help: mov dx,offset help mov ah,9h int 21h jmp GetCommandLetter GetFileName: mov dx,offset r mov ah,9h int 21h mov dx,offset filenameStr mov bx,dx mov [byte ptr bx],13 ;8+1+3+1 mov ah,0Ah int 21h mov dx,offset filenameStr + 2 mov ah,9h int 21h mov [byte ptr filenameStr+2+8],0 call OpenFile xor bx,bx call WipeClean call ReadFile mov dx,offset filereaderline mov ah,9h int 21h call DisplayFileString call CloseFile jmp GetCommandLetter CreatingFile: mov dx,offset c mov ah,9h int 21h mov dx,offset filenameStr mov bx,dx mov [byte ptr bx],13 ;8+1+3+1 mov ah,0Ah int 21h mov dx,offset filenameStr + 2 mov ah,9h int 21h mov [byte ptr filenameStr+2+8],0 call CreateFile call WriteToFile call DisplayFileName xor bx,bx call CloseFile jmp GetCommandLetter WritingToFile: mov dx,offset w mov ah,9h int 21h mov dx,offset filenameStr mov bx,dx mov [byte ptr bx],13 ;8+1+3+1 mov ah,0Ah int 21h mov dx,offset filenameStr + 2 mov ah,9h int 21h mov [byte ptr filenameStr+2+8],0 call OpenFile xor bx,bx call WipeClean mov dx,offset filereaderline mov ah,9h int 21h mov dx,offset WriteStr mov bx,dx mov [byte ptr bx],100 ;8+1+3+1 mov ah,0Ah int 21h call WriteToFile call CloseFile call DisplayWriteStr jmp GetCommandLetter exit: mov ax, 4c00h int 21h END start A: Found the error in your code : the file is been opened in READ ONLY mode, so you can't write it : proc OpenFile ;Open file mov ah,3Dh mov al,2 ;<================== 0:READ ONLY, 1:WRITE ONLY, 2:READ/WRITE. lea dx,[filenameStr+2] int 21h jc openerror mov [filehandle],ax ret openerror: mov dx,offset ErrorOpenMsg mov ah,9h int 21h ret endp OpenFile
{ "language": "en", "url": "https://stackoverflow.com/questions/36924892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: can not add webpart to sharepoint page i create a website on my local machine but i can't add webpart to web page, it don't rise any error but th webpart don't display to the page. anyone help me. Thanks A: I know this is an old question, but it's ranking high in Google results, so I figured I'd answer it anyway. Make sure you're not running any code in the layout page's codebehind that calls and then closes SPContext.Current.Web. I had this exact behavior and that was the culprit To test, add a different web part to a default page layout. If it adds, then it's either your web part or your code behind. If you can't add any web parts to your custom layout, it's your code behind. If it's just your web part, it's your web part. Remember, SPContext.Current.Web returns a reference to the current SPWeb object. SharePoint will close the object itself when it's done, and closing it early can cause "unpredictable behavior." A: We had the same problem with Firefox some time ago, but the problem disappeared when we installed SP2 for SharePoint 2007. The only thing that surprises me is that you also have the problem with IE.
{ "language": "en", "url": "https://stackoverflow.com/questions/2951510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does FolderBrowserDialog not allow the desktop as SelectedPath when RootFolder is MyComputer? This works: FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.RootFolder = Environment.SpecialFolder.MyComputer; dlg.SelectedPath = "C:\\Almo\\"; dlg.ShowDialog(); This does not: FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.RootFolder = Environment.SpecialFolder.MyComputer; dlg.SelectedPath = "C:\\Users\\Almo\\Desktop\\"; dlg.ShowDialog(); The first opens a fileselection dialog starting in C:\Almo, the second started at MyComputer. Is there a way to make this work? The issue is my Application's default save location is the Desktop, and I want the user to be able to select a different location, and I want the dialog to start wherever the current location is. A: Try: Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) A: Use : dlg.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) this gets you the path of the desktop for the user who is running the code. A: Apparently, the Desktop in Win 7 doesn't actually exist at the path c:\Users\username\Desktop The system pretends it does at the command prompt and in windows explorer. But since it isn't there, the part of SelectedPath that requires its path to be under RootFolder disallows setting the path in that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7810189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Good program structure when updating values in databound object I'm writing a Winforms based tool and could use some guidance on the structure. The program communicates with a piece of hardware over serial, and shows a GUI to display values. Most values are either set from the pc, or read from the device. There are some which are set from the pc and then confirmed by the device. Currently I have an Model object with all the values the device can send or receive. It uses a PropertyChangedEvent with a databinding to show values on the Form. Additionally there is a encoder/decoder that listens on the event, which encodes changes and sends it to the serial port. In the serial port receive function the message is decoded, and the correct value in the Model is updated. The problem I'm having is that this will cause another PropertyChangedEvent, which will send another serial message. I'm looking for a good way to replace that listener with something else? I'd like to maintain the databinding to the form, so that every form element doesn't need an event. Most values are declared like this: private bool _voltageVBatToggle; public bool voltageVBatToggle { get => _voltageVBatToggle; set { if (_voltageVBatToggle != value) { _voltageVBatToggle = value; OnPropertyChanged(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/62005933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python only sends output interactvely When I run my python script (content irrelevant for this question, just uses print a couple of times) interactively, it sends the output straight away. When I use it in a pipe to tee or in an output redirection (./script.py > script.log) there is no output. What am I doing wrong? A: I suspect you're encountering output buffering, where it's waiting to get a certain number of bytes before it flushes. You can look at the unbuffer command if that is undesirable for you. A: As it turns out, Python detects whether or not you are using a tty, and increases its buffering when you are not. Several options on how to disable this can be viewed at this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/29849552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving a Date in Excel from Datepicker I am trying to save a date from a DatePicker on a Windows Form, into an existing Excel Spreadsheet. The following code assigns a string the ShortDate value of the DatePicker: if (checkupCheck.Checked) { newCheckupDate = checkupPicker.Value.Date.ToShortDateString(); } else { newCheckupDate = null; } This value is then saved after being placed into a data grid with the following code: for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { for (int k = 0; k < dataGridView1.Columns.Count; k++) { worksheet.Cells[i + 2, k + 1] = dataGridView1.Rows[i].Cells[k].Value.ToString(); } } workbook.Save(); When looking at the value of the newCheckupDate string at a breakpoint, it appears as I would like it "dd/mm/yyyy" When this is saved into Excel however, the cell will contain "dd/mm/yyyy 00:00:00". I do not want the time being added. The cell is formatted as a date cell. I have a feeling that Excel may be the cause of the problem here, but I don't know how to solve it. Thanks in advance for any help! A: Without delving into the why, you can simply format the cell in the loop : for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { for (int k = 0; k < dataGridView1.Columns.Count; k++) { worksheet.Cells[i + 2, k + 1] = dataGridView1.Rows[i].Cells[k].Value.ToString(); worksheet.Cells[i + 2, k + 1].NumberFormat = "dd/mm/yyyy" } } workbook.Save();
{ "language": "en", "url": "https://stackoverflow.com/questions/15312285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Typescript with Prisma I'm completely new to Typescript. I've started to work with Prisma and, coming from Sequelize, I miss simply writing stuff e.g. user.update({ ... }). It seems that Prisma returns just plain objects, and not classes, so I came up with this: import { Prisma, User as PrismaUser } from '@prisma/client'; import prisma from './path-to-prisma-instance'; class User { constructor(data: PrismaUser) { Object.assign(this, data); } update = async (props: Prisma.UserUpdateArgs) => { const data = await prisma.user.update({ ...props, where: { id: this.id } // Property 'id' does not exist on type 'User' }); return new User(data); }; } I'm getting that Property 'id' does not exist on type 'User'. How am I able to fix this?
{ "language": "en", "url": "https://stackoverflow.com/questions/75227367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ZF2 - validation within a bootstrap modal I am using twitter bootstrap in a zf2 application. A bootstrap modal displays a form containing user details, which i would like to be edited and saved. This is fairly trivial if i just submit form in the dialog and reload the whole page, but i am looking for a way to validate the form without it being submitted, and ideally if the data is valid, for it to pass the new data back to the page when the modal dialog is closed. How can i do this - would it need to be an ajax call? If so how would i structure that in my controller to return the form validation in a way that the errors can be rendered in the modal? Edit 1: Accepted answer below is spot on so far. The only thing i'm having trouble understanding is how to pass the validation data from the controller back to the bootstrap modal. So as a simple workflow - modal window opens loaded with an edit form bound to a User model, which shows the User data to be edited (all preloaded and assigned to the view already). The modal form is submitted, jquery hooks onto the form submit and sends the data as an ajax request to UserController::EditUserAction - where the form data is validated against the models inputfilter. If it turns out to be valid, the data is saved and the modal dialog is closed. If the data is invalid, say changing the email address to an address that already exists, the action returns a JsonModel with the form error(s) - how is this then passed to the bootstrap modal to highlight the field that produced the error, like the way that ZF does automatically when a form is typically submitted? A: You would do this with ajax. To understand what to do in your controller you have to understand the fundementals of an ajax call. jQuery makes this pretty easy. <script> $(function() { jQuery.ajax({ type: method, dataType: 'json', url: url, data: data, error: function(jqXHR, textStatus, errorThrown) { // Do something to handle the error }, success: function(data, textStatus, jqXHR) { // Do something else on successful validation } }); }); </script> The type is the HTTP method (eg. 'POST'). The url is the the route to get you to the controller which will give you a response. The data is the form data to be sent. More documentation is at https://api.jquery.com/jQuery.ajax/ The success function is executed if the HTTP response code is in the 200's. If you send an HTTP response code in the 400's or 500's, the javascript in the error function will be executed. This can be used to show an error in your modal dialog. You can modify the HTTP response code in a controller by using the following code: $this->getResponse()->setStatusCode(400); where 400 is the HTTP response code (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for more info about HTTP response codes) Then, to send data back with the response, return a JsonModel in the controller instead of a ViewModel return new JsonModel($array); where $array is the data you want to send back to the browser. If you end up doing this a lot, you might investigate the zf2 class \Zend\Mvc\Controller\AbstractRestfulController. A: if you want try for validation before submit form (send data to server) . may be better use client side validation . http://www.rayfaddis.com/blog/2013/05/27/jquery-validation-with-twitter-bootstrap
{ "language": "en", "url": "https://stackoverflow.com/questions/22418104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conflict between tensorflow/PIL/pillow and scikit-image? I am tying to rebuild my computer to run Spyder in a tensorflow environment for some image processing. In the past this worked and I had scikit-image working fully in that environment, and accessible from Spyder. Something has changed. I have: 1) re-installed Anaconda 2) re-installed tensorflow in a conda environment 3) installed libraries as needed, including Spyder. Then I start Spyder from the Conda navigator, in the tensorflow environment. This seems to work, I can import tensorflow, keras, pandas, sklearn, etc. But skimage only works partially. for example: import skimage works fine. But, import skimage.io as io does not. The error comes out as 'from PIL import Image' Is this something about PIL/pillow not co-existing in the same environment? Can this be fixed easily or should I just use opencv for image io? I have tried other modules in skimage and they all import. So using another package to open an image would not be the end of the world, but it would be nice to get the entirety of skimage working. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/54332306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select begin and end dates independently with dc.js Is it possible to filter a chart by selecting a specific begin date and then an end date without one interfering with the other? For example I'm using a barChart and I have a range like range: [01/02/2022 -> 17/02/2022] and my goal is to set a begin date and end date by selecting each one. I using crossFilter for filtering data but when I move the mouse or slide left or right both date are being set. My JS: MyChart .width(width) .height(250) .margins({ top: 10, right: 20, bottom: 25, left: 70 }) .dimension(moveMonths) .mouseZoomable(true) .transitionDuration(1) .x(d3.time.scale().domain([d3.min(data, function (d) { return d.dd; }), d3.max(data, function (d) { return d.dd; })])) .round(d3.time.month.round) .xUnits(d3.time.months) .title(function (p) { return p.key.getDate() + '/' + (p.key.getMonth() + 1) + '/' + p.key.getFullYear() + ' Total ' + formatDecimal(p.value, 2, ',', '.') + " €"; }) .elasticY(true) .renderHorizontalGridLines(true) .brushOn(false) .compose([ dc.lineChart(DeptVariationChart) .group(moveMonthsGroup) .valueAccessor(function (d) { return d.value; }) ]) .renderHorizontalGridLines(true) .yAxis().tickFormat(function (v) { return formatDecimal(v, 0, ',', '.') + " €"; });
{ "language": "en", "url": "https://stackoverflow.com/questions/71157519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Matching braces in ruby with a character in front I have read quite a few posts here for matching nested braces in Ruby using Regexp. However I cannot adapt it to my situation and I am stuck. The Ruby 1.9 book uses the following to match a set of nested braces /\A(?<brace_expression>{([^{}]|\g<brace_expression>)*})\Z/x I am trying to alter this in three ways. 1. I want to use parentheses instead of braces, 2. I want a character in front (such as a hash symbol), and 3. I want to match anywhere in the string, not just beginning and end. Here is what I have so far. /(#(?<brace_expression>\(([^\(\)]|\g<brace_expression>)*\)))/x Any help in getting the right expression would be appreciated. A: Using the regex modifier x enables comments in the regex. So the # in your regex is interpreted as a comment character and the rest of the regex is ignored. You'll need to either escape the # or remove the x modifier. Btw: There's no need to escape the parentheses inside [].
{ "language": "en", "url": "https://stackoverflow.com/questions/5428173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: const_cast and std::move to remove constness from non-reference I have an external library which I can not modify. The library declares a template function that for some reason returns const non-reference object: template<class C> const C foo(); I have another external library which I can not modify too. The library declares a class that is non-copyable and has a move constructor from a non-const object only: struct bar { bar(); bar(const bar&)=delete; bar(bar&&); }; Now I need to use foo<bar>. A simple usage: bar buz() { return foo<bar>(); } fails with main.cpp: In function 'bar buz()': main.cpp:13:21: error: use of deleted function 'bar::bar(const bar&)' return foo<bar>(); ^ main.cpp:8:5: note: declared here bar(const bar&)=delete; ^~~ which makes sense, and no simple workaround make the code compile. However, if I add some more complex workaround: bar buz() { return const_cast<bar&&>(std::move(foo<bar>())); } it compiles and the whole code work as expected (not only the simplified example above, but my real code too). However, it is safe, or am I running into some undefined behavior? Is there any better workaround? I have read and I understand questions about returning const from functions (1, 2), and the common answer there seems to be that returning const objects is discouraged in modern C++, but my question is not about it, but about how can I workaround the situation when an external library returns const object. A: Casting away the const will lead to undefined behavior if the move constructor for bar modifies anything. You can probably work around your issue like this without introducing undefined behavior: struct wrapped_bar { mutable bar wrapped; }; bar buz() { return foo<wrapped_bar>().wrapped; } Having the wrapped member be mutable means that the member is non-const even though the wrapped_bar object as a whole is const. Based on how foo() works, you may need to add members to wrapped_bar to make it work more like a bar. A: Technically speaking, you are exposing your program to undefined behavior. Since original object C (a temporary) was declared const, const-casting and modifying it is illegal and against the standard. (I assume, move constructor does some modifications to the movee). That being said, it probably works in your environment and I do not see a better workaround. A: As result of function call is by definition an R-Value itself, you do not need to apply std::move on it in return statement - const_cast<bar&&>(foo<bar>()) should be enough. That make code a little bit simpler to read. Still - there is no standard guarantee that this will always work for all bar types. Even more - this might in some cases lead to undefined behavior.(Imagine some very intrusive optimization, which completely eradicates foo and makes its result an object in "static data" segment of memory - like if foo was a constexpr. Then calling moving constructor, which probably modifies its argument, might lead to access violation exception). All you can do is either switch to different library (or, if possible, ask library maintainer to fix API) or create some unit test and include it in your build process - as long as test passes, you should be OK (remember to use same optimization settings as in "production" build - const_cast is one of those things which strongly depends on compilation settings).
{ "language": "en", "url": "https://stackoverflow.com/questions/37418387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Range not Found Error on for Loop in Google Apps Script I'm looking to create templates using GAS -- all I need is to copy and paste variables into designated cells, push the data, then move to the next. I had my script working great for a single template (the first set of variables). I tried to set up a loop, and now I'm hitting a "Range not found" error I'm going crazy trying to figure out. I had it working copying and pasting the variables out and generating the template, but struggling to get it to move to the next cell in each column. I made a range for each column where the script should loop through, meaning: Row 2 Col A, Row 2 Col B, Row 2 Col C, Row 2 Col D each go through the loop (variables get pasted, sheet gets created, etc), then we move onto Row 3 Col A, Row 2 Col B, so on so forth. function CreateTemplates() { var templatesNeeded = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test'); var rundownSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Exclusive Template Creation'); var tabname = templatesNeeded.getRange('A2').getValue(); var pasteTemplate = rundownSheet.getRange('e1:l150').getValues(); const row = 2; const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheetByName('Test'); const rows = sheet.getLastRow() - row + 1; const range = sheet.getRange(row, 1, rows, 1); const values = range.getValues().flat(); const dateRange = sheet.getRange(row, 2, rows, 1); const dateValues = dateRange.getValues().flat(); const gameRange = sheet.getRange(row, 3, rows, 1); const gameValues = gameRange.getValues().flat(); const typeRange = sheet.getRange(row, 4, rows, 1); const typeValues = typeRange.getValues().flat(); const broadcastRange = sheet.getRange(row, 5, rows, 1); const broadcastValues = broadcastRange.getValues().flat(); const matches = {}; values.forEach((value, i) => { if (value !== '') { rundownSheet.getRange('E3').setValue(templatesNeeded.getRange(values).getValue()); rundownSheet.getRange('B1').setValue(templatesNeeded.getRange(dateValues).getValue()); rundownSheet.getRange('B2').setValue(templatesNeeded.getRange(gameValues).getValue()); rundownSheet.getRange('B3').setValue(templatesNeeded.getRange(typeValues).getValue()); rundownSheet.getRange('H2').setValue(templatesNeeded.getRange(broadcastValues).getValue()); var tss = SpreadsheetApp.openById('16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ'); var sheet = tss.getSheetByName('Single Template'); sheet.copyTo(tss).setName(tabname); // Logger.log(value) sheet.getRange(1,1,pasteTemplate.length,pasteTemplate[0].length).setValues(pasteTemplate); Utilities.sleep(1000); } }); } I think it's clearly a problem with how I created my ranges (or something with the loop). Any thoughts are greatly, greatly appreciated. Here's a test link where the code would be hosted: https://docs.google.com/spreadsheets/d/1WeBgyi8JVfC02rCIB0T1eEbbmtpaXYF16qM7MLIzqPs/edit#gid=0 Here's a test link where the code will be pushed to (templates will be created here): https://docs.google.com/spreadsheets/d/16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ/edit#gid=804269175 Large improvement, but still hitting some errors. Now, it's looping through and creating the tabs, but the setValues to actually move the data over doesn't seem to work. Thought it was a timing issue - I added in utilities.sleep but still playing with it, with no luck yet. Basically, I want the variables to surface the data needed, that data to copy and paste to a template, then new variables, then new template: function createNewTemplates() { const ss = SpreadsheetApp.getActive(); const sh1 = ss.getSheetByName('Test'); const sh2 = ss.getSheetByName('Exclusive Template Creation'); const sh1A2 = sh1.getRange('A2').getValue(); const vs2 = sh2.getRange('e1:l150').getValues(); const sr = 2; // const sh1 = ss.getSheetByName('Test'); const vs1 = sh1.getRange(sr, 1, sh1.getLastRow() - sr + 1, 5).getValues(); const tss = SpreadsheetApp.openById('16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ'); vs1.forEach((r, i) => { if (r[0] !== '') { Utilities.sleep(2000); sh2.getRange('E3').setValue(r[0]); sh2.getRange('B1').setValue(r[1]); sh2.getRange('B2').setValue(r[2]); sh2.getRange('B3').setValue(r[3]); sh2.getRange('H2').setValue(r[4]); let sh = tss.getSheetByName('Single Template'); sh.copyTo(tss).setName(r[0]); let shnew = tss.getSheetByName(r[0]); Utilities.sleep(200); shnew.getRange(1, 1, vs2.length, vs2[0].length).setValues(vs2); } }); } A: Try this: function createNewTemplates() { const ss = SpreadsheetApp.getActive(); const sh1 = ss.getSheetByName('Test'); const sh2 = ss.getSheetByName('Exclusive Template Creation'); const vs2 = sh2.getRange('e1:l150').getValues(); const sr = 2; const vs1 = sh1.getRange(sr, 1, sh1.getLastRow() - sr + 1, 5).getValues(); const tss = SpreadsheetApp.openById('16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ'); let sh = tss.getSheetByName('Single Template'); vs1.forEach((r, i) => { if (r[0] !== '') { sh2.getRange('E3').setValue(r[0]); sh2.getRange('B1').setValue(r[1]); sh2.getRange('B2').setValue(r[2]); sh2.getRange('B3').setValue(r[3]); sh2.getRange('H2').setValue(r[4]); let shnew = sh.copyTo(tss).setName(r[0]); shnew.getRange(1, 1, vs2.length, vs2[0].length).setValues(vs2); } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/74622248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MYSQL update, replace delete with PHP array I have a query I need to run on a $_POST array with php it's quite simple as it takes all the values in the array then runs a query for each of the values which updates the database, here is the tricky part: As the array is dependent of checkboxes selected by the user the query has to either Update, Replace or remove values in DB dependent on what is in the $_POST array. I've only been able to have the query successfully run the last value in the array. I've tried both 'REPLACE INTO' and 'INSERT IGNORE INTO' but with no luck. I'm starting to think much more complex coding is going to be needed :( here's what I have so far: foreach($params['text'] as $boilertext) { $sql = 'UPDATE '._DB_PREFIX_.'boilertexts SET id_product="'.pSQL($boilertext).'" WHERE id_text="'.$params['id'].'"'; if(!Db::getInstance()->Execute($sql)) { echo mysql_error(); } } EDIT: This is the post params i'm getting: Array ( [text] => Array ( [0] => 8 [1] => 6 [2] => 10 ) // the Text ID i'm updating [textValue] => "Some text that I'm adding to another DB table" [id] => 28 // The ID that all the params from ['text'] are linked too [update] => update // Name of the submit button I'm using for form processing ) My issue is that although the foreach is running the SQL x amount of times for each query (tested it by printing out a count for each query) it will only insert the last value in ['text'] array. It also doesn't seem to update/remove the text id from the DB if it is not in the array A: What you really do is 3 updates on same record . Thats why you get only last value in database. You are updating record id_text=28 with values 8,6,10. A: It will only end up set as the last value, as you are updating the same record the number of times that you have values in your array. Only one field in one record is being processed, it can not magically become multiple records this way - you would need a separate table, or use INSERT.
{ "language": "en", "url": "https://stackoverflow.com/questions/4615188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doctrine Query count() and groupBy() date I need to find the total number of logins per day, but how would I select count() and group by day in DQL? I'm using Doctrine 2.3. public function getLoginCount() { return $this->createQueryBuilder('i') ->select('i') // and count(*) ->groupBy('i.timestamp') // group by day ->getQuery() ->execute() ; } I need something like this: Date | count 2013-01-01 | 6 2013-01-02 | 7 2013-01-03 | 3 A: From help on the Doctrine IRC channel you need to create a custom DQL function. Example: https://github.com/beberlei/DoctrineExtensions/blob/master/lib/DoctrineExtensions/Query/Mysql/Day.php Docs: http://www.doctrine-project.org/blog/doctrine2-custom-dql-udfs.html A: A bit late for OP, but maybe someone will find it handy. I was able to achieve that with the DQL query bellow: $dql = ' SELECT SUBSTRING(i.timestamp, 1, 10) as date, COUNT(i) as count FROM Entity i GROUP BY date '; $query = $entityManager->createQuery($dql); return $query->getResult(); I think similar should be doable with Doctrine query builder.
{ "language": "en", "url": "https://stackoverflow.com/questions/14791767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to resign first responder from text field when user tap elsewhere? I have filled my view with ScrollView (same size as the view) and I'm stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any idea on how to do that ? I'm using the following method but it's not working as expected: - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { [textField resignFirstResponder]; return YES; } Thx for helping, Stephane A: I found the answer here: If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES] The endEditing(_:) method is designed right for it Causes the view (or one of its embedded text fields) to resign the first responder status. A: UIViewController inherits from UIResponder so a naive way (I am pretty sure is not the smartest way to do it) would be by overwriting the following methods (at least 1 of them) – touchesBegan:withEvent: – touchesMoved:withEvent: – touchesEnded:withEvent: - touchesCancelled:withEvent: Next you could get the touched view by doing UITouch *touch = [touches anyObject]; UIView *touchedView = [touch view]; finally resign the first responder if that view is not your text field if(touchedView != textField){ [textField resignFirstResponder]; } _ Demerits of this approach: You will have to handle the "tap" by yourself. (Same problem as the old iOS 3.1 or earlier). You will have to come up with your own implementation to differentiate single taps from drags, swipes, double taps, long taps, etc. Is not hard to get it working well but it is not likely you get it exactly the same way Apple detects taps (timings, distances, thresholds count!) However, that depends on your needs. If your view structure is simple enough then you could add a gesture recognizer to the container view and resign the first responder every time the handler is called :) Hope this helps A: Nobody has yet presented the best answer here: [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil]; From the documentation on this method: Normally, this method is invoked by a UIControl object that the user has touched. The default implementation dispatches the action method to the given target object or, if no target is specified, to the first responder. Subclasses may override this method to perform special dispatching of action messages. I bolded the relevant part of that paragraph. By specifying nil for the to: parameter, we automatically call the given selector on the first responder, wherever it is, and we don't need to have any knowledge of where in the view hierarchy it is. This can also be used to invoke other methods on the first responder as well, not just cause it to resign first responder status. A: -(BOOL)textFieldShouldReturn:(UITextField *)textField { [self.TextField resignFirstResponder]; return YES; } A: Give a unique Tag to your UITextfield (i.e. 333), then to resign the first responder do this: UITextField *textField = (UITextField *)[self.view viewWithTag:333]; [textField resignFirstResponder]; A: For a more robust and clean solution add a tap gesture recognizer to your primary view. This will work better with nested views and will be cleaner than secret buttons in code and UI builder. In your view did load: UITapGestureRecognizer* tapBackground = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)]; [tapBackground setNumberOfTapsRequired:1]; [self.view addGestureRecognizer:tapBackground]; ..and define your target action to be triggered on tap: -(void) dismissKeyboard:(id)sender { [self.view endEditing:YES]; } A: The best option is the shortest way ;) - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } A: Using Swift you can do this: func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside)) self.view.addGestureRecognizer(tap) } @objc func hideKeyboardByTappingOutside() { self.view.endEditing(true) } A: Just create an IBOutlet or pointer to the text field and call [textField resignFirstResponder]; from where ever you want. A: UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapTodissmiss)]; [self.view addGestureRecognizer:tap]; and selector -(void)TapTodissmiss{ [self.txtffld resignFirstResponder]; } A: I am posting this as a separate answer because a lot of the other answers recommend using [textField resignFirstResponder]. This is causing an invalid capability error in Xcode 11.5 with the incomprehensible addition "Unable to insert COPY_SEND" On a iPad with iOS 9.3.6: 2020-05-23 20:35:01.576 _BSMachError: (os/kern) invalid capability (20) 2020-05-23 20:35:01.580 _BSMachError: (os/kern) invalid name (15) On a iPad with iPadOS 13.5: 2020-05-23 20:38:49 [Common] _BSMachError: port 12f0f; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" On a iPhone with iOS 13.5: 2020-05-23 20:43:34 [Common] _BSMachError: port d503; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" [textField resignFirstResponder] cannot be used anymore. A: When possible the best option is to make your UIView to inherit from UIButton instead. You just need to change it in Interface Builder and immediately you will get the options to create an Action "Touch Up Inside" like any other button. Your view will work as usual because UIButton is still a view but you will get notified when someone taps on the view. There you can call [self.view endEditing:YES]; To resign any keyboard. Please note that if your view is an UIScrollView this solution is not for you. A: Create your IBOutlet in ViewController.h file like below: //YOUR ViewController.h FILE #import <UIKit/UIKit.h> @interface ViewController : UIViewController { //WIRE THIS WITH YOUR UITextField OBJECT AT YOUR .xib FILE IBOutlet UITextField *yourIBOutletUITextField; } @end Add this to your ViewController.m file: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [yourIBOutletUITextField resignFirstResponder]; } like below: //YOUR ViewController.m FILE #import "ViewController.h" @implementation ViewController //ADD THIS METHOD BELOW - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [yourIBOutletUITextField resignFirstResponder]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end A: For my implementation, [self.view endEditing:YES] did not work. To finally make sure the keyboard was hidden, I had to make one of my views the first responder, and then immediately make it resign as per the function below: -(void) hideKeyboardPlease{ [uiTextTo becomeFirstResponder]; [uiTextTo resignFirstResponder]; } A: This is what I do... UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAllKeyboards)]; tapGesture.cancelsTouchesInView = NO; [self.view addGestureRecognizer:tapGesture]; -(void) hideAllKeyboards { [textField_1 resignFirstResponder]; [textField_2 resignFirstResponder]; [textField_3 resignFirstResponder]; . . . [textField_N resignFirstResponder]; } A: This is the easiest way iv found that works consistently. Just add a tap gesture recognizer on the view and you're good to go. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } A: Update I found another simple way simply declare a property :- @property( strong , nonatomic) UITextfield *currentTextfield; and a Tap Gesture Gecognizer:- @property (strong , nonatomic) UITapGestureRecognizer *resignTextField; In ViewDidLoad _currentTextfield=[[UITextField alloc]init]; _resignTextField=[[UITapGestureRecognizer alloc]initWithTarget:@selector(tapMethod:)]; [self.view addGestureRecognizer:_resignTextField]; Implement the textfield delegate method didBeginEditing -(void)textFieldDidBeginEditing:(UITextField *)textField{ _currentTextfield=textField; } Implement Your Tap Gesture Method (_resignTextField) -(void)tapMethod:(UITapGestureRecognizer *)Gesture{ [_currentTextfield resignFirstResponder]; } A: Create a big button behind it all, and the button's callback calls resignFirstResponder to every input you have. Just make sure to put everything that the user interacts with on top of the button. Of course the button will be custom rect and transparent. I would look into implementing an IBOutletCollection called resignables and set every input to that collection. And the button callback iterates over that collection calling resignFirstResponder to them all. Edit: if it is a re-sizable scroll view, remember to correctly set the re-size markers in the button's view option, that way the button will always expand and contract to the scrollview's height and width
{ "language": "en", "url": "https://stackoverflow.com/questions/7794959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: coordinates for google maps from MySQL database, the right way for optimization? Is there a right way of getting coordinates from mysql for Google Maps? The current way I'm doing is I have jQuery script to get coordinates from a populated element which I use MySQL to populate a list of coordinates. // jQuery script to get the coordinates var coordArray = []; $(".marker").each(function(index,div) { var coords = $(this).data("coords").split(","); coordArray.push([coords[0],coords[1]]); }); //while loop in PHP and I have displayed the coordinates within a <div> element: while($row = $sql->fetch(PDO::FETCH_ASSOC)) { <div class="marker" data-coords="<?php echo $row['lat'].",".$row['lng'];?>">stuff</div> } Is there a better way of doing so? Or would this be okay as well? A: In your php you would create an array of the values from DB in your while loop. Then output this array to a javascript variable using json_encode $arr=array(); while($row = $sql->fetch(PDO::FETCH_ASSOC)){ $arr[]=array( $row['lat'], $row['lng']); } echo `<script>var markerData='. json_encode( $arr).';</script>'; This will create a JavaScript array in page you would loop over to create markers: <script> var markerData=[ [100,40], [99,37]/* etc*/]; </script> You could also retirve the JSOn data using AJAX depending on your needs
{ "language": "en", "url": "https://stackoverflow.com/questions/14077566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OR tag is not working with Cucumber Runner class For some reason when i apply OR tags in Runner class it not working my console just print 0 scenarios 0 steps 0.01ms But when I provide individual tags then it works fine, can anyone provide timely help to fix this issue, please let me know what is missing here Feature file Feature: Validate foreign exchange rates for positive and negative scenarios Scenario Outline: Verify rates for latest and past dated foreign exchange rates Given rates for foreign exchange rates When user calls Get http request with <Uri> Then user gets success with status code 200 And <base> in response body is <baseValue> @Regression Examples: Positive scenarios |Uri |base |baseValue| |/api/latest |base |EUR | |/api/2020-05-08|base |EUR | |/api/2010-01-14|base |EUR | Scenario Outline: Verify the response from invalid url for Given rates for foreign exchange rates When user calls invalid Get http request with <Uri> Then user gets error message with status code 400 @NegativeTest Examples: Negative scenarios |Uri | |/api/ | |/api/2020-02-30| |/api/20100114 | Runner Class @RunWith(Cucumber.class) @CucumberOptions( features="src/main/java/features",//the path of the feature files glue= {"stepDefinitions"},//the path of the step definition files tags= {"@Regression,@NegativeTest"},**// this one is not working** //tags = {"@Regression"}, monochrome=true //display the console output in a proper readable format ) public class TestRunner { } A: Seems you are using the latest version of cucumber and it doesn't recognize the old way of mentioning multiple tags. For the mentioned example ,we can run both scenarios by mentioning tags = {"@Regression or @NegativeTest"} in runner class (ie tags = {"@Regression,@NegativeTest") should be given as tags = {"@Regression or @NegativeTest"}) Also in the above query , i could see that tags are used above example keyword. Normally the tags can be used at the feature file level or before the scenario/scenario outline keywords
{ "language": "en", "url": "https://stackoverflow.com/questions/61749573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looping through all the worksheets in a workbook This is my code to loop through all worksheets. I want to copy particular cell value from all the sheets and paste it to my master sheet. First i tried for one work sheet, its working fine. I modified the same code to loop through all the worksheets in the workbook. I displayed worksheets name and data which i want to copy. Its going to all the worksheets properly but i am not getting the data for worksheets except first sheet. Even its not displaying in msgbox except for first worksheet. For Each ws In ActiveWorkbook.Worksheets If Range("C3").Value = "" Then Coverge_ID = Range("C2") MsgBox Coverge_ID ThisWorkbook.Worksheets(2).Activate Range("A1").Offset(I, 0) = Coverge_ID I = I + 1 Else Coverge_ID = Range("C3") MsgBox Coverge_ID ThisWorkbook.Worksheets(2).Activate Range("A1").Offset(I, 0) = Coverge_ID I = I + 1 End If MsgBox ws.Name Next ws A: Couple of things: * *You're not actually referring to the sheet in the loop by qualifying Range() with your ws variable *You don't need to activate the worksheet to append a value to it Try the below code instead: Dim ws As Worksheet Dim i As Long Dim Coverage_ID As String For Each ws In ActiveWorkbook.Worksheets If ws.Range("C3").Value = "" Then Coverage_ID = ws.Range("C2").Value MsgBox Coverage_ID ThisWorkbook.Worksheets(2).Range("A1").Offset(i, 0) = Coverage_ID i = i + 1 Else Coverage_ID = ws.Range("C3").Value MsgBox Coverage_ID ThisWorkbook.Worksheets(2).Range("A1").Offset(i, 0) = Coverage_ID i = i + 1 End If MsgBox ws.Name Next ws
{ "language": "en", "url": "https://stackoverflow.com/questions/24932331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find the class of the clicked item using Jquery I have the following code: $(".perf-row").click(function(e) { if (e.target.tagName.toLowerCase() == "a") { pageTracker._trackPageview($(this).attr("rel")); return true; //link clicked } else { window.open($(this).attr("rel"));return false; } }); to the conditional statment of if (e.target.tagName.toLowerCase() == "a") i would like to also add "OR class is equal to price". I'm not quite sure how to do that, i can't seem to find the class of the clicked element (which will be a td inside the table row). i've tried $(this).class, $(this.class) but neither work.... Help would be greatly appreciated! A: To see whether the element has class .price, use the $.hasClass() method. $(this).hasClass("price"); A: You could combine both your tests into a single jQuery command: if( $(e.target).is('.price, a') ) { .... } That tests if the target is either has the class price, or is an a tag, or is both. If you wanted to test that it was an a tag and had the price class, you would use this: if( $(e.target).is('a.price') ) { .... } Update: I may have misread your question. If you were going to add this second test to the same if test, then use my code. If you wanted to add a else if then use the .hasClass method as explained by the other answers. A: you can try: $(this).attr("class"); but this will return you names of all the classes applied to the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/1885941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: type parameters generics in interfaces and concrete classes I'm creating something like this and got struck about the usage of generics in java. Idea: Producer produces something of type T and consumers contains command objects, command objects holds different mediators. Mediators holds objects of type Subject and updates values of type T Note: I'm doing this to understand how generics works in terms of inheritance of the generic types and composition of the type parameter definitions in generic type intefaces and concrete classes, so please don't bother about rationale of the design. Interfaces definitions: Composition: * *IObserver *ISubject which holds object of type T and IObserver. *IMediator holds objects of type ISubject and type T *ICommand holds objects of type IMediator and type T *IProducerConsumer holds objects of type T and ICommand. There are some concrete Objects for the corresponding interfaces. I defined interfaces like this: public interface IObserver<T> public interface ISubject<T,O extends IObserver<T>> Cool until now. But Now the problems started. public interface IMediator<T,S extends ISubject<T,O>, O extends IObserver<T>> compiler is forcing me to do this. I mean O extends IObserver<T> as above. So, I infered that I can't define like below public interface IMediator<T,S extends ISubject<T,O extends IObserver<T>> > I concluded: that inner type parameter definition must not be expanded as above. So, finally happy with public interface IMediator<T,S extends ISubject<T,O>, O extends IObserver<T>> Now mess started in ICommand public interface ICommand <T,M extends IMediator<T, ?, ?>>, I'm struck now compiler is not accepting many of my possibilities even what inference i made as above. I mean public interface ICommand <T,M extends IMediator<T, S, o>, S extends ISubject<T, IObserver<T>>,O extends IObserver<T>> is not working. I don't want to user wild card I want to tell to the compiler something more concrete. My questions are: * *Is my inference correct as in ICommand definition. *How to interpret the above case studies. *What are the best defintions assuming that I want to insert T and must able to get and put. *What is the rules and relations of the type parameter definitions in interface and implemented classes. Please explain ? A: Generics with Bound Parameters (no wildcards) * *Is my inference correct as in ICommand definition? No. Two reasons * *You have written a small 'o' while passing it to Mediator. (I guess it's just a typing mistake.) *You passed IObserver<T> in stead of O to ISubject which would definitely cause a parameter bound mismatch. Correct Version: interface ICommand<T, M extends IMediator<T, S, O>, S extends ISubject<T, O>, O extends IObserver<T>> * *How to interpret the above case studies? * *The first thing you'd need to understand that you have one unknown type T and five interfaces. *Therefore you would have total six concrete types which have to be included progressively in the interface declarations. (You explicitly asked not to bother about rationale of the design.) *If you write them in a correct order, it becomes much more manageable. Interface declarations: interface IObserver<T> interface ISubject<T, O extends IObserver<T>> interface IMediator<T, O extends IObserver<T>, S extends ISubject<T,O>> interface ICommand<T, O extends IObserver<T>, S extends ISubject<T, O>, M extends IMediator<T, O, S>> interface IProducerConsumer<T, O extends IObserver<T>, S extends ISubject<T, O>, M extends IMediator<T, O, S>, C extends ICommand<T, O, S, M>> * *What are the best defintions assuming that I want to insert T and must able to get and put? * *If you want to get and put object of type T, what you probably need is bunch of interfaces which take only one parameter T. Generics will enforce that all would be compatible as T will be replaced by same type everywhere. *Your current system is too rigid. In real scenario, you would never have so many implementations of these interfaces (unless you are re-implementing facebook in java) so that you'd have many possible combinations of the implementations and you want to ensure compatibility. *Generics enforces type-safety by applying restrictions which are good. But you should not put restrictions just because you can put them. You are losing flexibility, readability and maintainability of your code. *You should add bounds only when you need them. They should not affect the design in any way before contracts between interfaces have been decided. Possibly sufficient way: interface IObserver<T> interface ISubject<T> interface IMediator<T> interface ICommand<T> interface IProducerConsumer<T> * *What is the rules and relations of the type parameter definitions in interface and implemented classes? * *The only relation between type parameters in interfaces and implementing class that I can think of is that implementing class has to provide a type to replace the generic type parameter. *In some cases, that type can again be a generic type in which case the responsibility of providing concrete type is forwarded to the code using the class reference or another class which extends that class. It may even be recursive! *The rules are not written in the language, in stead, you are applying all the rules on this mechanism when you make any type parameter bound. So as long as you are supplying a type which qualifies against all of your rules, you are good to go. *More rules means more robust but less flexible/readable. So do the trade of wisely. Two simple cases: // General way private class ProductObserver implements IObserver<Product> { } private ProductObserver productObserver; // Aspect oriented way private class LoggerObserver<T> implements IObserver<T> { } private LoggerObserver<Product> loggerObserver; * *Lastly, I'd suggest you to read (comprehensive) Java Generics FAQ by Angelika Langer if you have any further doubt. *If you keep experimenting like this, you might as well end up inventing a design pattern. Don't forget to share it with us when you do :D Hope this helps. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/22829533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MySQL: Mass Conversion Script for Table Engine I'm trying to figure out how to convert en mass from database table engine A to table engine B (in this case, from MyISAM to InnoDB). I know I can do it for individual tables using the MySQL workbench, but i'd like a script or a program that can do the conversion en mass. Anyone got any ideas? * EDIT * I'd prefer an SQL query that I could use to do this, without using php, if possible. A: In pseudo code using information_schema tables: $rows = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'yourDBName' AND ENGINE LIKE 'engineA'"; foreach ($rows as $table) { $query = 'ALTER TABLE '.$table.' ENGINE = engineB'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/4904956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get specific property from all items from the list I have list of Contacts: public class Contact { private string _firstName; private string _lastName; private int _age; /// <summary> /// Constructor /// </summary> /// <param name="fname">Contact's First Name</param> /// <param name="lname">Contact's Last Name</param> /// <param name="age">Contact's Age</param> public Contact(string fname, string lname, int age) { _firstName = fname; _lastName = lname; _age = age; } /// <summary> /// Contact Last Name /// </summary> public string LastName { get { return _lastName; } set { _lastName = value; } } /// <summary> /// Contact First Name /// </summary> public string FirstName { get { return _firstName; } set { _firstName = value; } } /// <summary> /// Contact Age /// </summary> public int Age { get { return _age; } set { _age = value; } } } and here I am creating my list: private List<Contact> _contactList; _contactList = new List<Contact>(); _contactList.Add(new Contact("John", "Jackson", 45)); _contactList.Add(new Contact("Jack", "Doe", 20)); _contactList.Add(new Contact("Jassy", "Dol", 19)); _contactList.Add(new Contact("Sam", "Josin", 44)); Right now I am trying to get all the first names of all the contacts in separate list using LINQ. So far I tried: public List<string> FirstNames { get { return _contactList.Where(C => C.FirstName.ToList()); } } A: public List<string> FirstNames { get { return _contactList.Select(C => C.FirstName).ToList(); } } A: You want to use the Select method, not Where here: _contactList.Select(C => C.FirstName).ToList(); Further, the need for the ToList() only exists because the property demands it. You could return an IEnumerable<string> instead if you wanted to get rid of that.
{ "language": "en", "url": "https://stackoverflow.com/questions/19962862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Vue.js: Get src of an Image and pass it to another call as I tried to explain in my headline: I'm currently trying to get into Vue.js and overall everything I've tried worked up to this point. Now I want to include exif.js to read the exif-data of an image I uploaded to my App. Im also using Laravel, which I think shouldn't matter in this situation. Here's my code from my modal.blade.php: <div class="modal-body"> <img class="img-fluid" ref="imageExif" v-if="Object.keys(file).length !== 0" src="" :src="'{{ asset('storage/' . Auth::user()->name . '_' . Auth::id()) }}' + '/' + file.type + '/' + file.name + '.' + file.extension" :alt="file.name"> <button class="btn btn-primary" @click="modalExif()">Show exif-data</button> </div> showModal() call: <div class="file-header-wrapper" v-if="file.type == 'image'" @click="showModal(file)"> <img v-if="file === editingFile" src="" :src="'{{ asset('storage/' . Auth::user()->name . '_' . Auth::id()) }}' + '/' + savedFile.type + '/' + savedFile.name + '.' + savedFile.extension" :alt="file.name"> <img v-if="file !== editingFile" src="" :src="'{{ asset('storage/' . Auth::user()->name . '_' . Auth::id()) }}' + '/' + file.type + '/' + file.name + '.' + file.extension" :alt="file.name"> </div> And here is what I've written in my app.js so far: showModal(file) { this.file = file; this.modalActive = true; }, modalExif() { console.log('Button clicked'); this.imageExif = this.$refs.imageExif.src; //I THINK THIS LINE IS MY PROBLEM EXIF.getData(this.imageExif, function() { console.log('image info', this); console.log('exif data', this.exifdata); }); }, As I mentioned in my Code, I think my problem is that I don't refer to my image correctly, but I'm pretty new to Vue and I don't know the syntax well enough to correct this by myself. I also don't know if this is the correct way of doing it, It's just one way I could think of. GitHub Repo: https://github.com/annazeller/mediadb Thank you :) A: You are accessing the img element's src correctly. Based on the README for exif-js, you need to pass the actual img element as the first parameter to the getData method, not the src: this.imageExif = this.$refs.imageExif; EXIF.getData(this.imageExif, function() { console.log('image info', this); console.log('exif data', this.exifdata); });
{ "language": "en", "url": "https://stackoverflow.com/questions/54562662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ threads race condition simulation Here is a C++ program that runs 10 times with 5 different threads and each thread increments the value of counter so the final output should be 500, which is exactly what the program is giving output. But i cant understand why is it giving 500 every time the output should be different as the increment operation is not atomic and there are no locks used so the program should give out different outputs in each case. edit to increase probability of race condition i increased the loop count but still couldn't see any varying output #include <iostream> #include <thread> #include <vector> struct Counter { int value; Counter() : value(0){} void increment(){ value = value + 1000; } }; int main(){ int n = 50000; while(n--){ Counter counter; std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread([&counter](){ for(int i = 0; i < 1000; ++i){ counter.increment(); } })); } for(auto& thread : threads){ thread.join(); } std::cout << counter.value << std::endl; } return 0; } A: You're just lucky :) Compiling with clang++ my output is not always 500: 500 425 470 500 500 500 500 500 432 440 A: Note Using g++ with -fsanitize=thread -static-libtsan: WARNING: ThreadSanitizer: data race (pid=13871) Read of size 4 at 0x7ffd1037a9c0 by thread T2: #0 Counter::increment() <null> (Test+0x000000509c02) #1 main::{lambda()#1}::operator()() const <null> (Test+0x000000507ed1) #2 _M_invoke<> /usr/include/c++/5/functional:1531 (Test+0x0000005097d7) #3 operator() /usr/include/c++/5/functional:1520 (Test+0x0000005096b2) #4 _M_run /usr/include/c++/5/thread:115 (Test+0x0000005095ea) #5 <null> <null> (libstdc++.so.6+0x0000000b8c7f) Previous write of size 4 at 0x7ffd1037a9c0 by thread T1: #0 Counter::increment() <null> (Test+0x000000509c17) #1 main::{lambda()#1}::operator()() const <null> (Test+0x000000507ed1) #2 _M_invoke<> /usr/include/c++/5/functional:1531 (Test+0x0000005097d7) #3 operator() /usr/include/c++/5/functional:1520 (Test+0x0000005096b2) #4 _M_run /usr/include/c++/5/thread:115 (Test+0x0000005095ea) #5 <null> <null> (libstdc++.so.6+0x0000000b8c7f) shows the race condition. (Also, on my system the output shows results different than 500). The options for g++ are explained in the documentage for g++ (e.g.: man g++). See also: https://github.com/google/sanitizers/wiki#threadsanitizer. A: Just because your code has race conditions does not mean they occur. That is the hard part about them. A lot of times they only occur when something else changes and timing is different. here are several issues: incrementing to 100 can be done really fast. So your threads may be already halfway done before the second one is started. Same for the next thread etc. So you never know you have really 5 in parallel. You should create a barrier at the beginning of each thread to make sure they start all at the same time. Also maybe try a bit more than "100" and only 5 threads. But it all depends on the system / load / timing. etc. A: to increase probability of race condition i increased the loop count but still couldn't see any varying output Strictly speaking you have data race in this code which is Undefined Behavior and therefore you cannot reliably reproduce it. But you can rewrite Counter to some "equivalent" code with artificial delays in increment: struct Counter { int value; Counter() : value(0){} void increment(){ int val=value; std::this_thread::sleep_for(std::chrono::milliseconds(1)); ++val; value=val; } }; I've got the following output with this counter which is far less than 500: 100 100 100 100 100 101 100 100 101 100
{ "language": "en", "url": "https://stackoverflow.com/questions/39529000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: no value given fr one or more required parameters I'm trying to prevent SQL injections. Am I doing this right? (I'm using MS Access.) Should I still use sqlparameter? OleDbParameter[] myparm = new OleDbParameter[2]; myparm[0] = new OleDbParameter("@UserID", UserName.Text); myparm[1] = new OleDbParameter("@Password", encode); string queryStr = "SELECT * FROM TMUser WHERE UserID=@UserID AND Password=@Password"; OleDbConnection conn = new OleDbConnection(_connStr); OleDbCommand cmd = new OleDbCommand(queryStr, conn); conn.Open(); OleDbDataReader dr = cmd.ExecuteReader(); A: Close! string queryStr = "SELECT * FROM TMUser WHERE UserID=@UserID AND Password=@Password"; OleDbConnection conn = new OleDbConnection(_connStr); OleDbCommand cmd = new OleDbCommand(queryStr, conn); cmd.Parameters.AddWithValue("@UserID", UserName.Text); cmd.Parameters.AddWithValue("@Password", encode); The parameters are part of the command object and you use the Parameters.AddWithValue method to set the parameter values to what you have defined in the query string. By the way, you should be using using statements to encapsulate some of your objects, here is what I typically do: using (OleDbConnection conn = new OleDbConnection(_connStr)) using (OleDbCommand = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "SELECT ..."; cmd.Parameters.AddWithValue(...); cmd.ExecuteReader(); //... } That way you don't have to worry about cleaning up resources if something goes wrong inside or closing the connection when you are done.
{ "language": "en", "url": "https://stackoverflow.com/questions/29933323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Reactive Security API Gateway with OpenID Connect, using private_key_jwt (login.gov) I'm following along with this 2-part tutorial. * *Part 1 *Part 2 The goal described: The API Gateway will serve as example of performing an OAuth 2 Authorization code flow based Login with session management. Furthermore it will display how to augment HTTP requests with the proper OAuth bearer token as required by the resource server. Key take-away being that the access/refresh token as acquired from Keycloak will never be exposed to the browser. The difference is that I'm not leveraging Keycloak, I am using Login.gov, and -- from my experience -- integrating with them can be quite painful, despite their decent documentation The problem: The tutorial thinks I can get away with something as basic as: ... .oauth2Login() Previously, when I was NOT using a gateway paradigm or reactive programming model, I had done a lot of tweaking of oauth on my security config to integrate with Login.gov, such as: ... .oauth2Login() .loginPage(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL) .authorizationEndpoint() .authorizationRequestResolver(new LoginGovAuthorizationRequestResolver(clientRegistrationRepository)) .authorizationRequestRepository(authorizationRequestRepository()) .and() .tokenEndpoint() .accessTokenResponseClient(accessTokenResponseClient()) .and() .failureHandler(new LoginGovAuthenticationFailureHandler()) .successHandler(new LoginGovAuthenticationSuccessHandler()) There's obviously a lot going on here, but the point is: all those jumping through hoops was mostly to do a couple things (that I can remember): * *add 2 params in the request resolver * *acr_values (constant: could be added in config authorization_uri) *nonce (22-character min, and at least then required a resolver) additionalParameters.put("acr_values", LoginGovConstants.LOGIN_GOV_LOA1) additionalParameters.put("nonce", nonce) Furthermore, the converter apparently necessitated me signing my own JWT and providing it client_assertion and the constant client_assertion_type parameters: @Override RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest) { RequestEntity<?> originalRequestEntity = super.convert(authorizationCodeGrantRequest) String registrationId = resolveRegistrationId(authorizationCodeGrantRequest) if(registrationId == LoginGovConstants.LOGIN_GOV_REGISTRATION_ID) { ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(registrationId) String clientId = clientRegistration.clientId String clientSecret = clientRegistration.clientSecret String tokenUri = clientRegistration.providerDetails.tokenUri Long expirationTime = LoginGovConstants.LOGIN_GOV_TOKEN_EXPIRATION_TIME String jwt = JWT.create() .withSubject(clientId) .withIssuer(clientId) .withAudience(tokenUri) // Should be an un-guessable, random string generated by the client .withJWTId(UUID.randomUUID().toString()) .withExpiresAt(new Date(System.currentTimeMillis() + expirationTime)) .sign(Algorithm.RSA256(keystoreUtil.rsaPublicKey(), keystoreUtil.rsaPrivateKey())) HttpHeaders headers = originalRequestEntity.headers MultiValueMap<String, String> formParameters = originalRequestEntity.body as MultiValueMap<String, String> URI uri = originalRequestEntity.url formParameters.add("client_assertion", jwt) formParameters.add("client_assertion_type", LoginGovConstants.LOGIN_GOV_CLIENT_ASSERTION_TYPE) return new RequestEntity<?>(formParameters, headers, HttpMethod.POST, uri) } } Suffice to say, at the time I implemented my previous solution, it seemed like a lot of backflips to accomplish some extra URL parameters that I thought Spring Security should provide by default. So if we can improve on my previous appraoch, I would appreciate some guidance. Nevertheless, with this new API gateway approach, I'm further confused, considering Webflux and a reactive paradigm. For example: * *OAuth2AuthorizationCodeGrantRequestEntityConverter vs. ServerOAuth2AuthorizationCodeAuthenticationTokenConverter *OAuth2AuthorizationRequestResolver vs. ServerOAuth2AuthorizationRequestResolver What is the overlap between these classes, if any? Is there an easier way to accomplish what I had previously done with these different Server* classes? Current behavior: Following the tutorial I mentioned, I have a partial flow going with my gateway, but the picture is not complete: spring: application: name: gateway security: oauth2: client: registration: login-gov: client-id: \${LOGIN_GOV_CLIENT_ID} authorization-grant-type: authorization_code redirect-uri: "{baseUrl}/{action}/oauth2/code/{registrationId}" scope: - openid - email provider: login-gov: authorization-uri: https://idp.int.identitysandbox.gov/openid_connect/authorize token-uri: https://idp.int.identitysandbox.gov/api/openid_connect/token?client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer user-info-uri: https://idp.int.identitysandbox.gov/api/openid_connect/userinfo jwk-set-uri: https://idp.int.identitysandbox.gov/api/openid_connect/certs user-name-attribute: sub Login.gov is using the private_key_jwt authentication method, and that seems to mean I have no "client-secret". Is this why it was necessary for me to create and sign my own JWT in my previous implementation? This is the output of the gateway when I've hit a gateway endpoint (/api/user/api/v1/savesearches/) that should eventually redirect to an actual service. The login flow initiates as expected, and I enter my credentials on the integration Login.gov page. Once I submit, I am ultimately redirected back to an error page /login?error 2020-04-20 14:10:30.934 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-10] HTTP GET "/api/user/api/v1/savesearches/" 2020-04-20 14:10:30.983 DEBUG 15352 --- [oundedElastic-2] o.s.w.s.s.DefaultWebSessionManager : Created new WebSession. 2020-04-20 14:10:30.995 DEBUG 15352 --- [oundedElastic-2] .s.u.m.MediaTypeServerWebExchangeMatcher : httpRequestMediaTypes=[text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] 2020-04-20 14:10:30.996 DEBUG 15352 --- [oundedElastic-2] .s.u.m.MediaTypeServerWebExchangeMatcher : Processing text/html 2020-04-20 14:10:30.996 DEBUG 15352 --- [oundedElastic-2] .s.u.m.MediaTypeServerWebExchangeMatcher : text/html .isCompatibleWith text/html = true 2020-04-20 14:10:30.997 DEBUG 15352 --- [oundedElastic-2] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-10] Completed 302 FOUND 2020-04-20 14:10:31.006 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-11] HTTP GET "/oauth2/authorization/login-gov" 2020-04-20 14:10:31.017 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-11] Completed 302 FOUND 2020-04-20 14:10:31.853 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-12] HTTP GET "/api/user/api/v1/savesearches/" 2020-04-20 14:10:31.861 DEBUG 15352 --- [ctor-http-nio-5] .s.u.m.MediaTypeServerWebExchangeMatcher : httpRequestMediaTypes=[text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] 2020-04-20 14:10:31.861 DEBUG 15352 --- [ctor-http-nio-5] .s.u.m.MediaTypeServerWebExchangeMatcher : Processing text/html 2020-04-20 14:10:31.861 DEBUG 15352 --- [ctor-http-nio-5] .s.u.m.MediaTypeServerWebExchangeMatcher : text/html .isCompatibleWith text/html = true 2020-04-20 14:10:31.861 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-12] Completed 302 FOUND 2020-04-20 14:10:31.868 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-13] HTTP GET "/oauth2/authorization/login-gov" 2020-04-20 14:10:31.874 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-13] Completed 302 FOUND 2020-04-20 14:10:44.361 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-14] HTTP GET "/login/oauth2/code/login-gov?code=d2236ca8-1458-4631-b067-057f461d2a71&state=pp0V-IpV75MSgq995i5IUoQvuaFGhBXBJyRiHsAhQvM%3D" 2020-04-20 14:10:44.382 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.r.f.client.ExchangeFunctions : [312e7ca5] HTTP POST https://idp.int.identitysandbox.gov/api/openid_connect/token?client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer 2020-04-20 14:10:44.950 DEBUG 15352 --- [ctor-http-nio-5] org.springframework.web.HttpLogging : [312e7ca5] Writing form fields [grant_type, code, redirect_uri, client_id, code_verifier] (content masked) 2020-04-20 14:10:45.080 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.r.f.client.ExchangeFunctions : [312e7ca5] Response 400 BAD_REQUEST 2020-04-20 14:10:45.094 DEBUG 15352 --- [ctor-http-nio-5] org.springframework.web.HttpLogging : [312e7ca5] Decoded [{error=Client assertion Nil JSON web token}] 2020-04-20 14:10:45.095 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-14] Completed 302 FOUND 2020-04-20 14:10:45.099 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-15] HTTP GET "/login?error" 2020-04-20 14:10:45.101 DEBUG 15352 --- [ctor-http-nio-5] o.s.w.s.adapter.HttpWebHandlerAdapter : [eae7892d-15] Completed 200 OK What stands out to me is very clear here. I can see the authorization step succeed, as indicated by the redirect to /login/oauth2/code/login-gov?code=d2236ca8-1458-4631-b067-057f461d2a71&state=pp0V-IpV75MSgq995i5IUoQvuaFGhBXBJyRiHsAhQvM%3D with the code and state parameters existing. What is confusing are the parameters provided to the the token endpoint: it only has the client_assertion_type that I provided in the config above, but it should have the actual client_assertion (JWT) too. I presume, this is all the hoop-jumping I had done before to create a JWT in the custom converter, but I never understood why Spring didn't do this for me? Am I missing some basic configuration step? If not, I could use some help to re-implement the converter in a reactive (ServerWebExchange) kind of way. Thank you for your patience. A: FYI Spring Security 5 does not yet support private_key_jwt which is why you're having to do extra work to get it working. (Adding an answer as I don't have enough reputation to comment)
{ "language": "en", "url": "https://stackoverflow.com/questions/61330618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find memory and runtime used by a NuSMV model Given a NuSMV model, how to find its runtime and how much memory it consumed? So the runtime can be found using this command at system prompt: /usr/bin/time -f "time %e s" NuSMV filename.smv The above gives the wall-clock time. Is there a better way to obtain runtime statistics from within NuSMV itself? Also how to find out how much RAM memory the program used during its processing of the file? A: One possibility is to use the usage command, which displays both the amount of RAM currently being used, as well as the User and the System time used by the tool since when it was started (thus, usage should be called both before and after each operation which you want to profile). An example execution: NuSMV > usage Runtime Statistics ------------------ Machine name: ***** User time 0.005 seconds System time 0.005 seconds Average resident text size = 0K Average resident data+stack size = 0K Maximum resident size = 6932K Virtual text size = 8139K Virtual data size = 34089K data size initialized = 3424K data size uninitialized = 178K data size sbrk = 30487K Virtual memory limit = -2147483648K (-2147483648K) Major page faults = 0 Minor page faults = 2607 Swaps = 0 Input blocks = 0 Output blocks = 0 Context switch (voluntary) = 9 Context switch (involuntary) = 0 NuSMV > reset; read_model -i nusmvLab.2018.06.07.smv ; go ; check_property ; usage -- specification (L6 != pc U cc = len) IN mm is true -- specification F (min = 2 & max = 9) IN mm is true -- specification G !((((max > arr[0] & max > arr[1]) & max > arr[2]) & max > arr[3]) & max > arr[4]) IN mm is true -- invariant max >= min IN mm is true Runtime Statistics ------------------ Machine name: ***** User time 47.214 seconds System time 0.284 seconds Average resident text size = 0K Average resident data+stack size = 0K Maximum resident size = 270714K Virtual text size = 8139K Virtual data size = 435321K data size initialized = 3424K data size uninitialized = 178K data size sbrk = 431719K Virtual memory limit = -2147483648K (-2147483648K) Major page faults = 1 Minor page faults = 189666 Swaps = 0 Input blocks = 48 Output blocks = 0 Context switch (voluntary) = 12 Context switch (involuntary) = 145
{ "language": "en", "url": "https://stackoverflow.com/questions/53565566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use Alternate Extension for .sql files in Sql Server I'm looking for a way to have sql server treat a different file extension as an .sql file... My company policy is that we name stored procedures as .PRC instead of .SQL. This makes it a hassle to open a file and edit/execute it. While I can associate SQL Server Management Studio to open the file, it doesn't treat it as a script so all the options to execute the script as well as color coding of the script are disabled. Currently I have to copy out the script and paste it into a new query, then when I'm done editing paste it back and save it. This is all related to our source control and is a major pain. Any way to fool sql server and have it treat these as .sql files so I can execute them directly? A: You can add the extension from the options dialog (tools->options). Then under Text Editor-File Extension and then choose the editing experience you want Once applied you can use it as you did .SQL. In the following image note the highlighting and the result set on the file SQLQuery.rpc
{ "language": "en", "url": "https://stackoverflow.com/questions/11508635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SelectedItem from menuBar I've got two questions: * *How to get a selectedItem on the sub menu as described in reference 1 (see also refenrence 2), workable in Google apps script *Is reference 3 related to this question? If yes, please star so that it might get some attention !! ===== * *Stackoverflow Question *Reference to Vaadin (GWT) *Issue 1413 A: You should create a different server handler for each item, with each one pointing to a different callback function.
{ "language": "en", "url": "https://stackoverflow.com/questions/11639042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Webpack: Module not found: Error: Can't resolve './containers' I want to link react project to python Flask, so I used webpack. But, I have the following error in webpack: ERROR in ./web/app.js Module not found: Error: Can't resolve '/containers' I don't know if there's an error in the path or the syntax is wrong. How do I solve this problem? This project is constructed like below: templete |--- index.html static web |--- app.js |--- containers |--- First.js |---Second.js app.py package.json webpack.config.js requirements.txt webpack.config.js: const path = require("path") const MiniCssExtractPlugin = require("mini-css-extract-plugin") module.exports = { mode: "development", entry: [ '@babel/polyfill', "./web/app.js" ], output: { filename: "flask_react_router.js", path: path.resolve(__dirname, "static"), publicPath: "/static/" }, module: { rules: [ { test: /\.(sa|sc|c)ss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader' ] }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: [{ loader: "babel-loader", options: { presets: ["@babel/preset-env", "@babel/preset-react"], plugins: [ ['@babel/plugin-proposal-decorators', {legacy: true}], ['@babel/plugin-proposal-class-properties', {loose: true}] ] } }] }, { test: /\.(png|jpg|ico|svg|eot|woff|woff2|ttf)$/, use: ['file-loader'] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "flask_react_router.css", chunkFilename: "[id].css" }) ] } app.js: import '@babel/polyfill' import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter, Route } from 'react-router-dom' import { First, Second } from './containers' ReactDOM.render( <BrowserRouter> <Route exact path='/first' component={ First } /> <Route exact path='/second' component={ Second } /> </BrowserRouter> , document.getElementById('root') ); First.js: import React, { Component } from 'react' export default class First extends Component { render() { return ( <div>Hello First</div> ) } } index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="kimkkikki"> <title>Flask React Router</title> <link rel="stylesheet" href="{{ url_for('static', filename='flask_react_router.css') }}"> </head> <body> <div id="root"></div> </body> <script type="text/javascript" src="{{ url_for('static', filename='flask_react_router.js') }}"></script> </html> app.py: from flask import Flask, render_template app = Flask(__name__) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def web(path): return render_template('index.html') if __name__ == '__main__': app.run(host='127.0.0.1') And executable code: webpack app.py Can someone help this problem? A: import { First, Second } from './containers' This is not a valid import statement. If you are importing a directory, then it should contain an index.js file which have exports for the files. A simple solution is to import the components as: import First from './containers/First'; import Second from './containers/Second'; Hope this works for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/60509092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable To Read Excel Numeric Value Using Apache POI Hi I am trying to read excel data at the time of execution.Before I was sending all data as a string in excel sheet and my code was working fine but after some change i need to read one numeric column also using same code . But i am getting error java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:1062) at org.apache.poi.xssf.usermodel.XSSFCell.getRichStringCellValue(XSSFCell.java:395) at org.apache.poi.xssf.usermodel.XSSFCell.getStringCellValue(XSSFCell.java:347) This is my code . public String[][] readFileAndExcelData(String sheetName) { int maxLAs = 1000; int maxRegs = 1000; String listUsers[][] = new String[maxLAs+1][9]; try { //-Load the properties System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n"); System.out.println("Read in PROPERTIES file"+ "\r\n"); System.out.println("---------------------------------------------------------------------------------"+ "\r\n"); Properties prop = new Properties(); InputStream input = null; String inputFS = getAutomationInputDataPath()+"//Validation.properties"; input = new FileInputStream(inputFS); prop.load(input); //-Input file with test data String userAuthenticationFile = prop.getProperty("users_test_file"); System.out.println("\t" + "userAuthenticationFile =" + userAuthenticationFile + "\r\n"); //-Load the path of the resources folder, containing files to be tested String resourcesPath = getAutomationInputDataPath()+"/"; System.out.println("\t" + "resourcesPath =" + resourcesPath + "\r\n"); System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n"); System.out.println("Read in INPUT file describing 051 User Authentication"+ "\r\n"); System.out.println("---------------------------------------------------------------------------------"+ "\r\n"); String inputDataFS = resourcesPath + userAuthenticationFile; InputStream inputData = null; inputData = new FileInputStream(inputDataFS); Workbook workbook = new XSSFWorkbook(inputData); Sheet lasSheet = workbook.getSheet(sheetName); Iterator<Row> rowIterator = lasSheet.iterator(); //-Maximum maxLAs learning activities may be specified, at this time //-First row must contain labels int numberUserAuthentication = 0; int r = 0; int c = 0; while (rowIterator.hasNext()) { Row nextRow = rowIterator.next(); Iterator<Cell> cellIterator = nextRow.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); listUsers[r][c] =cell.getStringCellValue(); c = c + 1; } r = r + 1; c = 0; } workbook.close(); inputData.close(); numberUserAuthentication = r-1; System.out.println("\t" + "Completed reading Excel file that describes User Authentication list. # LAs = " + numberUserAuthentication + "\r\n"); }catch (Exception e) { e.printStackTrace(); } return listUsers; } Can any one help me i want to read complete excel data . I have total 6 sheets and in every sheet i have multiple data in row and column . Unable to read numeric data from excel sheet.
{ "language": "en", "url": "https://stackoverflow.com/questions/50447705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Expand/collapse folders in the Outlook navigation pane programmatically I am writing an add-in for Outlook using C#. Is there are way to programmatically expand and collapse folders in the Outlook 2007 folders navigation pane? Also, is there an event fired when a folder is expanded? A: Outlook does not expose events that will allow you to expand or collapse the folders in the treeview. You may be able to do this using the Windows API. A: There might be a way to expand (but not to collapse). Basically what you need to do is to go through your sub folders one by one during each step make the sub folder your current folder. I have tested this in Outlook 2010 (VSTO) on addin startup. So if you have the Parent Folder Folder A and its sub folders Folder A1, Folder A2 and Folder A3. In order to expand Folder A do the following: * *Get the active explorer (Globals.thisaddin.application.activeexplorer) *Set the current folder explorer.currentfolder = Folder A *Now loop through all sub folders under Folder A and make each sub folder the current folder: (The code should be something like this) Subfolders = FolderA.Folders For Each folder as outlook .folder in Subfolders Explorer.currentfolder = folder Next Folder This method works for me so hope this would be hopeful
{ "language": "en", "url": "https://stackoverflow.com/questions/2193774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }