text
stringlengths
64
81.1k
meta
dict
Q: I need to store the previous value of a variable in another variable I'm making a dice rolling game and I need to make it that if you roll twice 6 in a row that you lose all your points. So I thought you need to make a variable that stores the previous value of the variable, but I just can't figure out how to do that. Here's the function, I need the store the previous value of the variable 'dice' all the way at the top of the function: document.querySelector('.btn-roll').addEventListener('click', function() { if(gamePlaying) { //1.Random number var dice = Math.floor(Math.random() * 6) + 1; //2. Display the result var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block'; diceDOM.src = 'dice-' + dice + '.png'; //3 Update the round score IF the rolled number was NOT a 1 if (dice !== 1){ roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else { togglePlayer(); } } else { alert("Start a new game!!!"); } }); A: hopefully the following will help: var previousDice = 0; document.querySelector('.btn-roll').addEventListener('click', function() { if(gamePlaying) { //1.Random number var dice = Math.floor(Math.random() * 6) + 1; if (dice === previousDice === 6) { // all your points are gone } //2. Display the result var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block'; diceDOM.src = 'dice-' + dice + '.png'; //3 Update the round score IF the rolled number was NOT a 1 if (dice !== 1){ roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else { togglePlayer(); } previousDice = dice; } else { previousDice = 0; alert("Start a new game!!!"); } });
{ "pile_set_name": "StackExchange" }
Q: Returning an element with a specific attribute JDOM i need your help on a particular bit of code. I have a document object in jdom. I also do have a element object for the root. Now i want to get a specific element based on the value of an attribute. But what i want to avoid, is to filter through the complete list of children, just to get one element. So is there some kind of way to filter on the value of a document. Lets say my attribute value is '123' Now i want the element where the 'id' value is '123' What is the best way to do this? Kind Regards. A: I would use XPath for that. With the following expression: //element[@attribute='value']
{ "pile_set_name": "StackExchange" }
Q: Não recebe os dados do POST Estou tentando gerar o login de acordo com os dados do banco de dados e prosseguir para a página restrita aos usuários registrados, mais decorre o erro de senha incorreta. Front-end: <div class="login-form"> <form action="modulo.php" method="POST"> <input type="email" placeholder="E-mail" value="email" > <input type="password" placeholder="Senha" value="password" > <input type="submit" class="btn-submit" value="Login"> </div> Back-end <?php session_start(); // error_reporting('1'); include 'config.php'; // username and password sent from form $myusername=$_POST['email']; $mypassword=$_POST['password']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM login WHERE email='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "menu.php" $_SESSION['email']=$myusername; $_SESSION['password']=$mypassword; header("location:menu.php"); } else { echo "<b class='error'>Wrong Username or Password</b>"; } ?> A: Está a faltar name="nomeDoCampo" nos inputs da sua form... Tente assim: <div class="login-form"> <form action="modulo.php" method="POST"> <input type="email" name="email" placeholder="E-mail" value="email" > <input type="password" name="password" placeholder="Senha" value="password" > <input type="submit" class="btn-submit" value="Login"> </div>
{ "pile_set_name": "StackExchange" }
Q: How to bypass GAC for strong name assemblies? I have a debug version of an assembly which has a strong name. I want to install the assembly in the bin folder of a web application. However, the CLR checks if a strong named assembly exists in a GAC before continuing with the rest of the probing. For my web application, I want the CLR to bypass looking into the GAC. Rather, I want the CLR to look into my bin folder first, and if it is not available look at the GAC. How can I do this? A: Hans is correct. DON'T do this - but just for interests sake; ---EXCOMMUNICATION EXCLUSION ZONE--- I do believe from experience that if you install another copy of an assembly (ie your debug version, with same version number), that there will be 2 copies in the GAC and the latest one installed will be used. ---END EXCOMMUNICATION EXCLUSION ZONE--- As Hans says, give your debug version a new version number and point to it with a publisher policy (which you put in the gac too), or an assembly redirect.
{ "pile_set_name": "StackExchange" }
Q: How to troubleshoot performance issues of PHP, MySQL and generic I/O I have a WordPress based website running on a shared hosting. Its response time is very decent (around 2s to retrieve the HTML page and 5s to load all the resources). I was planning to move it to a dedicated virtual server (Ubuntu 12.04 LTS), which should theoretically improve things and make them more consistent given its not shared. However I observed severe performance degredation, with the page taking 10seconds to be generated. I ruled out network issues by editing /etc/hosts on the server and mapping the domain to 127.0.0.1. I used the Apache load tester ab to get the HTML, so JS, CSS and images are all excluded. It still took 10 seconds. I have Zpanel installed on the server which also uses MySQL, and its pages come up quite fast (1.5s) and also phpMyAdmin. Performing some queries on the wordpress database directly through phpMyAdmin returns them quite fast too, with query times in the 10 to 30 millisecond region. Memory is also sufficient, with only 800Mb being used of the 1Gb physical memory available, so it doesn't seem to be a swap issue either. I have also installed APC to try to improve the PHP performance, but it didn't have any effect. What else should I look for? What could be causing this degradation in performance? Could it be some kind of I/O issue since I am running on a cloud based virtual server? I wish to be able to raise the issue with my provider but without showing actual data from some diagnosis I am afraid he will just blame my application. UPDATE with sar output (every second) when I did an HTTP request: 02:31:29 CPU %user %nice %system %iowait %steal %idle 02:31:30 all 0.00 0.00 0.00 0.00 0.00 100.00 02:31:31 all 2.22 0.00 2.22 0.00 0.00 95.56 02:31:32 all 41.67 0.00 6.25 0.00 2.08 50.00 02:31:33 all 86.36 0.00 13.64 0.00 0.00 0.00 02:31:34 all 75.00 0.00 25.00 0.00 0.00 0.00 02:31:35 all 93.18 0.00 6.82 0.00 0.00 0.00 02:31:36 all 90.70 0.00 9.30 0.00 0.00 0.00 02:31:37 all 71.05 0.00 0.00 0.00 0.00 28.95 02:31:38 all 14.89 0.00 10.64 0.00 2.13 72.34 02:31:39 all 2.56 0.00 0.00 0.00 0.00 97.44 02:31:40 all 0.00 0.00 0.00 0.00 0.00 100.00 02:31:41 all 0.00 0.00 0.00 0.00 0.00 100.00 UPDATE 2 After josten's suggestions. I/O: iotop fails with OSError: Netlink error: No such file or directory (2) and sar -d also fails with Requested activities not available in file /var/log/sysstat/sa14. I think this is because this is a virtual machine, just like iostat also fails. Could it be the reason why %iowait reported by sar 1 10 is always 0%? CPU Load: The process that is topping the CPU% in htop is actually apache2. I was expecting this to maybe be the database, but its not. It goes up to 94% for a few seconds when I do a fresh HTTP request. Seems this is the culprit. I have done an strace -f -t and one summary strace -c -f. There seems to be an awful lot of lstat calls (57786), with 2455 resulting in errors. No idea if this is normal. Other than that the topmost call was wait4 which I presume is normal (its just waiting), and munmap. Top 5 below. % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 51.06 0.124742 897 139 6 wait4 14.90 0.036388 1 57786 2455 lstat 9.67 0.023622 13 1857 munmap 7.69 0.018790 37 514 brk 6.70 0.016361 481 34 clone 2.87 0.006999 74 94 12 select strace itself slowed down apache by a factor of 2. I am trying to understand the long trace now to see if there is anything indicative of what was causing the CPU to spike for a few seconds. What is the typical time for lstat for a good performing server? I wish to gather some information so that I can complain in a constructive manner to the provider if it is the storage access fault. UPDATE Output of fio random read test: random-read: (g=0): rw=randread, bs=4K-4K/4K-4K, ioengine=sync, iodepth=1 fio 1.59 Starting 1 process random-read: Laying out IO file(s) (1 file(s) / 128MB) Jobs: 1 (f=1): [r] [100.0% done] [12185K/0K /s] [2975 /0 iops] [eta 00m:00s] random-read: (groupid=0, jobs=1): err= 0: pid=24264 read : io=131072KB, bw=10298KB/s, iops=2574 , runt= 12728msec clat (usec): min=119 , max=162219 , avg=380.34, stdev=957.37 lat (usec): min=119 , max=162219 , avg=380.89, stdev=957.40 bw (KB/s) : min= 7200, max=13424, per=99.89%, avg=10285.72, stdev=1608.68 cpu : usr=2.80%, sys=18.65%, ctx=33511, majf=0, minf=23 IO depths : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, >=64=0.0% submit : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0% complete : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0% issued r/w/d: total=32768/0/0, short=0/0/0 lat (usec): 250=45.57%, 500=37.17%, 750=3.41%, 1000=7.83% lat (msec): 2=5.67%, 4=0.27%, 10=0.08%, 20=0.01%, 250=0.01% Run status group 0 (all jobs): READ: io=131072KB, aggrb=10297KB/s, minb=10545KB/s, maxb=10545KB/s, mint=12728msec, maxt=12728msec The only hint I have now is that the CPU line of the fio output seems to show quite a bit of activity when compared to other systems. I ran it on my local Ubuntu machine and the output was: cpu : usr=0.19%, sys=0.59%, ctx=32923, majf=0, minf=23 The usr percentage seems to be a small fraction of what is being reported on my server. UPDATE Re PHP APC. Yes it is installed. Output from phpinfo: APC Support enabled Version 3.1.7 APC Debugging Disabled MMAP Support Enabled MMAP File Mask no value Locking type pthread mutex Locks Serialization Support php Revision $Revision: 307215 $ Build Date May 2 2011 19:00:42 Is there any specific setting I should check for? These are the settings I have (local value, Master value): apc.cache_by_default On On apc.canonicalize On On apc.coredump_unmap Off Off apc.enable_cli Off Off apc.enabled On On apc.file_md5 Off Off apc.file_update_protection 2 2 apc.filters no value no value apc.gc_ttl 3600 3600 apc.include_once_override Off Off apc.lazy_classes Off Off apc.lazy_functions Off Off apc.max_file_size 1M 1M apc.mmap_file_mask no value no value apc.num_files_hint 1000 1000 apc.preload_path no value no value apc.report_autofilter Off Off apc.rfc1867 Off Off apc.rfc1867_freq 0 0 apc.rfc1867_name APC_UPLOAD_PROGRESS APC_UPLOAD_PROGRESS apc.rfc1867_prefix upload_ upload_ apc.rfc1867_ttl 3600 3600 apc.serializer default default apc.shm_segments 1 1 apc.shm_size 32M 32M apc.slam_defense On On apc.stat On On apc.stat_ctime Off Off apc.ttl 0 0 apc.use_request_time On On apc.user_entries_hint 4096 4096 apc.user_ttl 0 0 apc.write_lock On On UPDATE Increased apc.shm_size to 96M. Cache full count is now 0, and there are 96.5% hits to the cache after a few refreshes of the website here and there. APC memory usage is 25.4MB free. It seems to have reduced the loading time by 3 seconds or so, now down to around 4 to 5 seconds if I do a pure wget from the server itself without getting any images etc. Still more than twice slower than the other hosting but definitely was an improvement. I am still finding it strange why it was taking so long to render those pages when the server is totally idle (I don't have APC installed on my development PC and it doesn't have that kind of behaviour). And its still strange where those extra remaining seconds are being wasted. A: You have to first determine what the issue is first; if it's PHP, MySQL, I/O, load, memory, CPU, kernel, etc. sar logs the systems metrics; you'll have to catch it in the act. You can configure atop to do process accounting which definitely helps. To determine if it's I/O Use tools such as iotop and atop to see what the disk usage is; these tools will also tell you what is causing the IO. Generally, if iowait is sustained over 10% this could be the issue. sar logs disk IO; so you can run sar -d to see it (look at %util column). To determine if it's load Use tools such as htop, top, uptime; again tie this to the process running and find out more details about what the process is doing. Note that this reports the load on the scheduler; it doesn't reflect the CPU usage. To determine if it's a CPU sar once again comes in to save the day; you can see this information with sar -P ALL. You can also use mpstat -P ALL for real-time data. Generally, the CPU is only an issue if all the CPU's are at 100%; 80%+ means they're being utilized (but not necessarily saturated). To determine if it's the Memory (VM) You'll want to use vmstat; vmstat -S M 1 and observe the swap, io, and system columns. Obviously a high amount of swapping can impact performance. There is also the system section; a high amount of interrupts can also do the same. To determine if it's interrupts You can use vmstat -S M 1. Unfortunately, it's hard to tell if interrupts are the issue if your system doesn't have a baseline on what is normal. A high amount of interrupts (which are caused from hardware requiring action from the kernel) will bring the system to a crawl. Failing NIC's are notorious for doing this. To determine if it's the kernel This is trickier but generally requires strace, perf, or sysdig tools. One such tool is perf top. strace with a summary (-c) is nice but it doesn't break it down relative to the system resources (so the data that is provided is only speculation); it's ideal to use perf top to come to the conclusion that it's the kernel. You can also use stap (SystemTap) if your machine supports it. I should also note that strace will impact performance; you should use sysdig if the system is at all important. To determine if it's MySQL/PHP You basically have to follow what I posted above (perf for example can provide information on what command is causing high kernel time, iotop, atop, htop can provide information relative to system resources on what is using them); basically, you're using the above tools to determine what is causing the load. Once you've determined it to be MySQL It could be a query that you're running (so you'll want to use EXPLAIN on that query in MySQL). You'll also need to make sure that your database is optimized and that the queries you're executing are optimized. You'll also have to make sure that the table engine you're using is ideal for what you're doing (I've seen many large tables that MyISAM when they should be InnoDB). If you've determined that none of the above are the issue and still suspect MySQL you may want to archive data in the affected tables to reduce access (table scans) to that table. You may also want to verify constraint consistency, enable cache buffering, and ensure indexes are optimal. A good tool to help in this process is mytop; but all the information that mytop provides is easily accessible in the mysql client. Some useful statements to run: SHOW FULL PROCESSLIST\G to get a complete list of currently executing SQL statements as well as their status to the server. SHOW ENGINE INNODB STATUS\G (InnoDB only) EXPLAIN EXTENDED <QUERY> to explain a query that you see MySQL executing. SHOW GLOBAL STATUS\G for a server-wide status Once you've determined it to be PHP You can use tools to profile your PHP code (such as xdebug) and then open the generated profile in KCacheGrind to see a performance analysis of the profiled PHP code. If you find it's none of these you may just need to upgrade your server. A: This looks like other cases I've seen where Apache is spending a lot of its time compiling PHP. Have you made sure an opcode cache (e.g. APC) is installed? It'll show as a loaded module in the output of phpinfo(), if that helps. Otherwise, to track what Apache's doing within mod_php, your best bet is going to be XHProf. To anyone other than jbx arriving here via Google: the other answers are excellent, by the way. Go read them. But those answers, and jbx's responses to them, have helped me arrive at this conclusion.
{ "pile_set_name": "StackExchange" }
Q: PHP do-while loop not working So I've been stuck on this do-while loop not working for about two hours. I really don't understand why it doesn't work. I'm getting this error: Notice: Undefined offset: 9 in /public_html/me/yes.php on line 60 The only problem I think of is that it doesn't accept while loops in a do-while. Here is my working code for just the inner while loop: $maxcols = $numofcols-1; //=9 $maxrow = count($myarray)-1; //=44 $currentcol=0; $currentrow=1; //do { $collection->insert(array($title[$currentcol] => $myarray[$currentrow][$currentcol])); $currentcol++; while ($currentcol<=$maxcols){ $newdata = array('$set' => array($title[$currentcol] => $myarray[$currentrow][$currentcol])); $currentcol--; $collection->update(array($title[$currentcol] => $myarray[$currentrow][$currentcol]), $newdata); $currentcol++; $currentcol++; } $currentrow++; //} while ($currentrow<=$maxrow); If I uncomment the two line's "//do {" and "//} while ($currentrow<=$maxrow);" my program dies with the error I mentioned above. Is there something dead simple as to why it's breaking my code? Thanks in advance UPDATE: Line 60 is: $collection->insert(array($title[$currentcol] => $myarray[$currentrow][$currentcol])); A: The answer: Such a simple little mistake, but there was no reset on the $currentcol Moving the initialization down right below the do statement made it work correctly.Can you tell it's getting late? hahaha Thanks all. $currentrow=1; do { $currentcol=0; $collection->insert(array($title[$currentcol] => $myarray[$currentrow][$currentcol])); $currentcol++; while ($currentcol<=$maxcols){ $newdata = array('$set' => array($title[$currentcol] => $myarray[$currentrow][$currentcol])); $currentcol--; $collection->update(array($title[$currentcol] => $myarray[$currentrow][$currentcol]), $newdata); $currentcol++; $currentcol++; } $currentrow++; } while ($currentrow<=$maxrow);
{ "pile_set_name": "StackExchange" }
Q: Need help formatting/parsing this list I'm not a developer so sorry if this is a dumb question or if my terminology is incorrect. I'm writing a script to make calls to our CMDB's API but i'm not sure how to handle the data that is being sent back from it. It appears to be a list type but I can't reference anything by key names. Is there a way to convert it to something that i can easily manipulate and pull data out of? Here is my code: import requests import json r=requests.post('API.URL', data={'grant_type': 'password', 'client_id':'#######', 'username': 'user', 'password': 'password'}) json_data = json.loads(r.content) token = json_data['access_token'] data ={ "filters": [ { "fieldId": "937905400191ae67dd03ab4b79968fcbaa264b1a75", "operator": "eq", "value": "hostname" } ], "fields":[ '9426b6ddf3cb971488517145e39efc5aa7f16fec46', '9343f8800b3917f26533954918a6388ae8c863507f', '9379053db492ece14816704ef5a9e3e567e217511b', '9343f93fc4c8422bcf24e74a9a86035bb7d0248b00', '941ba290776d6f51ce35664246927b958330a753b2' ], "association": "Configuration Item", "busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8", "includeAllFields": 'false', "pageNumber": 0, "pageSize": 300, "scope": "Global", "scopeOwner": "(None)", "searchName": "APItest" } payload = json.dumps(data) headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization':'bearer '+token} search=requests.post('http://API.URL', headers=headers, data=payload) search_json = json.loads(search.content) bo = search_json['businessObjects'] print(bo) Here's the response: [ { "busObRecId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1", "hasError": false, "links": [ { "url": "http://URL", "name": "Delete Record" } ], "fields": [ { "displayName": "Business Sponsor", "name": "Business Sponsor", "value": "", "html": null, "dirty": false, "fieldId": "9426b6ddf3cb971488517145e39efc5aa7f16fec46" }, { "displayName": "Owned By", "name": "Owned By", "value": "John Doe", "html": null, "dirty": false, "fieldId": "9343f8800b3917f26533954918a6388ae8c863507f" }, { "displayName": "Asset Status", "name": "Asset Status", "value": "Active", "html": null, "dirty": false, "fieldId": "9379053db492ece14816704ef5a9e3e567e217511b" }, { "displayName": "Description", "name": "Description", "value": "Automation Server", "html": null, "dirty": false, "fieldId": "9343f93fc4c8422bcf24e74a9a86035bb7d0248b00" }, { "displayName": "Data Center Location", "name": "Data Center Location", "value": "", "html": null, "dirty": false, "fieldId": "941ba290776d6f51ce35664246927b958330a753b2" } ], "errorMessage": null, "busObPublicId": "9423ad7d617390fdc956ee4302a69d0ccf1a37a4c1", "busObId": "93dada9f640056ce1dc67b4d4bb801f69104894dc8", "errorCode": null } ] type() shows the object bo as a list and len() says it only has one element so I'm not sure how to pull data out of it without hacking away at it stripping out characters. A: The reason why you cannot reference anything by key names is the fact that your output is a list. A list which is only containing one single dictionary element. If you print out bo[0] you get the whole data, without the [ and ] symbols. As for the dictionary now we can access different elements by keys, e.g.: print(bo["busObId"]) will return the following value: 93dada9f640056ce1dc67b4d4bb801f69104894dc Let's say you would want to print out the fieldId of the first element of "fields". You can do it the following way: print(bo[0]["fields"][0]["fieldId"]) Hope this helped.
{ "pile_set_name": "StackExchange" }
Q: Highcharts customized chart I'm using Highcharts to develop a customized chart. Here is what I've gotten by my own jsfiddle. Here is my code: $(function () { $('#container').highcharts({ chart: { type: 'area', inverted: true, height: 700, width: 780, marginRight: 20 }, credits: { enabled: false }, colors: [ '#828385', '#3AAFC1', '#F87D2A', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'], exporting: { enabled: false }, title: { text: ' ' }, subtitle: { style: { position: 'absolute', right: '0px', bottom: '10px' } }, legend: { itemDistance: 30, x: 180, verticalAlign: 'top' }, xAxis: { categories: ["Label1", "Label2", "Label3", "Label4", "Label5", "Label6", "Label7", "Label8", "Label9", "Label10"], offset: -410, labels: { overflow: 'justify' }, plotLines: [{ color: '#A0A0A0', width: 1, value: 0 }, { color: '#A0A0A0', width: 1, value: 1 }, { color: '#A0A0A0', width: 1, value: 2 }, { color: '#A0A0A0', width: 1, value: 3 }, { color: '#A0A0A0', width: 1, value: 4 }, { color: '#A0A0A0', width: 1, value: 5 }, { color: '#A0A0A0', width: 1, value: 5 }, { color: '#A0A0A0', width: 1, value: 6 }, { color: '#A0A0A0', width: 1, value: 7 }, { color: '#A0A0A0', width: 1, value: 8 }, { color: '#A0A0A0', width: 1, value: 9 }] }, yAxis: { title: { text: 'Índice teste' }, max: 100, min: 0, }, plotOptions: { area: { fillOpacity: 0.5 }, series: { cursor: 'pointer', point: { events: { click: function () { if (jQuery('#type_group_name_hidden').val() == 'Processo') { jQuery('#type_group_name_hidden').val('Atividade'); } else if (jQuery('#type_group_name_hidden').val() == 'Atividade') { jQuery('#type_group_name_hidden').val('Procedimento'); } else if (jQuery('#type_group_name_hidden').val() == 'Procedimento') { jQuery('#type_group_name_hidden').val('Processo'); } jQuery('#group_name_hidden').val(this.category); requestAjaxChart('processos', buildProcessos); } } }, marker: { lineWidth: 1 }, threshold: 50 } }, series: [{ name: "Market", data: [46.503590664272934, 51.39078282828278, 56.89226932668327, 47.66801075268824, 46.82561768530563, 59.23058676654176, 51.08220338983055, 46.17849829351536, 55.84550063371354, 51.428756058158314] }, { name: "My network", data: [48.175, 27.159999999999997, 39.916666666666664, 38.6, 53.85, 38.949999999999996, 30.4, 51.9, 33.519999999999996, 54.7875] }, { name: "Avg", data: [70, 80, 65, 75, 85, 82, 72, 69, 71, 58] }] }); }); Even it looks pretty good, it's not exactly what the client desire. I need to do some changes as described bellow: Remove all the vertical lines on xAxis. As my chart is a inverted one, I couldn't figure out how to remove them. On the xAxis values (0 - 100), remove the intermediaries values (10, 20, 30, ...) keeping just the first and last value (0, 100) Move the yAxis labels upon the horizontal lines Make clickable the points behind the overflowed chart area I've tried almost all configuration options but with no success. Any suggestion? A: Some answers : 1) See from docs gridlineWidth property. 2) See from docs tickPositions property. 3) Another docs labels.y property. 4) Not possible, even if it's SVG/VML it still is HTML, you can't make clickable DIV which is positioned behind another one.
{ "pile_set_name": "StackExchange" }
Q: Attempts to create new clickable html element from JS have failed Ok, I'm attempting to create a game from scratch in HTML, but I've already hit a snag in this bit of code: EDIT: the following takes place in the <script> tag. var c = document.createElement("button"); c.innerHTML = "Explore"; c.id = "explore"; c.onclick = "explore()"; para.appendChild(c); When the code above is executed, it creates a <button> element displaying "Explore", but when clicked, it doesn't run the explore() function. Please help. Note: para refers to a <div> element. I've also included the full code as a snippet, since it's short, for testing purposes. <!DOCTYPE html> <html> <head> </head> <body> <div id="buttons"> <button id="bgn", onclick="begin()">BEGIN</button> </div> <script> var name; var maxHp=10; var hp=10; var lvl=1; var exp=0; var dmg=1; var mp=5; var equip=[null,null,null,null]; var inven=[]; var skills=[]; var spells=[]; function begin() { var q = confirm("Are you sure?"); if(q) { naming(); } }; function naming() { var q = prompt("What is your name",""); if(q!==null) { name=q; alert("Ok, I'll call you "+name+"!"); var para=document.getElementById("buttons"); var child=document.getElementById("bgn"); para.removeChild(child); var c = document.createElement("button"); c.innerHTML = "Explore"; c.id = "explore"; c.onclick = "explore()"; para.appendChild(c); } } function explore() { alert("You have explored!"); } </script> </body> </html> A: Your c.onclick is assigned to a string and not a function. Try it like this: var c = document.createElement("button"); c.innerHTML = "Explore"; c.id = "explore"; c.onclick = explore; para.appendChild(c);
{ "pile_set_name": "StackExchange" }
Q: postgres force json datatype When working with JSON datatype, is there a way to ensure the input JSON must have elements. I don't mean primary, I want the JSON that gets inserted to at least have the id and name element, it can have more but at the minimum the id and name must be there. thanks A: The function checks what you want: create or replace function json_has_id_and_name(val json) returns boolean language sql as $$ select coalesce( ( select array['id', 'name'] <@ array_agg(key) from json_object_keys(val) key ), false) $$; select json_has_id_and_name('{"id":1, "name":"abc"}'), json_has_id_and_name('{"id":1}'); json_has_id_and_name | json_has_id_and_name ----------------------+---------------------- t | f (1 row) You can use it in a check constraint, e.g.: create table my_table ( id int primary key, jdata json check (json_has_id_and_name(jdata)) ); insert into my_table values (1, '{"id":1}'); ERROR: new row for relation "my_table" violates check constraint "my_table_jdata_check" DETAIL: Failing row contains (1, {"id":1}).
{ "pile_set_name": "StackExchange" }
Q: Are private members useful anymore? Watchpoints and data break points make it possible to watch the changes of a value in memory in many languages. Much of the justification I have seen for getters and setters and private variables hinges on the getters and setters being clear places in which break points can be set. If watchpoints and data breakpoints make the break points on getters and setters a moot point, should I be using private members in my code anymore if I trust the other programmers on my team? A: I assume you mean "get rid of accessors and make private members public"... well, from a design point of view, a getter/setter is not doing much more than a public variable anyway, just with more layers. Now, a good class design would not even begin to consider exposing a variable at all, it instead adds methods that apply to the internal state of the object (said state being expressed in terms of one or more variables) to perform logical operations on the object. So really, getters and setters are a smell and should be removed. If you think of a class as a bundle of variables then you're not thinking right anyway, fix that first. Once fixed, you find you'll have no getters or setters anyway and all variables will be private. Then you can put your breakpoints on the methods that operate on the class.
{ "pile_set_name": "StackExchange" }
Q: For video content, are intros or outros less intrusive? For a brief time my Youtube channel had a little Intro to build some branding and show off my channel name. I quickly found that, at least to me, it was pretty annoying and only delayed my ability to watch the video. I've consistently found intro soungs/credits annoying on TV shows as well. I started wondering, what about an outro with the same branding? Outros don't actually inhibit the watcher's ability to watch the video, and it's really no problem if they leave once they hit the outro either; they've already viewed my video (and any in-stream/sidebar ads). Is there any data out there supporting intros or outros as being less annoying/more pleasurable to users? A: In general you should try to grab your viewer's attention right out the gate and attempt to keep them focused with interesting content throughout. Therefore, I would think it would be better to have an outro for the reason you stated of not inhibiting the viewer's ability to watch the video. One common complaint I always hear is the massive sigh following clicking a link to a youtube video and getting stuck waiting for a 30 second advertisement for what could be just a 40 second video. There have been a batch of cognitive psychology studies on attention spans, and the result is always the shorter the better. According to one by Lloyds, the average attention span is now just 5 minutes. Thus the faster you can deliver your content, the better. There's also a batch of articles online to support the whole shorter is better concept in specific regards to youtube videos, they're all supported by a bit of research, and they're all actually a pretty good read. Here's a couple of choice selections: Optimum Length of an Online Video Web Video and Short Attention Spans At 60 seconds more than half your audience is gone
{ "pile_set_name": "StackExchange" }
Q: Problem using bind1st and bind2nd with transform I think C++0x bind is much better, but I'd like to understand the old bind1st and 2st before I use C++0x's bind: struct AAA { int i; }; struct BBB { int j; }; // an adaptable functor. struct ConvertFunctor : std::binary_function<const AAA&, int, BBB> { BBB operator()(const AAA& aaa, int x) { BBB b; b.j = aaa.i * x; return b; } }; BBB ConvertFunction(const AAA& aaa, int x) { BBB b; b.j = aaa.i * x; return b; } class BindTest { public: void f() { std::vector<AAA> v; AAA a; a.i = 0; v.push_back(a); a.i = 1; v.push_back(a); a.i = 2; v.push_back(a); // It works. std::transform( v.begin(), v.end(), std::back_inserter(m_bbb), std::bind(ConvertFunction, std::placeholders::_1, 100)); // It works. std::transform( v.begin(), v.end(), std::back_inserter(m_bbb), std::bind(ConvertFunctor(), std::placeholders::_1, 100)); // It doesn't compile. Why? How do I fix this code to work? std::transform( v.begin(), v.end(), std::back_inserter(m_bbb), std::bind2nd(ConvertFunctor(), 100)); std::for_each(m_bbb.begin(), m_bbb.end(), [](const BBB& x){ printf("%d\n", x.j); }); } private: std::vector<BBB> m_bbb; }; int _tmain(int argc, _TCHAR* argv[]) { BindTest bt; bt.f(); } Why can't the third transform function be compiled? How do I fix this code to work? A: Change struct ConvertFunctor : std::binary_function<const AAA&, int, BBB> { BBB operator()(const AAA& aaa, int x) { to: struct ConvertFunctor : std::binary_function<AAA, int, BBB> { BBB operator()(const AAA& aaa, int x) const { Don't ask me why, I only read the compilation error messages.
{ "pile_set_name": "StackExchange" }
Q: how to put windows theme buttons and widgets on the kivy layouts I intent to produce an application for windows OS and want its GUI to be designed in python kivy. the problem is when some widget like Button is added to the layout, i got the button without windows OS themes applied. i need the button and the entire GUI widgets with operating system themes. what i have to do? here is a simple code of GUI with a button on it. manipulation required?: from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout class TestApp(App): def build(self): layout = FloatLayout(orientation='vertical') btn = Button(text='The button!',size_hint=(0.2,0.1),pos=(200,200)) layout.add_widget(btn) return layout def callback(self, event): print("button touched") self.label.text = "button touched" if __name__ == "__main__": TestApp().run() A: As stated by others in comments, it's not how kivy works, ease of porting of every platforms and ability to build custom widgets comes at the cost of system integration, kivy widgets look the same whatever the platform, and doesn't feel native anywhere, unless you spend time making them do. You can define rules for your widgets specific to each platforms, to make them look and feel native, but it's work, and if you want it to follow user theming, then it's certainly out of reach for any reasonable effort, with kivy it's you who decides how your application look, not the system.
{ "pile_set_name": "StackExchange" }
Q: SYMFONY 4 Data recovery from my forms does not work I've just started learning Symfony, I'm in the basics, but I already have a problem with recovering user data. When I look in the symfony nav bar, I see that the $Client function does not recover any value, while the $request function does recover all the values entered and I do not understand why.... Here are the codes: Client.php namespace App\Model; use Symfony\Component\Validator\Constraints as Assert; class Client{ public $famille; /** * @Assert\Range(min=1900, max=2050) */ public $anneeDeNaissance; public $enfant; public $enfant_nombre; public $enfant_foyer; public $pension; public $pension_tarif; } simulateur.html.twig {% extends "home.html.twig" %} {% block title %} Simulimmo - Simulateur{% endblock %} {% block stylesheet_content %}<link rel="stylesheet" href="css/simulateur.css"> {% endblock %} {% block contact %} {% endblock %} {% block nous %} {% endblock %} {% block simulation %} {% endblock %} {% block body %} <div class="container-naviguation"> <div class="content-naviguation"> <div class="colonne-naviguation"> <div class="numero-naviguation situation_naviguation active"><p>1</p></div> <div class="texte-naviguation"> <strong> SITUATION </strong> </div> </div> <div class="colonne-naviguation separation-naviguation patrimoine_separation"></div> <div class="colonne-naviguation"> <div class="numero-naviguation patrimoine_naviguation"><p>2</p></div> <div class="texte-naviguation"><strong> PATRIMOINE </strong> </div> </div> <div class="colonne-naviguation separation-naviguation epargne_separation"></div> <div class="colonne-naviguation"> <div class="numero-naviguation epargne_naviguation"><p>3</p></div> <div class="texte-naviguation"> <strong>ÉPARGNE</strong> </div> </div> <div class="colonne-naviguation separation-naviguation objectifs_separation"></div> <div class="colonne-naviguation"> <div class="numero-naviguation objectifs_naviguation"><p>4</p></div> <div class="texte-naviguation"> <strong>OBJECTIFS</strong> </div> </div> <div class="colonne-naviguation separation-naviguation resultats_separation"></div> <div class="colonne-naviguation"> <div class="numero-naviguation resultats_naviguation"><p>5</p></div> <div class="texte-naviguation"> <strong>RÉSULTATS</strong></div> </div> </div> </div> <!-- Partie questionnaire --> <div class="container-questionnaire"> <div class="content-questionnaire"> <div class="section"> <div class="situation section show"> <h1> SITUATION </h1> {{ {{ form_start(SituationForm) }} {{ form_row(SituationForm.famille) }} {{ form_row(SituationForm.anneeDeNaissance)}} {{ form_row(SituationForm.enfant)}} {{ form_row(SituationForm.enfant_nombre) }} {{ form_row(SituationForm.enfant_foyer) }} {{ form_row(SituationForm.pension) }} {{ form_row(SituationForm.pension_tarif) }} {{ form_end(SituationForm) }} }} </div> <!-- Section 2 | patrimoine --> <div class="patrimoine section hidden"> <h1>PATRIMOINE </h1> </div> <!-- Section 3 | epargne --> <div class="epargne section hidden"> <h1>ÉPARGNE </h1> </div> <!-- Section 4 | objectifs --> <div class="objectifs section hidden"> <h1>OBJECTIFS </h1> </div> <!-- Section 5 | resultats --> <div class="resultats section hidden"> <h1>RÉSULTATS </h1> </div> <div class="button"> <a><button onClick="pagePrecedente()" class="precedent hidden">Précédent</button></a> </div> </div> </div> </div> {% endblock %} {% block javascript %} function changerElement(section){ hidden = document.getElementsByClassName(section); show = document.getElementsByClassName(section); } function afficherConsole(section, hidden, show){ console.log(section); console.log(hidden); console.log(show); } function affichageNouvelleSection(section, section_precedente){ //CSS modification $("." + section_precedente).css("display", "none"); // Enleve la partie d'avant $("." + section).css("display", "inherit"); // Affiche la page d'après } function modificationNaviguation(section){ // CSS modification $("." + section + "_naviguation").addClass("active"); // Changement de la boule (Grâce à ACTIVE) $("." + section + "_separation").addClass("active"); // Changement de la séparation $(".precedent").addClass("show").removeClass("hidden"); // Affiche le bouton pour retourner en arrière } /** * La fonction suivant() s'occupe d'afficher la nouvelle partie du questionnaire */ var suivant = 1; function pageSuivante(){ var situation = "situation"; var patrimoine = "patrimoine"; var epargne = "epargne"; var objectifs = "objectifs"; var resultats = "resultats"; /*Sélection de votre page */ switch(suivant){ case 1: /* Situation */ changerElement(situation); affichageNouvelleSection(situation, resultats); modificationNaviguation(situation); afficherConsole(situation); break; case 2: /* Patrimoine */ changerElement(patrimoine); affichageNouvelleSection(patrimoine, situation); modificationNaviguation(patrimoine); afficherConsole(patrimoine); break; case 3: /* Epargne */ changerElement(epargne); affichageNouvelleSection(epargne, patrimoine); modificationNaviguation(epargne); afficherConsole(epargne); break; case 4: /* Objectifs */ changerElement(objectifs); affichageNouvelleSection(objectifs, epargne); modificationNaviguation(objectifs); afficherConsole(objectifs); break; case 5: /* Résultat */ changerElement(resultats); affichageNouvelleSection(objectifs, resultats); modificationNaviguation(resultats); afficherConsole(resultats); break; default: suivant = 0; console.log("default"); break; suivant += 1; } return suivant; } /** * La fonction precedent() s'occupe d'afficher la partie précédente du questionnaire */ function pagePrecedente(){ suivant -= 2; pageSuivante(); return suivant; } {% endblock %} SituationController.php <?php // src/Controller/SimulationController.php namespace App\Controller; use App\Model\Client; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Twig\Environment; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; class SituationController extends AbstractController { /** * @Route("/simulateur", name="simulateur") */ public function situation(Environment $twig, Request $request): Response { $Client = new Client(); $Situation = $this->createFormBuilder($Client) ->add("famille", ChoiceType::class, [ 'label' => 'Votre situation familliale ?', 'choices' => [ 'Célibataire' => 'celibataire', 'Marié(e)' => 'marie', 'Pacsé(e)' => 'pacse', 'En concubinage' => 'concubinage', 'Divorcé(e)' => 'divorce', 'Veuf/Veuve' => 'veuf' ], 'attr' => [ 'class' => 'situation_familliale input'] ]) ->add('anneeDeNaissance', IntegerType::class, [ 'label' => 'Quelle est votre année de naissance ?', 'required' => False, 'attr' => [ 'class' => 'naissance input', 'placeholder' => 'Ex : 1950'] ]) ->add('enfant', ChoiceType::class,[ 'label' => 'Avez vous des enfants ?', 'choices' => array( 'Non' => False, 'Oui' => True, ), 'attr' =>[ 'class' => 'enfant'] ]) ->add('enfant_nombre', IntegerType::class, [ 'label' => 'Combien avez-vous d\'enfants ?', 'required' => False, 'attr' => [ 'class' => 'enfant_nombre input', 'placeholder' => 'Ex : 3']]) ->add('enfant_foyer', IntegerType::class, [ 'label' => 'Combien sont encore dans votre foyer fiscal ?', 'required' => False, 'attr' => [ 'class' => 'enfant_foyer input', 'placeholder' => 'Ex : 3']]) ->add('pension', ChoiceType::class,[ 'label' => 'Avez vous des enfants ?', 'choices' => array( 'Non' => False, 'Oui' => True, ), 'attr' =>[ 'class' => 'pension'] ]) ->add('pension_tarif', IntegerType::class, [ 'label' => 'Combien vous coûte cette pension mensuellement?', 'required' => False, 'attr' => [ 'class' => 'pension_tarif input', 'placeholder' => 'Ex : 450€']]) ->add ('submit', SubmitType::class, [ 'label' => "Suivant", 'attr' => [ 'class' => 'envoyer', ], ]) ->getForm(); dump($request); return $this->render('/content/simulateur.html.twig', [ 'SituationForm'=>$Situation->createView() ]); } } Ps : It's my first time on StackOverflow. A: You're missing this part which actually populate the form based on the request. $situation->handleRequest($request); If your $client hasn't been automatically updated, you can then retrieve the data with : $situation->getData();
{ "pile_set_name": "StackExchange" }
Q: How to test/assert if an event is broadcasted in Laravel I am developing a Laravel application. I am using Laravel Broadcast in my application. What I am trying to do now is that I am trying to test if an event is broadcasted in Laravel. I am broadcasting an event like this: broadcast(new NewItemCreated($item)); I want to test if the event is broadcasted. How can I test it? I mean in unit test. I want to do something like Broadcast::assertSent(NewItemCreated::class) Additional information That event is broadcasted within the observer event that is triggered when an item is created. A: I think you can treat broadcasting more or less like events, so you can refer to this section of the documentation.
{ "pile_set_name": "StackExchange" }
Q: ¿Cómo reubicar la DataGridView en el nuevo dato ingresado en la tabla? Bueno mi asunto es que necesito que mi DataGridView se reubique en el nuevo dato ingresado dentro de mi tabla ya que al hacerlo se redirige al primer valor de la tabla. Espero y puedan resolver mi duda. Abajo esta el código con el que lleno mi DataGridView. public void Main(DataGridView dgv) { try { da = new SqlDataAdapter("select * from Main", strconex); dt = new DataTable(); da.Fill(dt); dgv.DataSource = dt; } catch { MessageBox.Show("Ocurrio un error inesperado"); } } A: Ubica después de tu código de inserción lo siguiente: dgv.Update(); dgv.Refresh(); y no deberías tener problemas para que este se actualice después del nuevo registro, si dejas tu código para reinsertar edito esta publicación y lo añado donde corresponda. Ante cualquier duda, consulta.
{ "pile_set_name": "StackExchange" }
Q: How to search through all items of a combobox in C#? I have a combobox, and I would like to search through every element in it. How can I do this? (also the number of items is not the same everytime, but this is not so important). I am using c# windows form application. A: you can do this for (int i = 0; i < myComboBox.Items.Count; i++) { string value = myComboBox.GetItemText(myComboBox.Items[i]); } A: Use a foreach loop. It will iterate all your items of ComboBox regardless of their count, e.g. foreach(var item in myComboBox.Items) { // do something with your item }
{ "pile_set_name": "StackExchange" }
Q: Self destruct AWS ECS tasks after reaching RUNNING state I have ECS Task set as a target on a CloudWatch Event rule that invokes on the below S3 Event Pattern. The rule invokes OK on a PUT operation in a S3 bucket, and starts the ECS Task that is set as its target. The Task reaches RUNNING state... and remains in RUNNING state until it is stopped. I use the CLI to stop the task. Also, this task is not part of a ECS Service, but a stand-alone task intended to do a specific task. Is there a way to self-destruct the Task after it reaches the RUNNING state and does the intended work? I could wait for 30mins or even a few hours... but ultimately the tasks needs to STOP by itself. This becomes particularly difficult to manage when there are 1000s of S3 PUT operations that invoke the CloudWatch rule that in-turn starts 1000s of tasks. I am looking for somehow stopping these tasks after they reach the RUNNING state and finish the intended work. Any suggestions? A: If you have to really have to stick at what you are doing, then you should invoke another lambda function to stop the task once a certain stage is reach in your application which is running as the docker container. Beware of integration hell though! What you are trying to do should be better handled by the AWS Lambda and Batch service. You can specify a docker image, to run and once the operation is done, exit the docker process. Refer this: https://medium.com/swlh/aws-batch-to-process-s3-events-388a77d0d9c2
{ "pile_set_name": "StackExchange" }
Q: set x-axis limits in ggplot2 -> when adding another regression line, numbers on x-axis disappear I want to plot a kaplan meier curve and overlay it with a Weibull regression line. Since the Weibull can make predictions exceeding the survival times of the data I would like to make the Weibull regression line 'longer'. My problem is: when I set my X-asis limits the numbering ends when the KM curve end (see curve below) This is my code: car2 <- car2[-c(34:39,41,43),] # I only need this variables from the dataset s1 <- with(car2,Surv(Time_OS_m,Event_OS)) #create survival object fKM1 <- survfit(s1 ~ Eigenschap,data=car2) #Kaplan meier curve for s1 sWei1 <- survreg(s1 ~ as.factor(Eigenschap),dist='weibull',data=car2) #Weibull regression line summary(sWei1) pred.I1 = predict(sWei1, newdata=list(Eigenschap="SA"),type="quantile",p=seq(.01,.99,by=.01)) pred.I2 = predict(sWei1, newdata=list(Eigenschap="I"),type="quantile",p=seq(.01,.99,by=.01)) df1 = data.frame(y=seq(.99,.01,by=-.01), Eigenschap1=pred.I1, Eigenschap2=pred.I2) df_long1 = gather(df1, key= "Eigenschap", value="Time_OS_m", -y) #Convert to long data format p = ggsurvplot(fKM1, data = car2, risk.table = TRUE, legend.title="", legend.labs = c("Infusion", "Screenfailure/\napheresis only"), title = "Overall Survival (with Weibull distribution)", pval = TRUE, pval.coord = c(0, 0.03), pval.size = 3.5, xlim = c(0,70)) #here i set the X axis limits p$plot = p$plot + geom_line(data=df_long1, aes(x=Time_OS_m, y=y, group=Eigenschap)) p Above code gives this plot: Can someone help me get the x axis numbered all the way to the end, What am I doing wrong here? A: This could be achieved via the argument break.x.by. Using the first example from survminer::ggsurvplot try this: library(survey) library(survminer) fit <- survfit(Surv(time, status) ~ sex, data = lung) # Basic survival curves ggsurvplot(fit, data = lung, xlim = c(0, 1500)) ggsurvplot(fit, data = lung, xlim = c(0, 1500), break.x.by = 250)
{ "pile_set_name": "StackExchange" }
Q: Variable Undefined Scope Here is my code: function example() { var post = object.get("owner"); post.fetch({ success: function(post) { window.titles = post.get("username"); console.log(window.titles); } }); console.log(window.titles); } The first log works successfully. Outside of the method, the second log prints as undefined. Why? A: It works in the outside function, but not right away because async calls take some time. That's the nature of JS. The easiest way "out of it" is to move all the code that depends directly on the results of your async function into another function and then just run it from within the success callback. Something like this: function example() { var post = object.get("owner"); post.fetch({ success: function(post) { window.titles = post.get("username"); otherImportantCode(); // call the remaining code from here } }); console.log(window.titles); // won't work here } function otherImportantCode() { console.log(window.titles); // see, it works here, outside the example function // ... the rest of the code depending on window.titles } When you're ready for more advanced handling of such issues, learn about promises and events.
{ "pile_set_name": "StackExchange" }
Q: Difference Between commit and apply in Android SharedPreferences SharedPreferences are used to save Application data in Android. commit() and apply() both are used to save the changes in the shared preferences. As mentioned in Android Library: public abstarct void apply(): Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. public abstract boolean commit (): Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences. Does this mean that the changes made by commit() are instant as compared with apply()? Which one is better? If I need to use the same shared preference value in the next immediate activity, which one should I use? As I have seen if the value of Preference is updated it is not reflected till the application is restarted. A: Commit() is instantaneous but performs disk writes. If you are on the ui thread you should call apply() which is asynchronous. A: apply() - returns void apply() was added in 2.3, it saves without returning a boolean indicating success or failure. commit() - returns boolean value. commit() returns true if the save works, false otherwise. apply() was added as the android dev team noticed that most no one took notice of the return value, so apply is faster. You can refer to below link What's the difference between commit() and apply() in Shared Preference
{ "pile_set_name": "StackExchange" }
Q: HTML5 Form Pattern for 7 or 10 numbers only I need a pattern for a student ID that must be either 7 or 10 digits long. pattern="[0-9]{7,10}" I got this but obviously this is between 7-10 not 7 | 10 I tried pattern="[0-9]{7|10}", that also does not work. Any ideas? A: You could use ^(\d{7}|\d{10})$"to get exactly 7 or 10 digits. Example Snippet: document.getElementById('textbox').onkeyup = function (){ document.getElementById('count').innerHTML = this.value.length; }; <p> <span>Character Count</span> <span id="count"></span> </p> <form>   <input id="textbox" type="text" pattern="^(\d{7}|\d{10})$" required /> </form> <p>Press Enter to check validation</p>
{ "pile_set_name": "StackExchange" }
Q: Get latest entry based on date I want to get the info about users and the amount of points they had before a specific date. The problem I can't know when their state was last recorded so I have to get the latest entry before the date. The query I've ended up with is something like this (simplified example): SELECT u.id, p.points, p.timestamp FROM user AS u INNER JOIN points ON u.id = p.user_id WHERE u.group = 'red' AND p.timestamp::date <= '2018-01-01 10:00:00' GROUP BY u.id, u.first_name, u.last_name, mh.gamified_mastery, mh.updated_at ORDER BY mh.updated_at DESC This gives me a table like this: id | points | timestamp ----------------------- 1 | 10 | 2018-01-01 9:00:00 1 | 25 | 2018-01-01 8:57:00 1 | 25 | 2018-01-01 8:00:00 2 | 100 | 2018-01-01 7:00:00 2 | 50 | 2018-01-01 6:00:00 2 | 15 | 2018-01-01 5:55:00 I don't actually want the timestamp to be displayed, it's here for presentation's sake. I only want the top entries for each player but I have to group by timestamp for the ORDER BY to work. Due to other limitations I really need to get all of this done in one query (I know I could just do a separate query with LIMIT 1 and join them in the app but that's not an option currently). A: I think you want distinct on: SELECT DISTINCT ON (u.id) u.id, . . . FROM (SELECT u.id, p.points, p.timestamp FROM user u INNER JOIN points p ON u.id = p.user_id WHERE u.group = 'red' AND p.timestamp::date <= '2018-01-01 10:00:00' GROUP BY u.id, u.first_name, u.last_name, mh.gamified_mastery, mh.updated_at ) pu ORDER BY u.id, mh.updated_at DESC;
{ "pile_set_name": "StackExchange" }
Q: How to add a column to a DataFrame based on a multi-index map I have a dataframe df as follows: # df.head(10) TYPE A B 0 0 5 25 1 1 7 23 2 5 10 43 3 1 5 37 4 2 4 61 5 3 1 17 6 0 8 39 7 2 4 59 8 4 2 6 9 0 3 31 And I have a multi-index map mapp as follows: # mapp.head(10) num AA BB 1 1 1 4 2 5 3 10 4 17 5 18 6 2 3 7 6 8 9 9 3 3 10 I want to add a column df['num'] like this: TYPE A B num 0 0 5 25 74 1 1 7 23 89 2 5 10 43 129 3 1 5 37 77 4 2 4 61 62 5 3 1 17 5 6 0 8 39 98 7 2 4 59 61 8 4 2 6 8 9 0 3 31 40 I try to realize it by using the following code: idx = df.set_index(['A', 'B']).index df['num'] = mapp.loc[idx, 'num'] But Python throws an Exception: Exception: cannot handle a non-unique multi-index! How can I fix it? Or is there any other method to solve this problem? Besides, the size of df is very large, I prefer not to use the loop. A: Use DataFrame.join: df1 = df.join(mapp, on=['A','B']) print (df1) TYPE A B num 0 0 5 25 NaN 1 1 7 23 NaN 2 5 10 43 NaN 3 1 5 37 NaN 4 2 4 61 NaN 5 3 1 17 5.0 6 0 8 39 NaN 7 2 4 59 NaN 8 4 2 6 8.0 9 0 3 31 NaN
{ "pile_set_name": "StackExchange" }
Q: What do Collections class references EMPTY_LIST, EMPTY_SET and EMPTY_MAP point to? This is a follow-up question to one I asked earlier. The Collections class has three final interface references, EMPTY_LIST, EMPTY_SET and EMPTY_MAP. What do they point to? For example, does the reference EMPTY_LIST point to an instantiated object of the LIST type with no elements? If so, what is the concrete class of this object? A: The concrete classes of those objects are hard-coded direct implementations of an empty collection; they aren't publicly visible or used anywhere else. See e.g. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/Collections.java#Collections.0EMPTY_LIST.
{ "pile_set_name": "StackExchange" }
Q: Antlr generated code invalid after upgrading from 3.2 to 3.5.2 I'm newbie in antlr Because of a migration to java 8 , i must migrate an antlrv3 code from 3.2 to 3.5.2. I have nothing changed in the antlr grammar who work perfectly with the version 3.2 and java 7 (target java 6) With the version 3.5.2 of antlr maven generate compilation error like: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project ccff-sql2xpath: Compilation failure: Compilation failure: [ERROR] /C:/ProjectSVN/JSR170/ccff-sql2xpath/target/generated-sources/antlr3/sql2xpath/query/compiler/TParser.java:[262,73] cannot find symbol [ERROR] symbol: variable props [ERROR] location: variable p of type org.antlr.runtime.ParserRuleReturnScope I think that something has changed in the way of antlr v3.5.2 generate the code because i have more than 77600 lines with this one and 'only' 3181 lines with the older version of antlr in the TParser.java generated file Can you help me ? Here is the parser grammar: parser grammar TParser; options { language = Java; output = AST; superClass = AbstractTParser; tokenVocab = TLexer; } @header { package sql2xpath.query.compiler; import sql2xpath.query.xpath.XPathException; import sql2xpath.query.xpath.constraint.TemporaryPathConstraint; } //============================================================================= query : s=select (f=from)? (w=where)? (o=orderby)? EOF; //============================================================================= select : SELECT^ p=proplist { for (String o: ((List<String>) p.props)) { composer.getColumnSpecifier().addProperty(o); } }; //============================================================================= from returns[String res = "unknown"] : FROM^ n=ntlist { if (n.nodetypes.size() > 1) throw new XPathException("Unable to deal with joined tables in FROM clause"); composer.getPathConstraint().setTypeName(toCompactStringTree(n.nodetypes.get(0))); }; //============================================================================= where returns[String res = "unknown"] : WHERE^ o=orexpression[true] { if (o.res != null) { // System.out.println("add constraint: " + o.res); composer.getPropertyConstraint().addConstraint(o.res); } }; //============================================================================= orderby returns[String res = "unknown"] : (ORDER BY)^ p=propname d=(DESC | ASC)? { if (d == null) composer.getOrderingSpecifier().addProperty(p.res, null); else if (d.getType() == ASC) composer.getOrderingSpecifier().addProperty(p.res, "ascending"); else composer.getOrderingSpecifier().addProperty(p.res, "descending"); } (COMA q=propname e=(DESC | ASC)? { if (e == null) composer.getOrderingSpecifier().addProperty(q.res, null); else if (e.getType() == ASC) composer.getOrderingSpecifier().addProperty(q.res, "ascending"); else composer.getOrderingSpecifier().addProperty(q.res, "descending"); })* ; //============================================================================= proplist returns[Object props] @init{ List<String> l = new ArrayList<String>(); } : a=propname { l.add(a.res); } (COMA b=propname { l.add(b.res); })* { $props = l; }; //============================================================================= ntlist returns[List nodetypes] : c+=complexpropname (COMA c+=complexpropname)* { $nodetypes = $c; }; //============================================================================= orexpression[boolean b] returns[String res = null] @init{ List<String> l = new ArrayList<String>(); List<Object> p = new ArrayList<Object>(); } : a=andexpression[b] { p.addAll(((List<Object>)(((Object []) a.res)[1]))); l.add((String)(((Object []) a.res)[0])); } (OR^ c=andexpression[b] { p.addAll(((List<Object>)(((Object []) c.res)[1]))); l.add((String)(((Object []) c.res)[0])); })* { StringBuffer sb = new StringBuffer(); for (String s: l) if (s!=null) sb.append(s + " or "); if (sb.length() > 0) $res = sb.substring(0,sb.length()-4); if (p.size() > 2) throw new XPathException("Unable to deal with more than two path constraints"); else if (p.size() == 2) { if (!$b) throw new XPathException("Cannot deal with negated or clauses"); TemporaryPathConstraint pc1 = (TemporaryPathConstraint) p.get(0); TemporaryPathConstraint pc2 = (TemporaryPathConstraint) p.get(1); //LOGGER.debug("Found or-ed constraints on jcr:path = " + pc1.path + " OR " + pc2.path); if (pc1.b && pc2.b) { composer.getPathConstraint().orConstraint(pc1.path, pc2.path); } else throw new XPathException("Only positive path constraints can be in the same or clause"); }else if (p.size() == 1) { if (!$b) throw new XPathException("Cannot deal with single negated path constraint"); TemporaryPathConstraint pc1 = (TemporaryPathConstraint) p.get(0); //LOGGER.debug("Found single constraint on jcr:path = " + pc1.path); if (pc1.b) { composer.getPathConstraint().singleConstraint(pc1.path); } else { throw new XPathException("Cannot deal with negative single path constraints"); } } }; //============================================================================= andexpression[boolean b] returns[Object res = null] @init{ List<String> l = new ArrayList<String>(); List<Object> p = new ArrayList<Object>(); String k = null; } : a=notexpression[b] { if (a.res instanceof TemporaryPathConstraint) p.add(a.res); else l.add((String)a.res); } (AND^ c=notexpression[b] { if (c.res instanceof TemporaryPathConstr StringBuffer sb = new StringBuffer(); for (String s: l) if (s!=null) sb.append(s + " and "); if (sb.length() > 0) k = sb.substring(0,sb.length()-5); if (p.size() > 2) throw new XPathException("Unable to deal with more than two path constraints"); else if (p.size() == 2) { if (!$b) throw new XPathException("Cannot deal with negated and clauses"); TemporaryPathConstraint pc1 = (TemporaryPathConstraint) p.get(0); TemporaryPathConstraint pc2 = (TemporaryPathConstraint) p.get(1); //LOGGER.debug("Found and-ed constraints on jcr:path = " + pc1.path + " AND " + pc2.path); if (pc1.b && !pc2.b) { composer.getPathConstraint().andNotConstraint(pc1.path, pc2.path); } else if (pc2.b && !pc1.b) { composer.getPathConstraint().andNotConstraint(pc2.path, pc1.path); } else throw new XPathException("Only one positive and one negative path constraint can be in the same and clause"); p.clear(); } $res = new Object [] {k, p}; }; //============================================================================= notexpression[boolean b] returns[Object res = null] : NOT^ d=containsexpression[false] { if (!$b) throw new XPathException("Impossible to parse nested NOT operators"); $res = d.res;} | c=containsexpression[b] {$res = c.res; }; //============================================================================= containsexpression[boolean b] returns[Object res = null] : c=containsfun[b] { $res = c.res; } | v=value IN p=propname { $res = composer.getPropertyConstraint().getComparingConstraint(p.res, "=", v.res, b); } | o=operatorexpression[b] { $res = o.res; }; //============================================================================= operatorexpression[boolean b] returns[Object res = null] : p=propname o=op v=value { if ("jcr:path".equals(p.res)) if (!"=".equals(o.res)) throw new XPathException("Impossible to use other operator than \"=\" or \"LIKE\" with jcr:xpath property"); else { TemporaryPathConstraint tpc = new TemporaryPathConstraint(TemporaryPathConstraint.EQUAL); tpc.path = v.res; tpc.b = $b; $res = tpc; } //composer.getPathConstraint().addConstraintAndProcess(v.res, b, false); else $res = composer.getPropertyConstraint().getComparingConstraint(p.res, o.res, v.res, b); } | p=propname IS NULL { $res = composer.getPropertyConstraint().getIsNullConstraint(p.res, b); } | p=propname IS NOT NULL { $res = composer.getPropertyConstraint().getIsNotNullConstraint(p.res, b); } | l=like[b] { $res = l.res; } | t=parentexpression[b] { $res = t.res; }; //============================================================================= op returns[String res = "unknown"] : EQ { $res = "="; } | NEQ { $res = "!="; } | LEQ { $res = "<="; } | LES { $res = "<"; } | GEQ { $res = ">="; } | GRE { $res = ">"; }; //============================================================================= parentexpression[boolean b] returns[String res = "unknown"] : LEFT_PAREN o=orexpression[b] RIGHT_PAREN { $res = "(" + o.res + ")"; }; //============================================================================= propname returns[String res = "unknown"] : QUOT c=complexpropname QUOT { $res = $c.res; } | c=complexpropname { $res = $c.res; }; //============================================================================= complexpropname returns[String res = "unknown"] : a=simplepropname (DOT b=simplepropname)? {$res = a.res; if (b != null) $res += "." + b.res;}; //============================================================================= simplepropname returns[String res = "unknown"] : a=identifier (COLON b=identifier)? {$res = a.res; if (b != null) $res += ":" + b.res;}; //============================================================================= identifier returns[String res = "unknown"] : nq=NonQuotedIdentifier { $res = $nq.getText(); } | q=QuotedIdentifier { $res = q.getText(); } | l=Letter { $res = l.getText(); } | STAR { $res = "*"; }; //============================================================================= value returns[String res = "value"] : x=complexpropname { $res = x.res; } | c=constant { $res = c.res; }; //============================================================================= like[boolean b] returns[Object res = null] : p=propname LIKE e=expression (c = escape)? { if ("jcr:path".equals(p.res)) { TemporaryPathConstraint tpc = new TemporaryPathConstraint(TemporaryPathConstraint.LIKE); tpc.path = e.res; tpc.b = $b; $res = tpc; // composer.getPathConstraint().addConstraintAndProcess(((c == null) ? e.res : e.res.replaceAll(c.res, "\\" + c.res)), $b, false); } else $res = composer.getPropertyConstraint().getLikeConstraint(p.res, ((c == null) ? e.res : e.res.replaceAll(c.res, "\\" + c.res)), $b); }; //============================================================================= escape returns[String res = "escape"] : ESCAPE e=expression { $res = e.res; }; //============================================================================= expression returns[String res = "expression"] : (u=unaryOperator)? c=constant { $res = ((u!=null)?u.res:"") + c.res; }; //============================================================================= unaryOperator returns[String res = "unaryOperator"] : MINUS { $res = "-"; }; //============================================================================= constant returns[String res = "constant"] : Number { $res = $Number.getText(); } | NULL { $res = $NULL.getText(); } | s=stringLiteral { $res = s.res; } | Currency { $res = $Currency.getText(); } | ODBCDateTime { $res = $ODBCDateTime.getText(); }; //============================================================================= stringLiteral returns[String res = "stringLiteral"] : UnicodeStringLiteral { $res = $UnicodeStringLiteral.getText(); } | ASCIIStringLiteral { $res = $ASCIIStringLiteral.getText(); }; //============================================================================= containsfun[boolean b] returns[String res = "containsfun"] : CONTAINS_FUN c=containscope COMA e=expression RIGHT_PAREN { $res = composer.getPropertyConstraint().getContainsConstraint(c.res, e.res, b); }; //============================================================================= containscope returns[String res = "containscope"] : c=complexpropname { $res = c.res; } | DOT { $res = "."; }; Here is the code of the method where is the error: // $ANTLR start "select" // be\\fgov\\minfin\\ccff\\jcr2\\sql2xpath\\query\\compiler\\TParser.g:27:4: select : SELECT ^p= proplist ; public final TParser.select_return select() throws RecognitionException { TParser.select_return retval = new TParser.select_return(); retval.start = input.LT(1); Object root_0 = null; Token SELECT2=null; ParserRuleReturnScope p =null; Object SELECT2_tree=null; try { // sql2xpath\\query\\compiler\\TParser.g:28:5: ( SELECT ^p= proplist ) // sql2xpath\\query\\compiler\\TParser.g:28:7: SELECT ^p= proplist { root_0 = (Object)adaptor.nil(); SELECT2=(Token)match(input,SELECT,FOLLOW_SELECT_in_select186); SELECT2_tree = (Object)adaptor.create(SELECT2); root_0 = (Object)adaptor.becomeRoot(SELECT2_tree, root_0); pushFollow(FOLLOW_proplist_in_select191); p=proplist(); state._fsp--; adaptor.addChild(root_0, p.getTree()); for (String o: ((List<String>) p.props)) { // <=====[ERROR] composer.getColumnSpecifier().addProperty(o); } } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; } // $ANTLR end "select" A: I think I understood the compilation error: The p property of type ParserRuleReturnScope is initialized with a method that returns a class of type proplist_return and extends the class ParserRuleReturnScope. ParserRuleReturnScope p =null; ... p=proplist(); // (proplist_return extend ParserRuleReturnScope) ... for (String o: ((List<String>) p.props)) { // <=====[COMPILATION ERROR] Because the class prolist_return is a child of ParserRuleReturnScope, p must be cast before searching for properties included in the child class, here the props property like this: proplist_return castP = (proplist_return) p; for (String o: ((List<String>) castP.props)) { With version 3.2, the plugin generates an error free code. with version 3.5.2, it generates these errors! I understand the cause of the compilation error. In fact version 3.5.2 of ANTLR is stricter, and in the action part of my rule 'select' in the grammar antlr, I forgot to reference the variable p and add a $ before. That's why the generator does not cast my class (see comment above) the wrong grammar is: select : SELECT^ p=proplist { for (String o: ((List<String>) p.props)) { composer.getColumnSpecifier().addProperty(o); } }; So the solution is: select : SELECT^ p=proplist { for (String o: ((List<String>) $p.props)) { composer.getColumnSpecifier().addProperty(o); } };
{ "pile_set_name": "StackExchange" }
Q: Save Action on webforms for marketers throws exception I am using the latest version of Sitecore - 7.2 (rev. 140228) and the latest version of WFFM - 2.4 rev. 140923. So the problem is whenever I try to submit a form no matter what kind of save action I have, Sitecore throws exception: Object reference not set to an instance of an object. Description: An unhandled exception occurred. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] Sitecore.Forms.Mvc.Controllers.ModelBinders.FormModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +571 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +457 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +152 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +641 Some additional information. The latest version of WFFM supports MVC so in this scenario I use cshtml layout. This is the blog post where is described how to use MVC - THIS Despite it is for previous versions of SC it doesn't matter and the solution is applicable for the latest version. A: Think I have a solution for this. I reverse engineered and debugged using a version of the controller and model binder I created after reflecting on the Sitecore.Forms.MVC classes using ILSpy. Apparently the null reference is occuring when it hits this: if (controllerContext.HttpContext.Request.RequestType == "POST" && formId != item.ID) item is null. item is set in the line before: Sitecore.Data.Items.Item item = RenderingContext.CurrentOrNull.PageContext.Database.GetItem(RenderingContext.CurrentOrNull.Rendering.DataSource); The data source property is empty on the rendering. If you check your presentation details, you'll see that's because there is another field that is used to specify your form ID. Apparently this looks like a Sitecore bug. But an easy workaround is to set the form data source in both the form ID and the Data source property of the rendering.
{ "pile_set_name": "StackExchange" }
Q: SQL Challenge - Display N (1, X or All) rows with a certain column value Here's a morning challenge: you have a table with rows like this: => select * from candidates; id | name ----+---------- 1 | JOhn Doe 2 | Melinda 3 | Bill 4 | Jane (4 rows) => select * from evaluation order by id; id | score | reason ----+-------+-------------------------------------- 1 | RED | Clueless! 1 | AMBER | Came in dirty jeans 2 | GREEN | Competenet and experienced 2 | AMBER | Was chewing a gum 3 | AMBER | No experience in the industry sector 3 | AMBER | Has knowledge gaps (6 rows) John has a red, Melinda has a green and amber, Bill has just ambers while Jane hasn't been interviewed yet. Your mission, should you choose to accept it is to generate a query that displays the results for Boss' approval. Boss likes to have results presented as: If a candidate has a GREEN, then display just greens and ignore reds and ambers. If candidate has reds and ambers or just ambers then display all of them, but have red score appear first so he can skip ambers if RED is really bad. display GREY for all candidates that have not been yet interviewed ('Jane') Rules of the game: No functions! Must be a single SQL query (however many sub-queries you want) Any SQL variant accepted, but ANSI SQL 92 or later gets you more points Try to avoid inline variables if you can (@foo in MySQL) My own answer turned out to be in line with group-think: SELECT * FROM evaluation e1 NATURAL JOIN candidates WHERE score = 'GREEN' OR ( score IN ( 'RED', 'AMBER' ) AND NOT EXISTS (SELECT 1 FROM evaluation e2 WHERE e1.id = e2.id AND score = 'GREEN') ) UNION SELECT id, 'GREY' AS score, 'Not yet evaluated' AS reason, name FROM candidates WHERE id NOT IN (SELECT id FROM evaluation) ORDER BY 1, 2 DESC A: The following is transitional SQL-92: SELECT c.name, e.* FROM candidates AS c JOIN ( SELECT * FROM evaluation WHERE score = 'GREEN' UNION SELECT * FROM evaluation AS e1 WHERE score IN ('AMBER', 'RED') AND NOT EXISTS ( SELECT * FROM evaluation AS e2 WHERE e2.id = e1.id AND e2.score = 'GREEN' ) ) AS e ON c.id = e.id UNION SELECT c.name, c.id, 'GREY', '(not interviewed)' FROM candidates AS c WHERE NOT EXISTS ( SELECT * FROM evaluation AS e WHERE e.id = c.id ) ORDER BY id, score DESC; Alternate (Intermediate SQL-92): SELECT c.name, e.id, e.score, e.reason FROM candidates AS c JOIN ( SELECT * FROM evaluation EXCEPT SELECT * FROM evaluation WHERE score IN ('AMBER', 'RED') AND id IN ( SELECT id FROM evaluation WHERE score = 'GREEN' ) ) AS e ON c.id = e.id UNION SELECT name, id, 'GREY' AS score, '(not interviewed)' AS reason FROM candidates WHERE id NOT IN ( SELECT id FROM evaluation ) ORDER BY id, score DESC; A: SELECT c.id AS id , c.name AS name , COALESCE(e.score, 'GREY') AS score , e.reason AS reason FROM candidates c LEFT JOIN evaluation e ON e.id = c.id WHERE e.score = 'GREEN' OR NOT EXISTS ( SELECT * FROM evaluation ee WHERE ee.id = c.id AND ee.score = 'GREEN' ) ORDER BY id ASC , score DESC
{ "pile_set_name": "StackExchange" }
Q: How to run jenkins with old version of Java instead the latest default one on MacOS? I'm setting up Jenkins on my Macbook (High Sierra), seems like the default version of Java is Java 9, which causes issue "java.lang.AssertionError: InstanceIdentity is missing its singleton" I changed the Java home of my Mac from 9.x to 8 already, but when I reinstall, same trouble still comes along. I checked the System Properties under Manage Jenkins/System Information, the value java.specification.version still is "9". So how can I install Jenkins with old version of Java? Or any workaround for it? A: Here is what worked for me with OS X 10.13.2 (High Sierra). I used "brew install jenkins" to install Jenkins. You can find instructions from http://flummox-engineering.blogspot.com/2016/01/installing-jenkins-os-x-homebrew.html, for example. Download JDK 8 from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html Set your JAVA_HOME and JDK_HOME to point to the version you downloaded. (Put this is your .bash_profile if needed.) For example, export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home export JDK_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home Type in "jenkins --httpPort=9898" or whatever port is desired to start Jenkins.
{ "pile_set_name": "StackExchange" }
Q: Allow only Nuget packages with verified package owners Our dev servers at work currently can't reach nuget.org because of concerns about the safety of packages. Is it possible to apply a url rule / filter to a firewall that would allow access only to those packages with a "verified package owner"? A: That's not possible with the server at this point. There's no APIs that would allow you to query whether a package has a verified owner or not. Additionally, the clients will hit so many different endpoints that it'd be very to make them all accessible. You'd need to whitelist almost all packages likely. There is some work on the clients being done to cover your scenario though. Along side with package signing, a new client policies is being worked on. That would allow you only to accept packages from certain package authors/feeds. An alternative in the short-term would be to use a mirroring feed that everyone in the company uses. That mirroring feed would only contain a set of whitelisted packages.
{ "pile_set_name": "StackExchange" }
Q: Need more than 2 datasets for “Execute R Script” module in “Azure Machine Learning Studio” Since connecting to Azure SQL database from “Execute R Script” module in “Azure Machine Learning Studio” is not possible, and using Import Data modules (a.k.a Readers) is the only recommended approach, my question is that what can I do when I need more than 2 datasets as input for "Execute R Script module"? // I'm already doing the following to get first 2 datasets, dataset1 <- maml.mapInputPort(1) dataset2 <- maml.mapInputPort(2) How can I "import" a dataset3? A: One thing you can do is combining two data-sets together and selecting the appropriate fields using the R script. That would be an easy workaround.
{ "pile_set_name": "StackExchange" }
Q: Warnings and Errors with declaration of multi-character character Screenshot 1 Here's my code. #include<iostream> #include<conio.h> #include<string.h> using namespace std; class Dragon { public: char element[30]; int energy; }; int main() { Dragon dragon; char name[30]; cout<<"Enter element.\n\n"; cin>>name; if(name=='Hell') { strcpy(dragon.element,"Hell Dragon"); dragon.energy=15000000; } else if(name=='Dark') { strcpy(dragon.element,"Dark Dragon"); dragon.energy=1000000; } else cout<<"Unknown Dragon."; cout<<"\nDragon's element = "<<dragon.element<<"\nDragon's energy level = "<<dragon.energy; getch(); return 0; } Just tried this program on my own in C++ and have problems in fixing the following errors- Errors and Warnings If you do have an idea on how I can modify this, please help me out. Thank you. A: One cause of your issues is that == can't be used to compare contents of character arrays. Solution 1: Use std::string The std::string data type is the preferred data structure in C++ for text strings. The std::string has overloaded == for comparing strings. The std::string also has a find method for searching for a substring. Solution 2: Use strcmp The C language uses character arrays for strings. The C language also has str*() functions for processing character arrays. The C++ language uses the str*() functions for processing the C-Style strings (character arrays). Use strcmp to compare character arrays with string literals: if (strcmp(name, "Hell") == 0) You may also want to use strstr for finding substrings or strchr for finding characters in a character array (C-style string).
{ "pile_set_name": "StackExchange" }
Q: Isolate Node JS "apps" within a single containing server My goal is to try to have multiple Node JS "apps" within one instance of a node js server. For example, in traditional PHP hosting, you can put different folders in the www directory and those folders will act as separate routes. If I have folder1 and folder2 as subdirectories going to www.example.com/folder1 or www.example.com/folder2 will be their own apps with their own index.html and everything. With Node JS it is a little different because instead of calling individual server-side PHP scripts, you make calls to the main server that is running. With something like socket.io, you do socket('on'...) and socket('emit'...) to communicate with the server, not calling specific scripts but instead communicating with the server. I want to try to mimic the PHP functionality within Node JS This might be an example file structure: main |--sites |--site1 | |--index.js | |--public |--site2 | |--index.js | |--public |--landing |--index.js |--public |--app.js I would imagine that the app.js file would have all the routes in it. It would specify that "/" was to the landing folder, "/site1" was to site1 folder etc. The thing I want with this is, however, that each of these "apps" is isolated. The index.js would be a server isolated to that app. The routing and everything within that app would all be done again, as if it was a fresh app.js, but they aren't separate node apps, just sub directories. Is this possible? Can you give me some example code for implementation? A: If using express, you can just create multiple instances of express. And then just attach them to your main router. eg. Lets say you have /app1/app.js const express = require('express'); const app = new express(); app.get('/xyz'); //etc.. module.exports = app; And say another /app2/app.js, that basically has the same.. You could then create your main entry point to have something like -> const app = new express(); app.use('/app1', require('./app1/app')); app.use('/app2', require('./app2/app')); In the above any requests to /app1/* will go to app1, and /app2/* go to app2.
{ "pile_set_name": "StackExchange" }
Q: I want to go layout I have a expandable list view and I want to go a layout(or layout's class) when click child items. How can I do it? My recently method is displaying toast... // Listview on child click listener expListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // TODO Auto-generated method stub Toast.makeText( getApplicationContext(), listDataHeader.get(groupPosition) + " " + listDataChild.get( listDataHeader.get(groupPosition)).get( childPosition), Toast.LENGTH_SHORT) .show(); return false; }}); A: Your question is not clear. I assume that you want to go to another screen, which is represented by an Activity ? If it's so, then search for, how to start an Activity in StackOverFlow. There are tons of questions related to it.
{ "pile_set_name": "StackExchange" }
Q: AlarmManager / BroadcastReceiver does not work I have this problem where AlarmManager does work properly or BroadcastReceiver does not receive notification. This problem happens when I test the app on on API 10 (2.3.7), however when I test it on API 14++, it works just fine. Below is the snippet of the code that calls the AlarmManager: AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent Notifyintent = new Intent(MainActivity.this, Notify.class); PendingIntent Notifysender = PendingIntent.getBroadcast(getApplicationContext(), 0, Notifyintent, PendingIntent.FLAG_UPDATE_CURRENT); am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Notifysender); And this is the BroadcastReceiver class: public class Notify extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("Notify","OnReceive"); } } And the AndroidManifest.xml <receiver android:name=".Notify"> <intent-filter> <action android:name="android.intent.action.NOTIFY"/> </intent-filter> </receiver> If the code above is run on API 10 (2.3.7), the "Notify" log message will not appear, however if it's run on API 14++, the "Notify" log message appears just fine. Thanks :) A: Ooops, sorry, after trying it in different emulator (same API 10 2.3.7), it actually works just fine. So I think the problem is probably with the emulator. Thanks :)
{ "pile_set_name": "StackExchange" }
Q: swift how to hide image but still let it occupy space in stack view how to hide image but still let it occupy space in stack view ? currently i set image.isHidden = false, and my stack view elements rearrange and squeeze the image space away. Is there a way to have the image still occupy space while being hidden? A: This should do it: image.alpha = 0
{ "pile_set_name": "StackExchange" }
Q: How to extend Button component and allow space event I want to create a custom component. By default it will be collapsed and show only a button (therefore, I want to extend Button and not any other component!). When a user clicks on this button, it will expand and show some fields inside it. The problem I face now (which looks like a bug), is that it is impossible to type space character inside those fields. I minimized my code just to several lines: Ext.define('Ext.ux.CustomMenu', { extend: 'Ext.button.Button', alias: 'widget.custommenu', requires: [ 'Ext.XTemplate' ], autoEl: {}, baseCls: Ext.baseCSSPrefix + 'test-btn', renderTpl: '<div class="foo"></div>', afterRender: function() { this.callParent(); this.attachField(); }, attachField: function () { Ext.create("Ext.form.field.Text",{ renderTo: this.el.query('.foo')[0] }); } }); Ext.create("Ext.ux.CustomMenu",{ renderTo: document.getElementById("button") }); And here is a fiddle, which shows this strange behaviour. So, how can I fix it? And please pay attention, that I really need to extend Button component. A: Ext.button.Button catches per default all SPACE and ENTER keydown events and stops them. So, your input field don’t get these. You need to override this part of Ext.button.Button. Ext.define('Ext.ux.CustomMenu', { extend: 'Ext.button.Button', ([...] onEnterKey: function (e) { if(e.type === 'keydown' && e.getKey() == e.SPACE) { return; } return this.callParent(arguments); } }); Here is the full example: https://fiddle.sencha.com/#view/editor&fiddle/21em
{ "pile_set_name": "StackExchange" }
Q: Prototypical inheritance: constructor of child I was playing around with prototypical inheritance, and bumped into something I found a bit remarkable. Here is the case: function Parent(){ this.name = "parent"; this.age = 30; }; var parent = new Parent(); console.log(parent.constructor); //Prints function Parent(); function Child(){ this.name = "child"; this.age = 10; }; var child = new Child(); console.log(child.constructor); //prints function Child() Child.prototype = new Parent(); //Set inheritance console.log(Child.prototype.constructor); //prints function Parent() as expected var child_2 = new Child(); console.log(child_2.constructor); //prints function Parent() ?? console.log(child_2.name); //Yet prints child, meaning the child's constructor is still function Child() Although I am not surprised that the constructor of Child is function Parent() after the inheritance is defined, I am a bit surprised that the constructor of child_2 is function Parent(), because the property set in the constructor body of Child, ie. this.name = "child" Is still executed. Is there a practical reason behind this occurrence? http://jsfiddle.net/7yobzt0u/1/ A: The Docs touch on this a little bit, but mostly just reference this SO question for the answer. As you have seen, constructor is a property on a function's prototype not the object itself. The only reason myObj.constructor returns something is because myObj's [[Prototype]] points to its constructor function's prototype property. When you said: child.prototype = new Parent() you made Child.prototype point to an "instance" of the parent "class". Then, when you said child_2 = new Child() that instance is what got copied to child_2's [[Prototype]] So when you said console.log(child_2.constructor) the lookup chain was as follows: Is constructor in child_2? -- NO, follow the [[Prototype]] We landed in this object, (which is an "instance" of the Parent class). Is constructor here? -- No, follow the [[Prototype]] We are now in the Parent.prototype object, is constructor here? --- Yes! return it. Rather than using new I suggest setting child's prototype with Object.create() but I suppose that's neither here nore there in regards to this question. Regardless, you need to set the constructor property manually, as referenced in the docs. Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;
{ "pile_set_name": "StackExchange" }
Q: Code School Screencast - Rails App From Scratch - Part 1 Error: Couldn't find Trip with 'id'= Following codeschool.com's ruby screencast on making an app and ran into this error. Full error is ActiveRecord::RecordNotFound in DestinationsController#show Couldn't find Trip with 'id'= The error applies to the @trip instance below GET /destinations/1.json def show @trip = Trip.find(params[:trip_id]) Here is the applicable code from the destinations_controller.rb: def show @trip = Trip.find(params[:trip_id]) @destination = Destination.find(params[:id]) end Here is the Trip model class Trip < ActiveRecord::Base has_many :destinations end And the Destination model class Destination < ActiveRecord::Base belongs_to :trip end Routes Rails.application.routes.draw do resources :destinations resources :trips do resources :destinations end root to: 'trips#index' Any help is greatly appreciated. :) :) :) Update 1: From log files Started GET "/destinations/4" for ::1 at 2016-03-31 00:50:08 +0900 Processing by DestinationsController#show as HTML Parameters: {"id"=>"4"} [1m[35mDestination Load (0.6ms)[0m SELECT "destinations".* FROM "destinations" WHERE "destinations"."id" = ? LIMIT 1 [["id", 4]] [1m[36mTrip Load (0.3ms)[0m [1mSELECT "trips".* FROM "trips" WHERE "trips"."id" = ? LIMIT 1[0m [["id", nil]] Completed 404 Not Found in 20ms (ActiveRecord: 1.8ms) ActiveRecord::RecordNotFound (Couldn't find Trip with 'id'=): app/controllers/destinations_controller.rb:14:in `show'* Update 2 : the destinations_controller in its entirety. class DestinationsController < ApplicationController before_action :set_destination, only: [:show, :edit, :update, :destroy] # GET /destinations # GET /destinations.json def index @destinations = Destination.all end # GET /destinations/1 # GET /destinations/1.json def show Rails.logger.debug params.inspect @trip = Trip.find(params[:trip_id]) @destination = Destination.find(params[:id]) end # GET /destinations/new def new @trip = Trip.find(params[:trip_id]) @destination = Destination.new end # GET /destinations/1/edit def edit @trip = Trip.find(params[:trip_id]) @destination = Destination.find(set_destination) end # POST /destinations # POST /destinations.json def create @trip = Trip.find(params[:trip_id]) @destination = @trip.destinations.new(destination_params) respond_to do |format| if @destination.save format.html { redirect_to trip_destination_path(@trip, @destination), notice: 'Destination was successfully created.' } format.json { render :show, status: :created, location: @destination } else format.html { render :new } format.json { render json: @destination.errors, status: :unprocessable_entity } end end end # PATCH/PUT /destinations/1 # PATCH/PUT /destinations/1.json def update respond_to do |format| if @destination.update(destination_params) format.html { redirect_to @destination, notice: 'Destination was successfully updated.' } format.json { render :show, status: :ok, location: @destination } else format.html { render :edit } format.json { render json: @destination.errors, status: :unprocessable_entity } end end end # DELETE /destinations/1 # DELETE /destinations/1.json def destroy @destination.destroy respond_to do |format| format.html { redirect_to destinations_url, notice: 'Destination was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_destination @destination = Destination.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def destination_params params.require(:destination).permit(:name, :description) end end A: Change the show action to this: def show @trip = @destination.trip end Edit: Removed @destination assignment here because of the before_action running set_destination. The Destination model has one Trip: class Destination < ActiveRecord::Base belongs_to :trip end Since you're setting the @destination because id is actually passed over, you can just get @trip through association.
{ "pile_set_name": "StackExchange" }
Q: Advanced Array.prototype.filter with Javascript I have an Javascript object like so... var strategies = [{ "strategy": { "category": "war" } }, { "strategy": { "category": "farming" } }] I then have an array that indicates which results I'd like back. It can be any of the following: [] OR ["war"] ["farming"] OR ["war", "farming"]. If we have the [], I want to return no results. But if ["war", "farming"] I want to return both of the results above. How do I accomplish this with Array.prototype.filter? I saw this post, but couldn't reason through it. strategies.filter((strategy) => ???? ) Thanks for your help. A: You can just check the value with indexOf: var categories = ['war', 'farming']; var filtered = strategies.filter((obj) => { return categories.indexOf(obj.strategy.category) > -1; });
{ "pile_set_name": "StackExchange" }
Q: Oracle RAC and sequences I have various database applications that use sequences, I´m migrating these applications to Oracle RAC from 10g without RAC to 11g with RAC. I need ordered sequences and gaps are tolerated. I'm thinking in cache sequences with order, I don´t know what are the effect in performance. Do you think this is a good option? What are your experience with sequences and RAC? Thanks, A: Exactly what do you mean by "ordered" in this context? By default, each node in the cluster has a separate cache of sequence numbers. So node 1 may be handing out values 1-100 while node 2 is handing out values 101-200. The values returned from a single node are sequential, but session A on node 1 may get a value of 15 while session B on node 2 gets a value of 107 so the values returned across sessions appear out of order. If you specify that the sequence has to be ordered, you're basically defeating the purpose of the sequence cache because Oracle now has to communicate among nodes every time you request a new sequence value. That has the potential to create a decent amount of performance overhead. If you're using the sequence as a sort of timestamp, that overhead may be necessary but it's not generally desirable. The overhead difference in practical terms is going to be highly application dependent-- it will be unmeasurably small for some applications and a significant problem for others. The number of RAC nodes, the speed of the interconnect, and how much interconnect traffic there is will also contribute. And since this is primarily a scalability issue, the practical effect is going to limit how well your application scales up which is inherently non-linear. Doubling the transaction volume your application handles is going to far more than double the overhead. If you specify NOCACHE, the choice of ORDER or NOORDER is basically irrelevent. If you specify ORDER, the choice of CACHE or NOCACHE is basically irrelevent. So CACHE NOORDER is by far the most efficient, the other three are relatively interchangable. They are all going to involve inter-node coordination and network traffic every time you request a sequence value which is, obviously, a potential bottleneck. It would generally be preferrable to add a TIMESTAMP column to the table to store the actual timestamp rather than relying on the sequence to provide a timestamp order. A: Summary CACHE can significantly improve the performance of a sequence that uses ORDER, even on RAC. It's still not as fast as NOORDER, but it can be surprisingly close. Especially if the sequence is only used on one of the nodes at a time. Test Case SQL> create sequence cache_order cache 20 order; Sequence created. SQL> create sequence cache_noorder cache 20 noorder; Sequence created. SQL> create sequence nocache_order nocache order; Sequence created. SQL> create sequence nocache_noorder nocache noorder; Sequence created. SQL> set timing on SQL> declare 2 v_temp number; 3 begin 4 for i in 1 .. 100000 loop 5 v_temp := cache_order.nextval; 6 end loop; 7 end; 8 / PL/SQL procedure successfully completed. Elapsed: 00:00:08.44 SQL> declare 2 v_temp number; 3 begin 4 for i in 1 .. 100000 loop 5 v_temp := cache_noorder.nextval; 6 end loop; 7 end; 8 / PL/SQL procedure successfully completed. Elapsed: 00:00:07.46 SQL> declare 2 v_temp number; 3 begin 4 for i in 1 .. 100000 loop 5 v_temp := nocache_order.nextval; 6 end loop; 7 end; 8 / PL/SQL procedure successfully completed. Elapsed: 00:00:35.15 SQL> declare 2 v_temp number; 3 begin 4 for i in 1 .. 100000 loop 5 v_temp := nocache_noorder.nextval; 6 end loop; 7 end; 8 / PL/SQL procedure successfully completed. Elapsed: 00:00:35.10 Test Case Notes My results were obtained on a 2-node RAC. Only one result set is shown, but I ran the test case multiple times, on different databases, and obtained almost identical results. I also ran the tests concurrently, on different nodes. The CACHE still significantly improves ORDER, although the CACHE NOORDER is more than twice as fast as CACHE ORDER. I've also noticed similar behavior in other environments in the past, although I do not have any results for them. Why? I don't understand why CACHE would make so much of a difference when ORDER is used. The amount of time to generate a number should be irrelevant compared to the time to send data over a network. This makes me think that either Oracle is using a poor algorithm, or my test case is wrong. (If anyone can find a problem with my test case, please let me know.) Also, this answer only discusses the time to generate the sequence. There may be other benefits of using NOORDER. For example, reduced index contention, as described here.
{ "pile_set_name": "StackExchange" }
Q: Android home menu in ICS I added home menu into my app and i need to menu text to be center align.it's work fine in ginger bread.but it is left align in ice cream sandwich.how can i solve this? this is my menu layout <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_home" android:title="@string/home" /> </menu> Screenshot: img http://img594.imageshack.us/img594/5756/device20121123152830.png A: getLayoutInflater().setFactory( new Factory() { @Override public View onCreateView ( String name, Context context, AttributeSet attrs ) { if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) { try { // Ask our inflater to create the view LayoutInflater f = getLayoutInflater(); final View view = f.createView( name, null, attrs ); /* * The background gets refreshed each time a new item is added the options menu. * So each time Android applies the default background we need to set our own * background. This is done using a thread giving the background change as runnable * object */ new Handler().post( new Runnable() { public void run () { view.setBackgroundResource( R.drawable.bg_btn1); view.setPadding(left, top, right, bottom); } } ); return view; } catch ( InflateException e ) {} catch ( ClassNotFoundException e ) {} } return null; } });
{ "pile_set_name": "StackExchange" }
Q: QDir::setCurrent vs QFileInfo:: I've come across a anomaly in Qt (v4.8.4) when re-assigning a new path to a pre-existing QDir object. Here is a reduced example demonstrating this: QString path1("F:/"); //Path must exist... QString path2("F:/Some/Valid/Path/For/You/"); //Path must exist... //Set default... QFileInfo fi1(path1); QDir d(fi1.absoluteDir()); //CASE 1... if(!d.setCurrent(path2)) { qDebug() << QString("Cannot set path (%1)").arg(path2).toAscii().data(); return -1; } qDebug() << "CASE 1:"; qDebug() << QString("path2: %1").arg(path2).toAscii().data(); qDebug() << QString("d : %1").arg(d.absolutePath()).toAscii().data(); //END of CASE 1... //CASE 2... QFileInfo fi2(path2); d = fi2.absoluteDir(); qDebug() << "CASE 2:"; qDebug() << QString("path2: %1").arg(path2).toAscii().data(); qDebug() << QString("d : %1").arg(d.absolutePath()).toAscii().data(); //END of CASE 2... Even though the call to d.setCurrent(path2) returns true, the new path is not set in the QDir object. OTOH, assigning the new path 1st to a QFileInfo object, and then calling absoluteDir() on that object returns an updated QDir object. You can then directly assign the returned object to a pre-existing QDir object (through the overridden assignment operator), and the path in the QDir object will be correctly updated. Why does the CASE 1 not work? A: QDir::setCurrent is a static function that sets the current path of the application. It doesn't modifiy any QDir instance. You should use QDir::setPath to assign a new path (or assign the QString directly to QDir with the = operator, since the conversion is implicit).
{ "pile_set_name": "StackExchange" }
Q: OData with EF Core / ASP.NET Core - Good or Bad? I've read a lot about OData with EF Core / ASP.NET Core. It seems to me that everybody has an opinion on this and It's gotten a bit confusing, so at the risk of sounding dumb, I have a few questions: Please note: ! I'm NOT talking about the classic ASP.NET 4.6 or 4.7 with EF6 ! ! I'm talking about ASP.NET Core with EF Core ! Considering building API - Is there stuff that EF Core alone couldn't handle as well as EF Core with OData? Considering building API - Is it not better to build clean RESTful APIs instead of OData style APIs? Isn't implementing OData stuff sacrificing best practices for convenience? What about long term? Aren't ASP.NET Core + EF Core being built with speed and efficiency in mind and thus won't they be faster and more efficient on their own? A: I will go with Shawn Wildermuth's advice that I found on Pluralsight: OData means that queries are on the client so that versioning OData services becomes risky and it feels like MS is moving away from it so I don't have confidence in the long-term viability of it either.
{ "pile_set_name": "StackExchange" }
Q: Ejabberd Single Request Sign On I have a working Ejabberd server (version 2.1.9) and my client application running just fine, but I wish to modify the way the application's XMPP client connects to Ejabberd in order to reduce the number of requests/responses between them, because its for a mobile environment and I wish to reduce the initial connection time. I've looked up the XMPP protocol specification (RFC 6120) and some protocol extensions (XEPs), namely XEP-0305 Quickstart, but the protocol itself doesn't specify single request sign in and the Quickstart extension although aims to reduce the number of requests isn't enough for the time reduction I'm looking for. After searching and not finding any solution I've started to modify both client and server and wish to accomplish the following for now as a proof of concept: //Client Request <?xml version='1.0'?> <stream:stream ... user='user' pass='pass'> //Server Response <?xml version='1.0'?> <stream:stream ... success='1'> I've managed to modify my client accordingly and the Ejabberd server, and it seems they connect successfully, but any request the client makes after establishing the session doesn't get a response by the server. I've used Wireshark to check the TCP connection client and server side: client side its open and the request is sent, and on the server side is also open and the request is received, but when I try to send the response it is not sent. I've modified ONLY the file ejabberd_c2s.erl and the changes are the following: //init function ... %% changed the first state of the fsm to point to quickstart %%          {ok, wait_for_stream, #state{socket = Socket1, {ok, wait_for_quickstart, #state{socket = Socket1, ... //wait_for_quickstart function ... case resource_conflict_action(U, StateData#state.server, R) of closenew -> send_header(StateData, Server, "1.0", DefaultLang, "0"), send_trailer(StateData), {stop, normal, StateData}; {accept_resource, R2} -> JID = jlib:make_jid(U, StateData#state.server, R2), allow = acl:match_rule(Server,c2s,JID),   case ejabberd_auth:check_password(U, Server, P) of true -> send_header(StateData, Server, "1.0", DefaultLang, "1"), change_shaper(StateData, JID), {Fs, Ts} = ejabberd_hooks:run_fold( roster_get_subscription_lists, StateData#state.server, {[], []}, [U, StateData#state.server]), LJID = jlib:jid_tolower(jlib:jid_remove_resource(JID)), Fs1 = [LJID | Fs], Ts1 = [LJID | Ts], PrivList = ejabberd_hooks:run_fold( privacy_get_user_list, StateData#state.server, #userlist{}, [U, StateData#state.server]), SID = {now(), self()}, Conn = get_conn_type(StateData), Info = [{ip, StateData#state.ip}, {conn, Conn}, {auth_module, StateData#state.auth_module}], ejabberd_sm:open_session(SID, U, StateData#state.server, R, Info), NewStateData = StateData#state{ user = U, resource = R2, jid = JID, sid = SID, conn = Conn, auth_module = ejabberd_auth_internal, authenticated = true, pres_f = ?SETS:from_list(Fs1), pres_t = ?SETS:from_list(Ts1), privacy_list = PrivList}, fsm_next_state_pack(session_established, NewStateData); _ -> %%auth fail end end. Just to clarify: the initial client authentication request and server response are being transmitted just fine, subsequent requests are also being transmitted but there is no response to them. I'm I overlooking something? Thanks in advance A: @Nuno-Freitas Indeed that was what was failing, thanks for your helpful insight. I added the code: R1 = xml:get_attr_s("r",Attrs), R = case jlib:resourceprep(R1) of error -> error; "" -> lists:concat([randoms:get_string() | tuple_to_list(now())]); Resource -> Resource end, That made the server respond to my requests, but there was other thing amiss: the <presence/> tag was breaking on server because the #state.lang was not defined, so I had to define it in the wait_for_quickstart function and now I have a single sign in XMPP client server working proof of concept.
{ "pile_set_name": "StackExchange" }
Q: MB can handle more lanes than the CPU afford (For multi-GPU configuration) I'm building a 4 GPU PC. During my research I was surprised, the manual of an potential motherboard says that a 40 CPU lane can handle four x16 PCIe slots. Can someone explain me how it works ? I thought 1 CPU lane = 1 PCIe lane. When you build powerful computers, it's important to understand where are the bottle necks, or you will waste money. The text in the manual: 40-LANE CPU 7 x PCI Express 3.0/2.0 x16 slots* (single at x16, dual at x16/x16, triple at x16/x16/x16, quad at x16/x16/x16/x16, seven at x16/x8/x8/x8/x8/x8/X8) The link to the manual: http://dlcdnet.asus.com/pub/ASUS/mb/Socket2011-R3/X99-E_WS/Manual/E13676_X99-E_WS_UM_V4_WEB.pdf (warning: the English version have some errors, the 40-lane and 28-lane CPU are not comparable. In the Chinese version you can see the real 4 way with 28-lane CPU 四張採 x16/x8/x8/x8) A: If we look at the motherboard diagram, we can see there is a chip between CPU and PCIe slots This PLX chip does multiplexing. It doesn't create new lanes. So to make it simple, in worst case we are not faster than our 40 CPU lanes. But when a GPU2 has already all his data transfered, GPU1 can passe from x8 to x16 for example. If you want to have more details about how PLX chip work, this article is very nice https://www.anandtech.com/show/6170/four-multigpu-z77-boards-from-280350-plx-pex-8747-featuring-gigabyte-asrock-ecs-and-evga I want to thanks the Asus support for giving me the motherboard diagram.
{ "pile_set_name": "StackExchange" }
Q: How can a macro be created to insert a text box pre-populated with text in Word 2010? I am attempting to create a Macro to insert a textbox populated with predetermined text when a shortcut key is selected. I am able to record a Macro to generate the text but I am unable to get it to populate the text box with the text inside. For example, if I select Ctrl+Alt+T, a text box will be created with the word "truck" in it. Using Microsoft word 2010, how can I accomplish this? A: This isn't specific to your VBA, because we don't know what it is, but below is how to add a textbox with text using VBA. Sub addBox() Dim Box As Shape Set Box = ActiveDocument.Shapes.addTextBox( _ Orientation:=msoTextOrientationHorizontal, _ Left:=50, Top:=50, Width:=100, Height:=100) 'This adds text to the box... Box.TextFrame.TextRange.Text = "Truck" End Sub source
{ "pile_set_name": "StackExchange" }
Q: Format date without translating text Is there a simple way to opt out of the translation that occurs when you format a date like this: {{ expiry | date('D, d M Y H:i:s', 'GMT') }} The problem is that I need this in english to create a valid date for my HTTP headers. But the site is in norwegian so days and months are translated, resulting in an invalid date. A: Not currently - we should probably add a new 'translate' argument to that function which would let you opt out of it. However Craft’s DateTime variables have a rfc1123() function which can be used instead of the Twig |date filter, and its output won’t get automatically translated. For reference, RFC 1123 defines the date/time specification recommended by RFC 2616 (HTTP 1.1) (which is the same as the one defined by RFC 822, just with 4-digit years). {{ expiry.rfc1123() }}
{ "pile_set_name": "StackExchange" }
Q: Query a subobject's property in a mongodb collection in meteor I want to search names in a guest list array that may contain multiple guest objects. This array of objects is stored among other properties in a mongo db collection named "Guests" in my meteor project . SimpleSchema snippet: guestList: { type: [Object], label: "Guest List" } example guest object: var newGuest = [{ firstName: "John", lastName: "Doe" }, { firstname: "Jane", lastName: "Doe" }]; It is being inserted successfully against the SimpleSchema, what I need help with now is how I can search the names if my complete object looks something like this is the collection? { guestList: newGuests, address: "123 4th St. NE", phone: "555-555-5555", email: "[email protected]" } Now let's say I have multiple entries with possible multiple guests within each guestList property but I want to get the entry that has the firstName of "Jane" in its guestList property. I've tried Guests.find({ guestList: { firstName : "Jane" } }).fetch(); but I'm not getting any results. I also tried Guests.find({guestList[0].firstName: "Jane"}).fetch(); with no results as well. Any help would be greatly appreciated! A: It sounds like what you are looking for is the $elemMatch query operator. Take a look at how to use it here too. I suggest writing your query like so: Guests.find({ guestList: { $elemMatch: { firstName: 'Jane' } } }); The reason why you would not use the first query that you specified is because it is trying to match on a single embedded document rather than on an array of documents. Also, the reason why you would not use the second query that you specified is because it is trying to match only on the first embedded document in an array of documents, but obviously you would want to check all of the embedded documents in an array.
{ "pile_set_name": "StackExchange" }
Q: How to randomly divide a huge corpus into 3? I have a corpus(held in a JSerial Datastore) of thousands of documents with annotations. Now I need to divide it into 3 smaller ones, with random picking. What is the easiest way in GATE? a piece of running code or detailed guide will be most welcomed! A: I would use the Groovy console for this (load the "Groovy" plugin, then start the console from the Tools menu). The following code assumes that you have opened the datastore in GATE developer you have loaded the source corpus, and its name is "fullCorpus" you have created three (or however many you need) other empty corpora and saved them (empty) to the same datastore. These will receive the partitions you have no other corpora open in GATE developer apart from these four you have no documents open Then you can run the following in the Groovy console: def rnd = new Random() def fullCorpus = corpora.find { it.name == 'fullCorpus' } def parts = corpora.findAll {it.name != 'fullCorpus' } fullCorpus.each { doc -> def targetCorpus = parts[rnd.nextInt(parts.size())] targetCorpus.add(doc) targetCorpus.unloadDocument(doc) } return null The way this works is to iterate over the documents and pick a corpus at random for each document to be added to. The target sub-corpora should end up roughly (but not necessarily exactly) the same size. The script does not save the final sub-corpora, so if it messes up you can just close them and then re-open them (empty) from the original datastore, the fix and re-run the script. Once you're happy with the final result, right click on each sub-corpus in turn in the left hand tree and "save to its datastore" to write it all to disk.
{ "pile_set_name": "StackExchange" }
Q: Infinitesimal transformation I came across this statement in the book "Quantum Field theory and the Standard Model" by Schwartz. "We would now like to find all the representations of the Lorentz group. The Lorentz group itself is a mathematical object independent of any particular representation. To extract the group away from its representations, it is easiest to look at infinitesimal transformations." I didn't understand how the concept of representation is related to infinitesimal transformation? How are these two concepts related? And what new insight in Physics it gives us? A: If we want to "extract the group away from its representation", then we need to fully know the group structure, i.e. how group elements relate to each other via group multiplication. One way to do this is to build the multiplication table of the group, which explicitly shows all possible multiplications between elements (in other words it defines the group). However, continuous group or more specifically Lie Groups (such as Poincare group) have infinite elements and therefore such multiplication table is out of the question. Yet we want to be able to describe the group structure without mentioning any representation. What we do is to look at the group generators and its Lie algebra. The algebra satisfied by the generators of the group consists in a set of algebraic relations independent of representation and which almost fully define the group. The way we obtain the generators is by looking at infinitesimal group transformation. By definition, Lie groups are differentiable manifolds thus we can find infinitesimal transformations by Taylor expanding around the identity element and we define the generator $T_a$ associated to the parameter $\theta_a$ as $$g(\delta\theta_a)=e+i\delta\theta_a T_a,\quad\mathrm{no\, sum},$$ where $e$ is the identity. I said that the Lie Algebra (or equivalently the local structure of a Lie Group) almost fully determine the group because the same Lie Algebra is in general associated to more than one group. For example, both groups $SU(2)$ and $SO(3)$ have the same algebra $\mathfrak{su}(2)$. In order to associate the algebra with a particular group we also need to specify the representation, which is the same for algebra and group.
{ "pile_set_name": "StackExchange" }
Q: Preserving "columns" when writing from a text file to excel using VBA I have a text file that is formatted in the following way: And I am using the below code in VBA to write the text file into excel: Sub Test() Dim Fn As String, WS As Worksheet, st As String Fn = "Path.txt" ' the file path and name Set WS = Sheets("Sheet1") 'Read text file to st string With CreateObject("Scripting.FileSystemObject") If Not .FileExists(Fn) Then MsgBox Fn & " : is missing." Exit Sub Else If FileLen(Fn) = 0 Then MsgBox Fn & " : is empty" Exit Sub Else With .OpenTextFile(Fn, 1) st = .ReadAll .Close End With End If End If End With 'Replace every two or more space in st string with vbTab With CreateObject("VBScript.RegExp") .Pattern = "[ ]{2,}" .Global = True .Execute st st = .Replace(st, vbTab) End With 'Put st string in Clipboard With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") .SetText st .PutInClipboard End With 'Paste Clipboard to range WS.Range("A1").PasteSpecial End Sub My goal is to preserve the columns from the text file in Excel. However, my code can't tell that a blank space under Plan Type and a blank space under Benefit Plan are actually two different columns of data. It treats the blank space under the two columns as one long blank space, and the formatting isn't preserved. Visually we know there are columns, but my code cannot see this. Is there a way to program this so it recognizes that there are two spaces in the text file instead of one big space? What I want to avoid is having to manually deliminate this with a character. Is that possible? A: Assuming that each column is 10 characters long, I would use this width instead of a space delimeter Sub FeedTextFileToActiveSheet(ByVal TextFile As String) Dim i As Integer, Line As String Open TextFile For Input As #1 While Not EOF(#1) i = i + 1 Input #1, Line Range("A" & i) = Trim(Mid(Line, 1, 10)) 'Business ID Range("B" & i) = Trim(Mid(Line, 11, 10)) 'Employee ID ' ... and so on Wend Close #1 End Sub To use it, just call FeedTextFileToActiveSheet("Path.txt") A: Have you tried the "import from text file option" of excel? If you just want to import the text file to excel with or without headers, then you can import directly in excel using the built in option available in excel.This recognises the header and blank spaces properly.One point to be noted is the headers of the text file should always be in first line for this method. If you are not sure of this, then you can go for a vba script.if so, then the link provided by ferdinando will help you.
{ "pile_set_name": "StackExchange" }
Q: Jquery text replacement into a text I try to change a text into this code : <li> <a id="toggle-edition" href="#"> <span class="glyphicon glyphicon-pencil"></span> Edit page </a> </li> With $("#toggle-edition").text('Save Page') My span is removed :( A: My span is removed is the expected behavior as you are overwriting the content of anchor element. Use the following code: $("#toggle-edition > span")[0].nextSibling.nodeValue = 'Save Page'; <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="toggle-edition" href="#"> <span class="glyphicon glyphicon-pencil"></span> Edit page </a>
{ "pile_set_name": "StackExchange" }
Q: Как сделать callback при выполнении запроса mysql node.js Как дописать функцию что бы она отдавала объект при выполнение запроса? Как к ней дописать coolback Прошу за ранние прощения не силен в этом. function user(val) { var sss=''; const connection = mysql.createConnection({ database: 'base', host: "localhost", user: "root", password: "" }); connection.query("SELECT * FROM `user` WHERE `uid`="+val+"", function(err, results) { console.log(results); //Тут все пришло!!! console.log(err); sss =results; }); connection.end(); return sss; } console.info(user(31)); //Тут пусто!!! A: function user(val) { return new Promise(function (resolve, reject) { var sss=''; const connection = mysql.createConnection({ database: 'base', host: "localhost", user: "root", password: "" }); connection.query("SELECT * FROM `user` WHERE `uid`="+val+"", function(err, results) { if (err) reject(err); resolve(results); }); connection.end(); }) } let user = user(31) .then(function(user) { console.log(user); //Здесь прийдёт }) .catch(function(err) { console.log(err); //Здесь будет ошибка в случае чего })
{ "pile_set_name": "StackExchange" }
Q: Python iterate through connected components in grayscale image I have a gray scale image with values between 0 (black) and white (255). I have a target matrix of the same size as the gray scale image. I need to start at a random pixel in the gray scale image and traverse through the image one pixel at a time (in a depth-first search manner), copying its value to the corresponding location in the target matrix. I obviously need to do this only for the non-white pixels. How can I do this? I thought that I could get the connected components of the gray scale image and traverse each pixel one by one, but I couldn't find any suitable implementation of connected components. Any ideas? For example, if my gray scale image is: [[255,255,255,255,255,255,255] [255,255, 0 ,10 ,255,255, 1 ] [255,30 ,255,255,50 ,255, 9 ] [51 ,20 ,255,255, 9 ,255,240] [255,255,80 ,50 ,170,255, 20] [255,255,255,255,255,255, 0 ] [255,255,255,255,255,255, 69]] Then a possible traversal is [0,10,50,9,170,50,80,20,51,30] followed by [1,9,240,20,0,69] to give [0,10,50,9,170,50,80,20,51,30,1,9,240,20,0,69]. The order between the different objects doesn't matter. Other possible traversals are: [1,9,240,20,0,69,0,10,50,9,170,50,80,20,51,30] or [1,9,240,20,0,69,0,10,50,9,170,50,80,20,30,51] or [1,9,240,20,0,69,10,50,9,170,50,80,20,30,0,51] etc. A: You can use networkx: from itertools import product, repeat import numpy as np import networkx as nx arr = np.array( [[255,255,255,255,255,255,255], [255,255, 0 ,10 ,255,255, 1 ], [255,30 ,255,255,50 ,255, 9 ], [51 ,20 ,255,255, 9 ,255,240], [255,255,80 ,50 ,170,255, 20], [255,255,255,255,255,255, 0 ], [255,255,255,255,255,255, 69]]) # generate edges shift = list(product(*repeat([-1, 0, 1], 2))) x_max, y_max = arr.shape edges = [] for x, y in np.ndindex(arr.shape): for x_delta, y_delta in shift: x_neighb = x + x_delta y_neighb = y + y_delta if (0 <= x_neighb < x_max) and (0 <= y_neighb < y_max): edge = (x, y), (x_neighb, y_neighb) edges.append(edge) # build graph G = nx.from_edgelist(edges) # draw graph pos = {(x, y): (y, x_max-x) for x, y in G.nodes()} nx.draw(G, with_labels=True, pos=pos, node_color='coral', node_size=1000) # draw graph with numbers labels = dict(np.ndenumerate(arr)) node_color = ['coral' if labels[n] == 255 else 'lightgrey' for n in G.nodes()] nx.draw(G, with_labels=True, pos=pos, labels=labels, node_color=node_color, node_size=1000) # build subgraph select = np.argwhere(arr < 255) G1 = G.subgraph(map(tuple, select)) # draw subgraph pos = {(x, y): (y, x_max-x) for x, y in G1.nodes()} labels1 = {n:labels[n] for n in G1.nodes()} nx.draw(G1, with_labels=True, pos=pos, labels=labels1, node_color='lightgrey', node_size=1000) # find connected components and DFS trees for i in nx.connected_components(G1): source = next(iter(i)) idx = nx.dfs_tree(G1, source=source) print(arr[tuple(np.array(idx).T)]) Output: [ 0 10 50 9 50 80 20 30 51 170] [ 9 1 240 20 0 69] A: So after so much researches for suitable implementation of connected components, I came up with my solution. In order to reach the best I can do in terms of performance, I relied on these rules: Not to use networkx because it's slow according to this benchmark Use vectorized actions as much as possible because Python based iterations are slow according to this answer. I'm implementing an algorithm of connected components of image here only because I believe this is an essential part of this question. Algorithm of connected components of image import numpy as np import numexpr as ne import pandas as pd import igraph def get_coords(arr): x, y = np.indices(arr.shape) mask = arr != 255 return np.array([x[mask], y[mask]]).T def compare(r1, r2): #assuming r1 is a sorted array, returns: # 1) locations of r2 items in r1 # 2) mask array of these locations idx = np.searchsorted(r1, r2) idx[idx == len(r1)] = 0 mask = r1[idx] == r2 return idx, mask def get_reduction(coords, s): d = {'s': s, 'c0': coords[:,0], 'c1': coords[:,1]} return ne.evaluate('c0*s+c1', d) def get_bounds(coords, increment): return np.max(coords[1]) + 1 + increment def get_shift_intersections(coords, shifts): # instance that consists of neighbours found for each node [[0,1,2],...] s = get_bounds(coords, 10) rdim = get_reduction(coords, s) shift_mask, shift_idx = [], [] for sh in shifts: sh_rdim = get_reduction(coords + sh, s) sh_idx, sh_mask = compare(rdim, sh_rdim) shift_idx.append(sh_idx) shift_mask.append(sh_mask) return np.array(shift_idx).T, np.array(shift_mask).T, def connected_components(coords, shifts): shift_idx, shift_mask = get_shift_intersections(coords, shifts) x, y = np.indices((len(shift_idx), len(shift_idx[0]))) vertices = np.arange(len(coords)) edges = np.array([x[shift_mask], shift_idx[shift_mask]]).T graph = igraph.Graph() graph.add_vertices(vertices) graph.add_edges(edges) graph_tags = graph.clusters().membership values = pd.DataFrame(graph_tags).groupby([0]).indices return values coords = get_coords(arr) shifts=((0,1),(1,0),(1,1),(-1,1)) comps = connected_components(coords, shifts=shifts) for c in comps: print(coords[comps[c]].tolist()) Outcome [[1, 2], [1, 3], [2, 1], [2, 4], [3, 0], [3, 1], [3, 4], [4, 2], [4, 3], [4, 4]] [[1, 6], [2, 6], [3, 6], [4, 6], [5, 6], [6, 6]] Explanation Algorithm consists of these steps: We need to convert image to coordinates of non-white cells. It can be done using function: def get_coords(arr): x, y = np.indices(arr.shape) mask = arr != 255 return np.array([y[mask], x[mask]]).T I'll name an outputting array by X for clarity. Here is an output of this array, visually: Next, we need to consider all the cells of each shift that intersects with X: In order to do that, we should solve a problem of intersections I posted few days before. I found it quite difficult to do using multidimensional numpy arrays. Thanks to Divakar, he proposes a nice way of dimensionality reduction using numexpr package which fastens operations even more than numpy. I implement it here in this function: def get_reduction(coords, s): d = {'s': s, 'c0': coords[:,0], 'c1': coords[:,1]} return ne.evaluate('c0*s+c1', d) In order to make it working, we should set a bound s which can be calculated automatically using a function def get_bounds(coords, increment): return np.max(coords[1]) + 1 + increment or inputted manually. Since algorithm requires increasing coordinates, pairs of coordinates might be out of bounds, therefore I have used a slight increment here. Finally, as a solution to my post I mentioned here, indexes of coordinates of X (reduced to 1D), that intersects with any other array of coordinates Y (also reduced to 1D) can be accessed via function def compare(r1, r2): # assuming r1 is a sorted array, returns: # 1) locations of r2 items in r1 # 2) mask array of these locations idx = np.searchsorted(r1, r2) idx[idx == len(r1)] = 0 mask = r1[idx] == r2 return idx, mask Plugging all the corresponding arrays of shifts. As we can see, abovementioned function outputs two variables: an array of index locations in the main set X and its mask array. A proper indexes can be found using idx[mask] and since this procedure is being applied for each shift, I implemented get_shift_intersections(coords, shifts) method for this case. Final: constructing nodes & edges and taking output from igraph. The point here is that igraph performs well only with nodes that are consecutive integers starting from 0. That's why my script was designed to use mask-based access to item locations in X. I'll explain briefly how did I use igraph here: I have calculated coordinate pairs: [[1, 2], [1, 3], [1, 6], [2, 1], [2, 4], [2, 6], [3, 0], [3, 1], [3, 4], [3, 6], [4, 2], [4, 3], [4, 4], [4, 6], [5, 6], [6, 6]] Then I assigned integers for them: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] My edges looks like this: [[0, 1], [1, 4], [2, 5], [3, 7], [3, 0], [4, 8], [5, 9], [6, 7], [6, 3], [7, 10], [8, 12], [9, 13], [10, 11], [11, 12], [11, 8], [13, 14], [14, 15]] Output of graph.clusters().membership looks like this: [0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1] And finally, I have used groupby method of Pandas to find indexes of separate groups (I use Pandas here because I found it to be the most efficient way of grouping in Python) Notes Download of igraph is not straightforward, you might need to install it from unofficial binaries.
{ "pile_set_name": "StackExchange" }
Q: What is the best way to use XSLT 2.0 with PHP? This is my second question on the site, like always, I've spent several hours reading a lot of related questions, the 2 most relevant are: Will XPath 2.0 and/or XSLT 2.0 be implemented in PHP? Which explains a solution using PHP/Java Bridge and Saxon. And Upgrade PHP XSLT processor to XSLT 2.0 Which explains a solution using XML_XSLT2Processor, installing it with PEAR and PHP. I focused mainly on the second option since php already have a XSLTProcessor library, but sadly it only supports XSLT 1.0 and I'm looking 2.0 support, so it seemed to be the right option, but after installing PEAR and trying to install XML_XSLT2Processor, and reading many articles(1, 2, 3, the ones I currently have open about the topic) and AltovaXML gone commercial, and PEAR being so buggy, I decided to go with the first option. But I don't really know Java, yet I'm gonna give it a try, but before starting with this I decided to ask first (plus the posts are a little outdated). Isn't there any other better way to manage XSLT 2.0 with PHP? A: The question is timely because last week we launched Saxon/C, a port of Saxon compiled to Intel machine code with APIs for C, C++, and PHP. It's early days yet (an Alpha 0.1 release), but if you don't mind being at the bleeding edge, you might give it a try. And of course we welcome your feedback. Details at http://www.saxonica.com/saxon-c/index.xml
{ "pile_set_name": "StackExchange" }
Q: Automating group creation I'm trying to write a script to automate creating groups from data being exported from SAP. So the data comes out as follows in the first column with part numbers and descriptions in the following ones. .1 ..2 ..2 ...3 ....4 .1 .1 ..2 and so on and so forth with 1 being the highest level and 4 the lowest raw material level there can be one of each or hundreds of each sub-level. Just one export has 2,000-5,000 components so it's a very tedious process starting out with grouping everything manually. So I've been trying to automate this but keep running into walls. My code is a mess and doesn't really do anything but I'll post what I've done. Dim myRange As Range Dim rowCount As Integer, currentRow As Integer Dim GrpRange As Range, GrpStart As Integer, GrpEnd As Integer, GrpCount As Integer Dim GrpLoop As Integer, GrpLoopEnd As Integer, GrpLoopEndRow As Integer Dim GrpSt As Integer GrpSt = 2 GrpStart = 2 GrpEnd = RowEnd(2, 1) GrpLoopEnd = 100 'Loop through each group 'For TotalLoop = 2 To GrpEnd 'Determine 1 to 1 row length For GrpStart = GrpSt To GrpEnd Cells(GrpStart, 1).Select If Right(ActiveCell, 1) = 1 Then GrpSt = ActiveCell.Row For GrpLoop = 0 To GrpLoopEnd If Right(Cells(GrpSt, 1), 1) = 1 Then GrpLoopEnd = 1 GrpLoopEndRow = ActiveCell.Row Exit For End If Next End If Next GrpStart I'm first just trying to find the length between each top level 1 and the next one, because sometimes there is structure and sometimes not. Next I was going to do the same for the 2 then 3 then 4 within that one "group", then do the grouping and finally loop through the rest of the column and do the same with each "1 to 1" group. I'm not sure if this is the right way or even possible but I had to start from somewhere. Here's an example of what is exported: Here's an example of the grouping I'm looking for: A: Try this code: Sub AutoOutline_Characters() Dim intIndent As Long, lRowLoop2 As Long, lRowStart As Long Dim lLastRow As Long, lRowLoop As Long Const sCharacter As String = "." application.ScreenUpdating = False Cells(1, 1).CurrentRegion.ClearOutline lLastRow = Cells(Rows.Count, 1).End(xlUp).Row With ActiveSheet.Outline .AutomaticStyles = False .SummaryRow = xlAbove .SummaryColumn = xlRight End With For lRowLoop = 2 To lLastRow intIndent = IndentCalc(Cells(lRowLoop, 1).Text, sCharacter) If IndentCalc(Cells(lRowLoop + 1, "A"), sCharacter) <= intIndent Then GoTo nxtCl: For lRowLoop2 = lRowLoop + 1 To lLastRow 'for all rows below our current cell If IndentCalc(Cells(lRowLoop2 + 1, "A"), sCharacter) <= intIndent And lRowLoop2 > lRowLoop + 1 Then 'if a higher dimension is encountered If lRowLoop2 > lRowLoop + 1 Then Rows(lRowLoop + 1 & ":" & lRowLoop2).Group GoTo nxtCl End If Next lRowLoop2 nxtCl: Next lRowLoop application.ScreenUpdating = True End Sub Function IndentCalc(sString As String, Optional sCharacter As String = " ") As Long Dim lCharLoop As Long For lCharLoop = 1 To Len(sString) If Mid(sString, lCharLoop, 1) <> sCharacter Then IndentCalc = lCharLoop - 1 Exit Function End If Next End Function
{ "pile_set_name": "StackExchange" }
Q: Case statement with 'OR' statement SELECT ProductNumber, Category = CASE ProductLine WHEN 'R' or 'r' THEN 'Road' WHEN 'M' or 'm' THEN 'Mountain' WHEN 'T' or 't' THEN 'Touring' WHEN 'S' or 's' THEN 'Other sale items' ELSE 'Not for sale' My basic requirement is to use 'OR' with CASE (if possible) , Please suggest if i am doing anything wrong. A: A different way to write case comes close, but then you have to repeat the variable: CASE WHEN ProductLine in ('R', 'r') THEN 'Road' WHEN ProductLine in ('M', 'm') THEN 'Mountain' Or a like character class: CASE WHEN ProductLine like '[Rr]' THEN 'Road' WHEN ProductLine like '[Mm]' THEN 'Mountain' Note that in SQL, string comparison is case-insensitive by default. You can alter the default by setting a case-sensitive database collation, but that's fairly unusual.
{ "pile_set_name": "StackExchange" }
Q: No access to environment variables while remote compiling using Code::Blocks, plink and makefiles I'm trying to set up Code::Blocks under Windows 7 Professional SP1 to work for remote compilation (using PuTTY link -> plink) on a linux server, but I am not much familiar with that topic. This is the manual I used: http://wiki.codeblocks.org/index.php?title=Using_Xming_for_remote_compilation I configured Code blocks as follows: Settings->Compiler and debugger->Global compiler settings->Toolchain executabes: Program Files->Make program: plink.exe Project->Properties->Project Settings: Makefile: makefile_name [checked] This is a custom makefile Execution direction: Z:\Path\to\Samba\Share Project's build options->Debug->"Make" commands: Build project/target: $make -X -ssh user@linux_server -pw my_great_password make -f $makefile -C /path/to/my/makefile Compile single file: $make -X -ssh user@linux_server -pw my_great_password make -f $makefile -C /path/to/my/makefile $file Clean project/target: $make -X -ssh user@linux_server -pw my_great_password make -f $makefile clean -C /path/to/my/makefile Ask if rebuild is needed: $make -X -ssh user@linux_server -pw my_great_password make -q -f $makefile -C /path/to/my/makefile Silent build: $make -X -ssh user@linux_server -pw my_great_password make -s -f $makefile -C /path/to/my/makefile By the way, do I invoke the compiler/linker on the linux server or is Code::Blocks itself compiling and linkung the source on the linux server? Excuse my nescience. The problem I am facing now, is that I can not access environment variables in the makefile: include $(MY_ENV_VAR)/path/to/another/makefile The error I receive let's me assume, that MY_ENV_VAR remains empty: /path/to/another/makefile: No such file or directory I checked if Code::Blocks tries to resolve the environment variable of my windows computer but that is not the case. Additional information: Code::Blocks version: Version: 10.05, Build: May 27 2010, 19:10:05 - wx2.8.10 (Windows, unicode) - 32 bit Linux server: Linux linux_server 2.6.18-238.el5 #1 SMP Sun Dec 19 14:22:44 EST 2010 x86_64 x86_64 x86_64 GNU/Linux I can provide more information if needed. I also welcome other suggestions to realize a remote compilation on a linux machine from windows. Or is another IDE more suitable for doing remote compilation? Thanks for reading/helping. Edit: I found someone having a similar problem with NetBeans IDE: http://forums.netbeans.org/topic37974.html A: According to this stackoverflow post and this fixunix post I could figure out, that plink doesn't execute startup scripts as it is the case, when you connect via putty. So I realized that Code::Blocks was innocent concerning my difficulties while trying to remote compile. In my case, I had to explicitly source the login script ~/.login to have access to my environment variables. For the make command this would for example mean: $make -X -ssh user@linux_server -pw my_great_password "source ~/.login;make -f $makefile" -C /path/to/my/makefile This way a managed to remote compile my software. To start the application, I added a post-build step: cmd /c "C:\Program^ Files\PuTTY\putty.exe -load my_session -pw my_great_password" In the password, I had to escape an ampersand character: ^& (by the way, there are many reasons to use a private key instead of a hardcoded password). This loads a stored PuTTY session, which has the following remote command(s): source ~/.login;/path/to/my/application/my_application;$< I'm using the C shell. Therefore I used $< to wait for an user input (enter key). Now I can compile and run my application by hitting the build button. Hope this helps others to configure Code::Blocks for remote compilation. Just leave a comment if you're facing further problems or if you want to provide additional information/advice.
{ "pile_set_name": "StackExchange" }
Q: My UICollectionView does not update if I use async way to get data If I use the following way to get data, it works fine. The UICollectionView shows the items properly. NSURL *articleUrl = [NSURL URLWithString:url]; NSData *articleHTMLData = [NSData dataWithContentsOfURL:articleUrl]; <Process data here> .... _objects = newArticles; _objects will be feed to UICollectionView. However, if I use the following async way to get data, the UICollectionView does not show anything. dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL); dispatch_async(myQueue, ^{ // Perform long running process NSURL *articleUrl = [NSURL URLWithString:url]; _articleHTMLData = [NSData dataWithContentsOfURL:articleUrl]; dispatch_async(dispatch_get_main_queue(), ^{ <Process data here> .... _objects = newArticles; }); }); Did I miss something? Thanks. A: You need to manually refresh UICollectionView after receiving new data. - (void) reloadData { [self.collectionView performBatchUpdates:^{ [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]]; } completion:nil]; } Call this method inside dispatch_async(dispatch_get_main_queue(), ^{ <Process data here> _objects = newArticles; [self reloadData]; });
{ "pile_set_name": "StackExchange" }
Q: Proguard issue with SAAgent(Samsung Accessory) java.lang.NoSuchMethodException: [] I am trying to use proguard with my android app and am using the samsung accesory sdk which keeps giving be trouble. No matter what I try in the proguard configuration I can't seem to get past this runtime exception: 07-21 13:44:12.851: E/SAAgent(3563): <init> [] 07-21 13:44:12.851: E/SAAgent(3563): java.lang.NoSuchMethodException: <init> [] ... 07-21 13:44:12.851: E/AndroidRuntime(3563): Caused by: java.lang.RuntimeException: Invalid implemetation of SASocket. Provider a public default constructor. ... Does anyone have any idea on what to try? A: The problem is that, with some optimization turned on, Proguard will change every inner class in a top-level class. This means that the default constructor of the inner class will be exchanged with an one-parameter constructor which takes the instance of the outer class, because in java an inner class keeps a reference to the outer class. The Samsung Accesory SDK requires a default constructor for the SASocket inner class implementation because I guess they use reflection to instantiate that object. Here http://sourceforge.net/p/proguard/bugs/387/ you can read that: "Outer$Inner is not changed to a top-level class, unless you also add -repackageclasses and -allowaccessmodification to the configuration". Unfortunately those flags are inherited usually from proguard-android-optimize.txt and if you want to keep the optimization on, the solution is adding to your proguard config: -keepattributes InnerClasses Please, notice, that in order to be able to use the whole functions of the Samsung Accesory SDK you should also include the following rules: # Based on http://proguard.sourceforge.net/manual/examples.html#library -keep public class com.samsung.** { public protected *; } -keepclassmembernames class com.samsung.** { java.lang.Class class$(java.lang.String); java.lang.Class class$(java.lang.String, boolean); } -keepclasseswithmembernames class com.samsung.** { native <methods>; } -keepclassmembers enum com.samsung.** { public static **[] values(); public static ** valueOf(java.lang.String); } -keepclassmembers class com.samsung.** implements java.io.Serializable { static final long serialVersionUID; private static final java.io.ObjectStreamField[] serialPersistentFields; private void writeObject(java.io.ObjectOutputStream); private void readObject(java.io.ObjectInputStream); java.lang.Object writeReplace(); java.lang.Object readResolve(); } A: Just adding this answer as an alternative and update to the already existing answer. Having recently integrated Samsung's Accessory SDK into an Android 'companion' app to support a Tizen app on the Galaxy Gear S2, I ran into the same problem when compiling a (minified) release build of the companion app. @while's answer already explains the cause and remedy of the NoSuchMethodException thrown. However, I found the outlined Proguard rules to be rather relaxed and numerous. This may have necessary for older versions of the Accessory SDK, but these days you can probably do with far less exclusions. Assuming you're using one of the more recent Accessory SDK versions (I tested both 2.2.2 and 2.3.0), you'll still want to start with: -keepattributes InnerClasses You can't get around this one, because the SAAgent uses reflection to instantiate an instance of the SASocket you implement somewhere in your own code. This rule ensures that the relationship between (and naming of) the inner and outer classes doesn't change. Now, you may be tempted to write a rule to keep the default constructor of your SASocket implementation by adding an exclusion for <init>(). Unfortunately, that won't work, because as part of the code optimisation Proguard will actually create a parameterised constructor in the inner class that accepts an instance of the outer class. As a result, that constructor isn't kept and stripped away because Proguard thinks no one is calling it. So, long story short, to keep both your SASocket implementation and its constructor(s), add a rule: -keep class * extends com.samsung.android.sdk.accessory.SASocket { <init>(...); } Up until this far, your app was probably crashing at runtime without the above rules. Having added them, this should no longer be the case. However, you'll notice that the Accessory SDK still logs various errors and that your app isn't yet working as intended. Inspecting Logcat, you should see errors indicating that the SDK failed to bind to your service. The cause for this may not be obvious, but if you dig around the Accessory SDK, you'll notice some IInterface and Binderextensions (i.e. in IDeathCallback and ISAFrameworkManager (2.2.2) or ISAFrameworkManagerV2 (2.3.0)). Since Proguard can't find any explicit calls to them and doesn't know these are in fact invoked at runtime by the Android framework, it'll strip them away. So, let's add a rule to stop Proguard from doing that: -keep class com.samsung.accessory.api.* extends android.os.Binder { *; } After this, it's time for congratulations: your service should now be bindable again. Depending on your implementation you may require further exceptions, but for a basic setup, above should do the trick. Adding it all up, you should have the following rules in your config: # # Samsung Accessory SDK Proguard Rules # # Keep relationship between inner and outer classes -keepattributes InnerClasses # Keep any SASocket implementation and its constructors -keep class * extends com.samsung.android.sdk.accessory.SASocket { <init>(...); } # Keep the Accessory SDK's IInterface and Binder classes -keep class com.samsung.accessory.api.* extends android.os.Binder { *; } YMMV.
{ "pile_set_name": "StackExchange" }
Q: Reducing an Improper Integral The question asks to show that $\displaystyle\int_{-\infty}^\infty \log\left|\frac{1+x}{1-x}\right|\frac{dx}{x}=\pi^2.$ The question walks you through steps on how to show this, but I'm stuck on the first step which asks me to reduce the integral to $$4\int_0^1 \log\left|\frac{1+x}{1-x}\right|\frac{dx}{x}.$$ What I've done so far is show that the integrand is strictly positive and that its an even function with symmetry about $x=0.$ Further, the function blows up as $x \to \pm 1.$ Hence, I have $$ \int_{-\infty}^\infty f(x)\,dx = 2\int_0^1 f(x)\,dx+2\int_1^\infty f(x) \, dx. $$ I'm not sure how to handle the discontinuities. Nor am I confident that this is the correct approach at all. A: Enforce the substitution $x\mapsto\frac 1x$ in your latter integral to obtain $$\small\int_1^\infty\log\left|\frac{1+x}{1-x}\right|\frac{{\rm d}x}x\stackrel{x\mapsto\frac 1x}=-\int_1^0\log\left|\frac{1+\frac1x}{1-\frac1x}\right|\frac1{\frac1x}\frac{{\rm d}x}{x^2}=\int_0^1\log\left|\frac{x+1}{x-1}\right|\frac{{\rm d}x}x=\int_0^1\log\left|\frac{1+x}{1-x}\right|\frac{{\rm d}x}x$$ Continuing by letting $x\mapsto\frac{1-x}{1+x}$ gives $$\int_0^1\log\left|\frac{1+x}{1-x}\right|\frac{{\rm d}x}x\stackrel{x\mapsto\frac{1-x}{1+x}}=-\int_0^1\log\left|\frac1x\right|\frac{2\,{\rm d}x}{1-x^2}=-2\int_0^1\frac{\log x}{1-x^2}\,{\rm d}x$$ Using the geometric series yields $$-2\int_0^1\frac{\log x}{1-x^2}\,{\rm d}x=-2\sum_{n\ge0}\int_0^1 x^{2n}\log x\,{\rm d}x=2\sum_{n\ge0}\frac1{(2n+1)^2}$$ Finally, since $\sum_{n\ge0}\frac1{(2n+1)^2}=\frac34\sum_{n\ge1}\frac1{n^2}=\frac34\zeta(2)$, we obtain $$\therefore~\int_0^1\log\left|\frac{1+x}{1-x}\right|\frac{{\rm d}x}x=\frac{\pi^2}4$$
{ "pile_set_name": "StackExchange" }
Q: SQL: sort by number of empty columns I have a SQL query which displays a list of results. Every row in my database has about 20 columns and not every column is mandatory. I would like the result of the SQL query to be sorted by the number of filled in columns. The rows with the least empty columns at the top, the ones with the most empty columns at the bottom. Do any of you guys have an idea how to do this? I thought about adding an extra column to the table which if updated every time the user edits their row, this number would indicate the number of empty columns and I could sort my list with that. This however, sounds like unnecessary troubles, but maybe there is no other way? I'm sure somebody on here will know! Thanks, Sander A: You can do it in just about any database with a giant case statement: order by ((case when col1 is not null then 1 else 0 end) + (case when col2 is not null then 1 else 0 end) + . . . (case when col20 is not null then 1 else 0 end) ) desc
{ "pile_set_name": "StackExchange" }
Q: Remove a specific data from a string In my selenium project, I'm trying to remove the dynamic data from the below-mentioned string, Example: Success! fnmnt_tag_dstl: Tag Range added: ABC1300000001-1300000096 Here, The following data is kept on changing every time i.e ABC1300000001-1300000096 or XYZ1400000001-1400000048 I want to keep this data from string "Success! fnmnt_tag_dstl: Tag Range added:"as it is and replace/remove ABC1300000001-1300000096 or XYZ1400000001-1400000048 etc... Actual string=> Success! fnmnt_tag_dstl: Tag Range added: ABC1300000001-1300000096 Expected String=> Success! fnmnt_tag_dstl: Tag Range added: A: Simply follow substring function starting from the beginning index to last index of colon (:) operator String actualValue = "Success! fnmnt_tag_dstl: Tag Range added: ABC1300000001-1300000096"; String expectedValue = actualValue.substring(0, actualValue.lastIndexOf(":")+1);
{ "pile_set_name": "StackExchange" }
Q: D3: Can't select a subset of my dataset I would like to select a subset of data with .select() or .selectAll(). For example, I have a dataset: var dataset = [4,5,6,7,9,56] Each number of this dataset is bound to an SVG <rect>: svg.selectAll("rect") .data(dataset) .enter() .append("rect"); Now I would like to select only a subset of data for applying some stuff on it (colouring in yellow in my case). This works for colouring every the <rect>: var allRect = myselection.selectAll("rect") .attr("fill","rgb(255, 255, 0)"); But I would like to select, for example, only the <rect>s corresponding to a number between 5 and 7. Or at least the <rect> corresponding to a specific number from my dataset. I tried: var specificRect = myselection.selectAll("rect")[5:9] var specificRect = myselection.selectAll("rect")[5] var specificRect = myselection.selectAll("rect")[2,3,4] var specificRect = myselection.selectAll("rect").data(dataset)[1] None of those are working. Thanks for your help. A: The solution was the use of ".filter". var specificRect = myselection.selectAll("rect").data(dataset) .filter(function(d) { return (d >= 5 && d <= 9) })
{ "pile_set_name": "StackExchange" }
Q: Overwrite an file which is currently open and it use in c# I am using C# to create a GUI which has a logging feature. When I create the log file, I provide it a filename. But I have the following issue. For instance, if the file is already open in the background on my desktop and I want to name my filename as the same, I get the exception message as following: The process cannot access the file 'C:\blah\blah\mytest.csv' because it is being used by another process. I am using the following piece of code to check if the file exists and using the streamwriter to create the new file. if (FileUtils.Exists(fileName)) { if (!FileUtils.Delete(fileName)) { cout<< Error replacing log file, it might be used by another process"; } } //Exception handling public static bool Delete(string myfiletowrite) { try { File.Delete(myfiletowrite); return true; } catch (IOException) { return false; } } myfile= new StreamWriter(myfiletowrite, true); //exception occurs here when I try to write to myfiletowrite which is currently open I am unsure on how to close this file which is open in the background so I could write to this file. I would appreciate it someone could help me with this. A: If the other application did not explicitely allow it (via Share mode), it is not possible to open the file for writing. If the other application is under your control, you have some options (open the file with FileShare.Write, implement some communication protocol between the two applications, use a common service for accessing the file, ...). Best option would be to choose a different file name.
{ "pile_set_name": "StackExchange" }
Q: Add Cancel button to default camera on Android I am currently using the default camera to take photos for my app. It currently displays Retry and OK buttons at the top of the screen when launched, is there any way of adding cancel to this, which would return the user to the app? A: No, it is not possible. Since we launch the default camera app with startActivityForResult(), which means you are kind of moving out of the app and seeking Result on completion of task on the CameraIntent. Customizing Camera intent is in not your hand untill Camera app exposes some API to do so(which is not yet available).
{ "pile_set_name": "StackExchange" }
Q: What determines a "year" in SW Universe, for age? In The Mandalorian, it's said that the package that the Mandalorian is to pick up is "50 years old". Given how many different planets, stars, etc. there are in the Star Wars universe, what is the "baseline" for a Year? This discussion does point out that a "year" is certainly relative: "Wait. They said fifty years old." "Species age differently. Perhaps it could live many centuries." - "The Mandalorian" and IG-11 upon discovering an infant of the species I found a reference to a "Standard Year": On Coruscant, a year was made up of twelve months[source?] spanning 365 days of 24 hours each, with no leap years. The galaxy used a standardized dating system based off of the galactic capital Coruscant. By the time of the New Republic, the Galactic calendar would use the Battle of Yavin as the epicenter on which to date years So would it all, even in the time-frame of the Mandalorian, and beyond, still be a Corsucantian year? A: Coruscanti time is the universal measurement seen in the Star Wars universe, according to the Lucasfilm Story Group's Pablo Hidalgo. Q. How is time measured in the galaxy if each planet has a different time of rotation and translation? PH: We kind of have assume that there is a standard hour, there is a standard day, a standard week, a standard month, a unit of measurement that everyone understands how long that is. And in our storytelling we say that all that measurement comes from Coruscant, so not only is it the Galactic capital, it's sort of the yardsticks from which all time is measured in the Galaxy Rebel Recon: Inside "The Future of the Force" So to answer your specific question, the Child would be fifty Coruscant (Standard) years old.
{ "pile_set_name": "StackExchange" }
Q: OpenLayers 3: Reload failed tiles I am using OpenLayers 3 with a Zoomify tile source. Based on various conditions I have to re-render my set of tiles on the server side and display the new set to the user as soon as possible. What I would want to do is to display a single zoom level as soon as this is rendered on the server side, and OpenLayers automatically try to get the other tiles when they are ready. But I found that once a tile is not found OpenLayers won't try to reload it afterwards. I am trying to do this manually and I want to catch the tileloaderror event on the Zoomify Source. The event is triggered correctly and I receive the Tile url that was not found. What would I want to do is to add a function here on a timeout to retry to load the tile but I didn't find anything in the API. Is there any method to try to reload a tile if it fails ? A: If anyone has encountered this issue, this will be supported natively by OpenLayers. Reference
{ "pile_set_name": "StackExchange" }
Q: Rational solutions of quadratic Diophantine equation $ax^2+by^2+cz^2+du^2=v^2$? What do we know about the rational solutions of quadratic Diophantine equation $ax^2+by^2+cz^2+du^2=v^2$ in five variables $x,y,z,u,v$? I am looking for references/papers related to this equation. A: $ax^2+by^2+cz^2+du^2=v^2$ Let assume $a+b+c+d=r^2.$ $p,q$ are arbitrary. Substitute $x=pt+1, y=qt+1, z=pt-1, u=qt-1, v=t+r$ to above equation, then we get $$t = \frac{2(ap-qr^2+qa+2bq+qc-cp-r)}{(-ap^2-q^2r^2+q^2a+q^2c-cp^2+1)}.$$ Thus, we get a parametric solution below. \begin{eqnarray} &x& = (a-3c)p^2+(2qc-2qr^2+2qa+4bq-2r)p+q^2a+q^2c+1-q^2r^2 \\ &y& = (-a-c)p^2+(2qa-2qc)p+3q^2c-3q^2r^2+3q^2a+4bq^2+1-2qr \\ &z& = (3a-c)p^2+(2qc-2qr^2+2qa+4bq-2r)p-q^2a-q^2c-1+q^2r^2 \\ &u& = (c+a)p^2+(2qa-2qc)p+q^2c-q^2r^2+q^2a+4bq^2-1-2qr \\ &v& = (-ra-rc)p^2+(2a-2c)p+2qc-2qr^2+2qa+4bq-q^2r^3+rq^2a-r+rq^2c. \end{eqnarray} Example for $(a,b,c,d,r)=(1,2,3,3,3).$ \begin{eqnarray} &x& = -8p^2+(-2q-6)p+1-5q^2\\ &y& = -4p^2-4qp-7q^2-6q+1\\ &z& = (-2q-6)p+5q^2-1\\ &u& = 4p^2-4qp+3q^2-6q-1\\ &v& = -12p^2-4p-2q-3-15q^2 \end{eqnarray}
{ "pile_set_name": "StackExchange" }
Q: Resizing TextView to fit text (with a nine patch background image)? I am using a TextView and a 9 patch image as its background for a messaging application in android. Here's what it looks like: See how for the blue, it is showing too much on the left? How can I reduce it when it decides that it has to wrap the text? I tried to access the Width and Height fields on the view in public View getView(int position, View convertView, ViewGroup parent), however they are always zero (ps the TextView is located inside of a ListView and the getView method is inside the adapter for the ListView). Thank you! TextView XML: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/message_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5sp" android:background="@drawable/bubble_b" android:shadowColor="@color/textShadow" android:shadowDx="1" android:shadowDy="1" android:text="Medium Text" android:textColor="#000000" android:textSize="16sp" android:lineSpacingMultiplier="1.1" /> </LinearLayout> Also, here's a screen of what the nine-patch does for it, so you can see how that works for it: A: In the iPad picture you attached, iMessage is setting maxWidth to the half of the screen I guess. So you can get Screen Width and set maxWidth to half of it for your TextView This is how you can get screen width and pass it to your TextView, Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); yourTextView.setMaxWidth(display.getWidth()/2); P.S. getWidth method for Display class says deprecated, you can find alternative solution to this. You can get width of your LinearLayout also.
{ "pile_set_name": "StackExchange" }
Q: Right way to write testable code in Java without optional parameters vs injection in ABAP OO If I want to write testable Code in Java and decided to use a dependency injection pattern to be able to mock my dependencys in the test environment. Normally I use this pattern in ABAP OO and don't know exactly the best way to achieve the same thing in Java. Here is what I do in ABAP OO: I only implement against interfaces and make sure to be able to inject the interfaces from the outside. The instantiation happens in the constructor. Or if a method needs to instantiate something I add an optional parameter to inject the dependency. Here is an example: CLASS cl_foo DEFINITION. PRIVATE SECTION. DATA: gr_dependency TYPE REF to if_dependency. "if_dependency is an interface PUBLIC SECTION. METHODS: constructor IMPORTING iv_bar TYPE string, "this String makes it complicated in the Java world ir_dependency TYPE REF TO if_dependency OPTIONAL. "CLASS-METHODS: create_instance.... ENDCLASS. CLASS cl_foo IMPLEMENTATION. METHOD constructor. IF ir_dependency IS BOUND. gr_dependency = ir_dependency. ELSE. CREATE OBJECT gr_dependency TYPE cl_dependency_implementation EXPORTING iv_bar. ENDIF. ENDMETHOD. ENDCLASS. But how do I achive the same thing in Java? There are no optinal parameters. Lets say I do something like this: public class Foo { private Dependency dependency; public Foo(String bar, Dependency dependency) { if(dependency == null) { this.dependency = new DependencyImplementation(bar); } } //public static Foo createInstance.... } This is nearly the same behavior (except that "IS BOUND" is different than "== null"). However this does not make it clear, that you don't have to provide an implementation for the interface Dependency. Also if I need references to other classes within Foo I would have to rewrite everything location that instantiates Foo. A: Most of the time, when I'm writing Java code, I setup the dependency externally and don't give classes a default if it is null. Instead, if it's null, I throw an IllegalArgumentException to force the value to be set. Generally, I do something like the following: public class Foo { private final Dependency dependency; public Foo(Dependency dependency) { if(dependency == null) { throw new IllegalArgumentException("dependency must be set message."); } this.dependency = dependency; } // the rest of the code here. } With the variable set to final, it will force the value to be set in the constructor, and by throwing an exception, if the developer attempts to pass null, you will help the programmer help to not miss this requirement quickly, rather than a null pointer exception later down the road. If you are using something like spring with an application context XML file to do dependency injection, then this will also help you to track down misspellings or other problems in the xml file, since it will immediately fail, if you fail to provide the parameter.
{ "pile_set_name": "StackExchange" }
Q: PhoneGap camera not able to confirm after capturing an image I'm making an app to test PhoneGap's capabilities, so that i might later use it for larger projects. I was trying to get the camera API working by building a simple test app that just captures and displays an image. The weird thing is that when i press my capture button which triggers navigate.camera.getPicture() I can take a picture but not confirm the picture so that the process returns to my app and gives me the captured image. All the other buttons are working as expected, so I can for example press cancel and it correctly returns back to my app and runs the function passed as second parameter to navigate.camera.getPicture() (the error handler). Here is how I call navigate.camera.getPicture(): navigator.camera.getPicture( function( uri ) { // code to handle success }, function( msg ) { // code to handle error }, { quality: 100, destinationType: Camera.DestinationType.FILE_URI, encodingType: Camera.EncodingType.PNG, targetWidth: 2000, targetHeight: 2000, correctOrientation: true, saveToPhotoAlbum: false } ); I have tried to comment out all the configuration parameters except destinationType to see if that helped. My config.xml has these lines to allow for camera: <plugin name="Camera" value="org.apache.cordova.CameraLauncher" /> <feature name="http://api.phonegap.com/1.0/camera" /> My debug environment is a Galaxy Nexus running Android 4.2.1. I have also run the app under Ripple which worked exacly as expected. The app is built with PhoneGap Build, not Android SDK on my machine, if that makes a difference. Is there anything I'm missing here? Thanks in advance =) A: I had the same issue running an app built with PhoneGap Build on a Galaxy Nexus running Android 4.2. I was able to solve this issue by using the following two feature directives in my config.xml: <feature name="http://api.phonegap.com/1.0/camera"/> <feature name="http://api.phonegap.com/1.0/file"/> Unfortunately, there were no errors coming from logcat, but this seems to do the trick. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: iPad App - Change languages programmatically I have an app that requires 2 languages, English and French. I have already set up the Localizable.strings files in their respective "en.lproj" and "fr.lproj" folders ... and when I change the iPad's language (in the native settings app), then launch my app, it does in fact load the correct text (i.e. either English copy or French copy). I need to have a UISegmentedControl toggle between the 2 languages without having to restart the app. How do I get the app to change the (current) language so that when I call a method that (re)sets all the UILabels' text and UIImageViews' images they read from the opposite .lproj folder's Localizable.strings file?!? I know how to use UISegmentedControl, and that is not my question. I'm looking more for a line of code that sets the application's bundle language or locale or something (as I'm quite new to internationalization.localization). - Example of how I set the image for a UIImageView: myUIImageView1.image = [UIImage imageNamed:NSLocalizedString(@"myUIImageView1", @"comment for the translator")]; Example of how I set the text of a UILabel: myLabel1.text = NSLocalizedString(@"myLabel1", @"comment for the translator"); A: FOUND THE SOLUTION!!! The following test app had a function that read the desired string from the correct 'Localizable.strings' file (based on the language selected): https://github.com/object2dot0/Advance-Localization-in-ios-apps - I took this code, and the code required to set the app's primary language (found in the above answer posted by Brayden: How to force NSLocalizedString to use a specific language), and put them together. Here's what my code looks like now (note - my UISegmentedControl calls a function in it's view's viewController [when the UISegmentedControl's 'Value Changed' method is triggered] that then calls the toggleLanguage function in the parent viewController): -(void)toggleLanguage:(NSString *)primaryLanguage secondaryLanguage:(NSString *)secondaryLanguage { //set app's primary language defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:[NSArray arrayWithObjects:primaryLanguage,secondaryLanguage,nil] forKey:@"AppleLanguages"]; [defaults synchronize]; //update UILabel and UIImageViews [self setLanguageSpecificItems]; } -(NSString *)languageSelectedStringForKey:(NSString *)key { //read primary language NSArray *appleLanguagesArray = [defaults objectForKey:@"AppleLanguages"]; NSString *currentLanguage = [appleLanguagesArray objectAtIndex:0]; //get the path to the desired lproj file NSString *path; if(currentLanguage==@"en") { path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"]; } else if(currentLanguage==@"fr") { path = [[NSBundle mainBundle] pathForResource:@"fr" ofType:@"lproj"]; } NSBundle* languageBundle = [NSBundle bundleWithPath:path]; //find and return the desired string NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil]; return str; } -(void)setLanguageSpecificItems { myUIImageView1.image = [UIImage imageNamed:[self languageSelectedStringForKey:@"myUIImageView1"]]; myLabel1.text = [self languageSelectedStringForKey:@"myLabel1"]; } - Thanks for the help everyone!!! -Chris Allinson
{ "pile_set_name": "StackExchange" }
Q: How can I quickly delete multiple messages at once in Discord? Is there an easy way to mass delete messages from a Discord channel? It's one of Discord's most requested features and is very helpful if a channel gets flooded with spam messages. The alternative is manually deleting almost every message in the server. A: Add Mee6 bot to your Discord server. One of its moderator options is a !Clear command. Usage: !clear @someone Delete the messages of @someone in the last 100 messages. !clear xx Delete the xx last messages. Maximum of 1000. Higher numbers may take a while and can crash your discord on mobile devices. Alternatively, if adding bots isn't an option, you can make manual deletion a bit easier by holding down Shift. This will skip the confirmation box that usually displays when deleting messages.
{ "pile_set_name": "StackExchange" }
Q: Request: Historical Street Atmos/Walla (Pre-50s) I'm wondering if anyone has or knows where I could find Street Ambience or Walla from the first half of last century. I'm not concerned about a specific nationality or language. I'm working on a uni project where the character travels to a unique, foreign land that has a vintage, steampunk style. The vehicles look vaguely like Model T Fords. A: Search your library for a WAV file named "old traffic". This is a cliche, very often used traffic sound that your uni might have on their drives. It's got a great little "beep beep" in the beginning of the file that I hear at least once a month in dated TV shows and movies.
{ "pile_set_name": "StackExchange" }
Q: My java while loop is not returning back the weekly pay Okay so part two on this. I restructured the code on this but now I can't figure out a way to return back the empWeeklyPay without initializing it to zero. And if I initialize it to zero then my pay will always be zero? Can anyone think of anything I can do? public double getWeeklyPay()//Call the getWeeklyHours method of the Emp's timecard to get the total //hours worked and then multiply the returned value by the emp's hourly rate and return the value. { TimeCard empTimeCard = timeCard; double empWeeklyPay; double totalOtHours; double totalRegHours; int i = 0; while(i <= empTimeCard.NUMDAYS && empTimeCard.getHoursByDay(i) > 8) { double empHourlyRate = getHourlyRate(); double otHours = 0; double regHours = 0; double sumOtHours = 0; int sumRegHours = 0; //grabbing the overtime and reghours and storing them otHours = empTimeCard.getHoursByDay(i) % 8; regHours = empTimeCard.getHoursByDay(i) - otHours; sumOtHours += otHours; sumRegHours += regHours; double tmpBasePay = (sumRegHours * empHourlyRate) + (sumOtHours * empHourlyRate * 1.5); if(Integer.toString(getEmployeeId()).charAt(0) == '0' || Integer.toString(getEmployeeId()).charAt(0) == '2' || Integer.toString(getEmployeeId()).charAt(0) == '9') //Java reads in 1010 so need to convert to a string to do a count on the value. { tmpBasePay += (tmpBasePay * .10); i++; } else if(Integer.toString(getEmployeeId()).charAt(0) == '3') { tmpBasePay -= (tmpBasePay *.10); i++; } else if(Integer.toString(getEmployeeId()).charAt(0) == '8') { tmpBasePay += (tmpBasePay * .20); i++; } totalRegHours = regHours; totalOtHours = sumOtHours; if(totalRegHours > 34) { tmpBasePay -= (tmpBasePay * .06); //empWeeklyPay = tmpBasePay; empWeeklyPay = tmpBasePay; } else { empWeeklyPay = tmpBasePay; } } return empWeeklyPay;// <---need to return back this value. A: Here is the answer to my question. I was able to figure it out. Please see code below in case someone else faces this same problem in the near or distant future: public double getWeeklyPay() { // Call the getWeeklyHours method of the Emp's timecard to get the total hours worked // and then multiply the returned value by the emp's hourly rate and return the value. double empWeeklyPay; double sumOtHours = 0; double sumRegHours = 0; int i = 0; while(i < getTimeCard().NUMDAYS) { // grabbing the overtime and regHours and storing them double otHours = 0; double regHours = 0; otHours += getTimeCard().getHoursByDay(i); regHours += getTimeCard().getHoursByDay(i) - otHours; sumOtHours += otHours; sumRegHours += regHours; i++; } empWeeklyPay = (sumRegHours * getHourlyRate()) + (sumOtHours * getHourlyRate() * 1.5); if(Integer.toString(getEmployeeId()).charAt(0) == '0' || Integer.toString(getEmployeeId()).charAt(0) == '2' || Integer.toString(getEmployeeId()).charAt(0) == '9') { // Java reads in 1010 so need to convert to a string to do a count on the value. double tmpBasePay = (sumRegHours * getHourlyRate()) + (sumOtHours * getHourlyRate() * 1.5); tmpBasePay += (tmpBasePay * .10); empWeeklyPay = tmpBasePay; } else if(Integer.toString(getEmployeeId()).charAt(0) == '3') { double tmpBasePay = (sumRegHours * getHourlyRate()) + (sumOtHours * getHourlyRate() * 1.5); tmpBasePay -= (tmpBasePay * .10); empWeeklyPay = tmpBasePay; } else if(Integer.toString(getEmployeeId()).charAt(0) == '8') { double tmpBasePay = (sumRegHours * getHourlyRate()) + (sumOtHours * getHourlyRate() * 1.5); tmpBasePay += (tmpBasePay * .20); empWeeklyPay = tmpBasePay; } if(sumRegHours > 34) { empWeeklyPay -= (empWeeklyPay * .06 ); return empWeeklyPay; } else return empWeeklyPay; }
{ "pile_set_name": "StackExchange" }
Q: Iterate over a list and making a new row based on Thymeleaf template I'm iterating over my product list and setting the variables like this List<InvoiceEntry> products = invoice.getProducts(); for (InvoiceEntry product : products) { BigDecimal netValue = product.getProduct().getNetValue() .setScale(2, RoundingMode.HALF_UP); double vatRate = product.getProduct().getVatRate().getVatPercent(); BigDecimal vatValue = netValue.multiply(BigDecimal.valueOf(vatRate)) .setScale(2, RoundingMode.HALF_UP); long amount = product.getAmount(); context.setVariable("productName",product.getProduct().getName()); context.setVariable("amount", product.getAmount()); context.setVariable("retailPrice", netValue + "zł"); context.setVariable("productNetValue", netValue.multiply(BigDecimal.valueOf(amount)) + "zł"); context.setVariable("productVatRate", (int) (vatRate * 100) + "%"); context.setVariable("productVatValue", vatValue.multiply(BigDecimal.valueOf(amount)) + "zł"); context.setVariable("total", netValue.add(vatValue).multiply(BigDecimal.valueOf(amount)) + "zł"); } String body = templateEngine.process("template", context); emailSender.sendEmail("[email protected]", "some title", body); return "index"; the template snippet <table width="100%" cellpadding="0" cellspacing="0"> <tr bgcolor="D0D0D0"> <td height="50" align="center"><h2 th:text="Name"></h2></td> <td height="50" align="center"><h2 th:text="Amount"></h2></td> <td height="50" align="center"><h2 th:text="RetailPrice"></h2></td> <td height="50" align="center"><h2 th:text="NetValue"></h2></td> <td height="50" align="center"><h2 th:text="VatRate"></h2></td> <td height="50" align="center"><h2 th:text="VatValue"></h2></td> <td height="50" align="center"><h2 th:text="Total"></h2></td> </tr> <tr bgcolor="ffffff"> <td height="50" align="center"><h2 th:text="${productName}"></h2></td> <td height="50" align="center"><h2 th:text="${amount}"></h2></td> <td height="50" align="center"><h2 th:text="${retailPrice}"></h2></td> <td height="50" align="center"><h2 th:text="${productNetValue}"></h2></td> <td height="50" align="center"><h2 th:text="${productVatRate}"></h2></td> <td height="50" align="center"><h2 th:text="${productVatValue}"></h2></td> <td height="50" align="center"><h2 th:text="${total}"></h2></td> </tr> </table> The question is how can I create a new row of new elements without losing previous data? for example, I want to achieve something like this So far I'm still getting only the last element from the list because of overwriting. I'm pretty new in Thymeleaf so much appreciate every help and tip ;) A: Instead of putting each individual attribute, you put the product list on the model. Then use th:each to loop over it. Controller context.setVariable("products", products); Template <tr bgcolor="ffffff" th:each="product: ${products}"> <td height="50" align="center"><h2 th:text="${product.product.name}"></h2></td> <td height="50" align="center"><h2 th:text="${product.amount}"></h2></td> . . . </tr>
{ "pile_set_name": "StackExchange" }
Q: How to implement bootstrap in an actionlink I would like to implement bootstrap in the following actionlink: @Html.ActionLink("Create New", "DepartmentView", "Department", null, new { @style="text-transform:capitalize;" }) A: @Html.ActionLink("LinkText", "FooAction", "FooController", null, new { @class = "btn btn-info" })
{ "pile_set_name": "StackExchange" }
Q: Splitting of strings based on the required length Is there an easy way on how to split a string based from the required length? For example, I have a string: <Data>AAAAABBBBB1111122222RRRRR<Data> and I want to populate an output like this: AAAAA BBBBB 11111 22222 RRRRR Thank you. A: You can use analyze-string to break up the data: <xsl:template match="Data"> <xsl:variable name="tokens" as="xs:string*"> <xsl:analyze-string select="." regex=".{{1,5}}"> <xsl:matching-substring> <xsl:sequence select="."/> </xsl:matching-substring> </xsl:analyze-string> </xsl:variable> <xsl:value-of select="$tokens" separator="&#10;"/> </xsl:template>
{ "pile_set_name": "StackExchange" }
Q: change state on single li react How can i add class to single li element using onClick? At the moment when i click on whatever li, all div's are getting item-active class when state is changed. I do have index from mapped array, but i'm not sure where (i believe in handleClick()?) should i use it to make it working... //import {cost} from '...'; export class CostFilter extends Component { constructor(props) { super(props); this.state = {active: "item-not-active"}; this.handleClick = this.handleClick.bind(this); } handleClick(){ let isActive = this.state.active === "item-not-active" ? "item-active" : "item-not-active"; this.setState({active: isActive}); } render() { return ( <ul> {cost.map((element, index) => <li onClick={this.handleClick} value={`cost-${element.cost}`} key={index}> <div className={`hs icon-${element.cost} ${this.state.active}`}></div> </li> )} </ul> ); } } A: Try something like this: export class CostFilter extends Component { constructor(props) { super(props); this.state = {activeIndex: null}; } handleClick(index) { let activeIndex = this.state.activeIndex === index ? null : index; this.setState({activeIndex}); } render() { return ( <ul> {cost.map((element, index) => <li onClick={this.handleClick.bind(this, index)} value={`cost-${element.cost}`} key={index}> <div className={` hs icon-${element.cost} ${this.state.activeIndex === index && 'item-active'} `}></div> </li> )} </ul> ); } }
{ "pile_set_name": "StackExchange" }
Q: How to extend windows explorer functionality? How would I go about extending the functionality of windows explorer in XP? Is there some way whereby I could create a "plugin" of some sorts that could hook into explore.exe to add additional folder browsing functionality? What language could I use to achieve this? This is an expansion of a question I asked here. A: There's a great series of tutorials on CodeProject which might help you. C++ is required there.
{ "pile_set_name": "StackExchange" }
Q: Conjecture $\sum_{n=1}^\infty\frac{\ln(n+2)}{n\,(n+1)}\,\stackrel{\color{gray}?}=\,{\large\int}_0^1\frac{x\,(\ln x-1)}{\ln(1-x)}\,dx$ Numerical calculations suggest that $$\sum_{n=1}^\infty\frac{\ln(n+2)}{n\,(n+1)}\,\stackrel{\color{gray}?}=\,\int_0^1\frac{x\,(\ln x-1)}{\ln(1-x)}\,dx=1.553767373413083673460727...$$ How can we prove it? Is there a closed form expression for this value? A: By Frullani's theorem $$ \log(n+2)=\int_{0}^{+\infty}\frac{1-e^{-(n+1)x}}{xe^x}\,dx \tag{1}$$ hence by multiplying both sides by $\frac{1}{n(n+1)}$ and summing over $n\geq 1$ we get: $$ \sum_{n\geq 1}\frac{\log(n+2)}{n(n+1)}=\int_{0}^{+\infty}\frac{(1-e^{-x})\left(1-\log(1-e^{-x})\right)}{xe^x}\,dx\tag{2} $$ then, by substituting $x=-\log(u)$: $$ \sum_{n\geq 1}\frac{\log(n+2)}{n(n+1)}=\int_{0}^{1}\frac{(u-1)\left(1-\log(1-u)\right)}{\log(u)}\,du\tag{3} $$ and the claim follows by substituting $v=(1-u)$. I do not think there is a nice closed form but in terms of a derivative of some special zeta function, due to $\log(n+2) = \left.\frac{d}{d\alpha}(n+2)^{\alpha}\right|_{\alpha=0^+}$, but for sure $$ \int_{0}^{1}\frac{-x}{\log(1-x)}\,dx = \int_{0}^{1}\frac{x-1}{\log x}\,dx = \log 2$$ and the Taylor series of $\frac{x}{\log(1-x)}$ depends on Gregory coefficients. A: Additionnally, by applying Theorem $2$ (here), one obtains a closed form in terms of the poly-Stieltjes constants. Proposition. We have $$ \begin{align} \int_0^1\frac{x\,(\ln x-1)}{\ln(1-x)}\,dx= \ln 2+\gamma_1(2,0)-\gamma_1(1,0) \tag1 \\\\\sum_{n=1}^\infty\frac{\ln(n+2)}{n\,(n+1)}=\ln 2+\gamma_1(2,0)-\gamma_1(1,0) \tag2 \end{align}$$ where $$ \gamma_1(a,b) = \lim_{N\to+\infty}\left(\sum_{n=1}^N \frac{\log (n+a)}{n+b}-\frac{\log^2 \!N}2\right). $$ A: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack} \newcommand{\dd}{\mathrm{d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{\mathrm{i}} \newcommand{\iff}{\Leftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\ol}[1]{\overline{#1}} \newcommand{\pars}[1]{\left(\, #1 \,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\root}[2][]{\,\sqrt[#1]{\, #2 \,}\,} \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ Another possible integral representation: \begin{align} \color{#f00}{\sum_{n = 1}^{\infty}{\ln\pars{n + 2} \over n\pars{n + 1}}} & = \sum_{n = 1}^{\infty}{1 \over n\pars{n + 1}}\ \overbrace{\bracks{\pars{n + 1}\int_{0}^{1}{\dd t \over 1 + \pars{n + 1}t}}} ^{\ds{\ln\pars{n + 2}}} \\[3mm] & = \int_{0}^{1} \sum_{n = 0}^{\infty}{1 \over \pars{n + 2 + 1/t}\pars{n + 1}}\,{\dd t \over t} = \int_{0}^{1} {\Psi\pars{2 + 1/t} - \Psi\pars{1} \over 1 + 1/t}\,{\dd t \over t} \\[3mm] & \stackrel{t\ \to 1/t}{=}\ \color{#f00}{\int_{1}^{\infty} {\Psi\pars{2 + t} - \Psi\pars{1} \over t + 1}\,{\dd t \over t} = \gamma\ln\pars{2} + \int_{1}^{\infty} {\Psi\pars{2 + t} \over t\pars{t + 1}}\,\dd t} \end{align}
{ "pile_set_name": "StackExchange" }
Q: function gives error on linux server I'm using a function i found on php.net(i think) to sort an array based on a value usort($comments, function ($a, $b) { return $b["date"] - $a["date"]; }); It's supposed to put newer dates first.Works just fine on windows localhost, gives error on linux server.Why ? Could anyone give me a replacement ? A: You are probably using a PHP version < 5.3 on your Linux. Anonymous functions are only available on the latest PHP versions. function mySort($a, $b) { return $b["date"] - $a["date"]; } usort($comments, 'mySort'); A: Probably because your server does not run PHP 5.3 and lambda functions are only available since then. What error do you get? In general, the code looks correct. A working version for PHP < 5.3 would be: function custom_sort($a, $b) { return $b["date"] - $a["date"]; } usort($comments, "custom_sort");
{ "pile_set_name": "StackExchange" }
Q: "State information lost" in SimpleSamlphp I got an error State information lost "State information lost" in SimpleSamlphp. Use sprint-security as SP, and configure the Idp on Simplesamlphp. Then,it's ok by browser to redirect the SP webpage to Idp, but after login the username and password, I got an error, "State information lost". ``` Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] array ( 'id' => 'a3a41e7aia439d7371j5e742e35jhi', 'url' => NULL, ) Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] Ron====sid===end Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] NULL Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] Ron====url===end Apr 19 08:52:28 simplesamlphp DEBUG [bc5df4b2c1] Ron====state:NULL Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] SimpleSAML_Error_NoState: NOSTATE Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] Backtrace: Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] 2 /var/simplesamlphp/lib/SimpleSAML/Auth/State.php:274 (SimpleSAML_Auth_State::loadState) Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] 1 /var/simplesamlphp/modules/saml/www/sp/saml2-acs.php:91 (require) Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] 0 /var/simplesamlphp/www/module.php:137 (N/A) Apr 19 08:52:28 simplesamlphp ERROR [bc5df4b2c1] Error report with id f9c150bb generated. ``` I found the stateID was from which sent by SP. And then in Idp side, now the logs shows the sessions contains two valid cookies for a phpsession, and an authtoken. But both of these Ids could not match with the "RequestId", or "InResponseTo" in the response. I'm just stuck here. How does it happen? Anyone can help? Thanks in advance. A: I found the the logic of the php was following with the SP php scripts in my case, and more obviously was that when I changed the "stateId" manually, I got an error like this: SimpleSAML_Error_Exception: This SP [https://domainname/simplesaml/module.php/saml/sp/metadata.php/default-sp] is not a valid audience for the assertion. Candidates were: [com:vdenotaris:spring:sp] which it's very strange and out of my expectation. Then I checked the file "metadata/saml20-sp-remote.php" that SimpleSAMLphp Documentation says it's for adding the SP metadata into Idp configuration to let it know. Finally, I found that I populated in the wrong SP metadata here. It goes wrong if it like this: $metadata['com:vdenotaris:spring:sp'] = array( 'AssertionConsumerService' => 'https://domainname/simplesaml/module.php/saml/sp/saml2-acs.php/default-sp', 'SingleLogoutService' => 'https://domainname/simplesaml/module.php/saml/sp/saml2-logout.php/default-sp', ); The AssertionConsumerService and SingleLogoutService should be assigned the URLs in your SP,since they're the services on the SP. So it should be like this: $metadata['com:vdenotaris:spring:sp'] = array( 'AssertionConsumerService' => 'https://SPonRonSever:8443/prj/saml/SSO', 'SingleLogoutService' => 'https://SPonRonSever:8443/prj/saml/SingleLogout', ); Then when you type "https://SPonRonSever:8443/prj" in the address bar of the browser, it could jump to the login page provided by Idp, after authentication, you could access the web page you wanted.
{ "pile_set_name": "StackExchange" }
Q: All-sides resize of borderless NSWindow in Lion In Lion, the standard resize method for windows changed from the lower-right corner to all sides, with an invisible area to click and drag. I have a custom borderless window, similar to the App Store, on which I would like to have this resize behavior (currently, I have a custom resizer view in the bottom right). I searched for "10.7" in the NSWindow documentation, but none of the newly available messages seem to suggest a way to enable this. Thanks. A: I don't know which object is responsible for setting it up, but NSWindow now has tracking areas in the corners and edges (Open Quartz Debug and check "Show tracking rectangles" to see what I mean). You could emulate this behavior without too much difficulty -- it's basic geometry.
{ "pile_set_name": "StackExchange" }
Q: how do I install MonetDB on Centos 6.5? I would like to install MonetDB on Centos 6.5. MonetDB website describes how to install for Debian / Ubuntu / Fedora distributions. I've a server on Centos 6.5 (and I'm not entirely sure to which Fedora distribution this should compare with). Obviously I would like to install the latest binaries of MonetDB: I would rather avoid to install from source (unless strictly necessary). How do I do it? A: Update: We now also provide CentOS RPMs: https://www.monetdb.org/downloads/epel/ Since we do not provide packages for CentOS, I believe compiling from source is the easiest option. I tried this on a CentOS 6.5 VM, the steps follow below. Simply download a tarball release (e.g. https://www.monetdb.org/downloads/sources/Oct2014-SP2/MonetDB-11.19.9.tar.xz) and then sudo yum install gcc bison openssl-devel pcre-devel libxml2-devel tar xvf MonetDB-*.tar.* cd MonetDB-* ./configure make -j sudo make install That should do it, you should be able to continue with http://www.monetdb.org/Documentation/UserGuide/Tutorial from there. One final note, in the ./configure step, watch out for the line "sql is enabled" towards the end, if it is not there, it will tell you which dependency is missing. Usually, they can be installed using yum (libxy-devel packages).
{ "pile_set_name": "StackExchange" }
Q: Why we need to pass module.exports as a parameter since we are already passing module as a parameter? I have been going through some online tutorials on Node.js. What I understood is that, on using require(./file-path) function, the node gets the content of that file and wraps inside an immediately invoking function (function(exports, require, module, __filename, __dirname) { // content }()) I understood the difference between exports and module.exports. That's all I can see in the internet on searching the above question. But what my question is , why we need to pass module.exports and module to the wrapping IIFE? We could have passed module alone and then get module.exports from it. Is there any advantage on doing like this? Normally when we pass an object to a function , we don't have to pass object.property additionally. A: The answer is: historical reasons. You're right, we could have only module and exports would not be needed but it's still there for backwards compatibility. It used to be a time when the module wrapper was changed in pretty much every patch release. In Node 0.1.11 the module wrapper was: var wrapper = "function (__filename) { "+ " var onLoad; "+ " var onExit; "+ " var exports = this; "+ content+ "\n"+ " this.__onLoad = onLoad;\n"+ " this.__onExit = onExit;\n"+ "};\n"; See: https://github.com/nodejs/node/blob/v0.1.11/src/node.js#L167#L177 As you can see the exports was the same as the this that the wrapper function was called with. You couldn't swap it with a new object and you couldn't even add some reserved keys to it - e.g. you couldn't safely export a property named __onExit. Then in 0.1.12 it was: var wrapper = "function (__filename, exports) { " + content + "\n};"; See: https://github.com/nodejs/node/blob/v0.1.12/src/node.js#L243-L245 Here the exports was an object supplied as one of the arguments but you couldn't swap it with a new object, you could only add or remove properties from the object that you got. Then the 0.1.13 was the first to have this, i.e. require and include: var wrapper = "function (__filename, exports, require, include) { " + content + "\n};"; See: https://github.com/nodejs/node/blob/v0.1.13/src/node.js#L225-L227 Then 0.1.14 was the first to have __module (with underscores) in the wrapper (and that dropped include): var wrapper = "var __wrap__ = function (__module, __filename, exports, require) { " + content + "\n}; __wrap__;"; See: https://github.com/nodejs/node/blob/v0.1.14/src/node.js#L280-L284 And the 0.1.16 was the first to have a module argument (with no underscores) in the wrapper: var wrapper = "var __wrap__ = function (exports, require, module, __filename) { " + content + "\n}; __wrap__;"; See: https://github.com/nodejs/node/blob/v0.1.16/src/node.js#L444-L448 It's been changed many times after that but this is the time that the module got introduced making the exports not necessary any more but still a useful shortcut, allowing you to use: exports.a = 1; exports.b = 2; exports.c = 3; instead of: module.exports.a = 1; module.exports.b = 2; module.exports.c = 3; though in practice if there was no exports then one would usually write: const exports = module.exports; exports.a = 1; exports.b = 2; exports.c = 3; or more likely: module.exports = { a: 1, b: 2, c: 3, }; or, to have some checks in static analysis tools: const a = 1; const b = 2; const c = 3; module.exports = { a, b, c }; There are many ways to do it, it's a pretty flexible mechanism.
{ "pile_set_name": "StackExchange" }
Q: SQL SUM multiple columns and match based on multiple values in one column I need help adding to my SQL statement. All of the Data is located in the same table. My current code is as follows, SELECT Date, Val2, SNumber, SUM(isnull(L1,0) + isnull(L2,0) + isnull(L3,0)) As TotalR, From Table1 Where Val2='Rep' Group By Value 2 has both "Store" and "Rep" I have the total of L1,L2,and L3 coming in great (for Rep's). what i need help with is how to get the total of "Store" L1,L2, and L3 where SNumber matches "Rep" and "Store" Some of the "Reps" are in the same "store" and should have the same total. Source Table Date Val2 Snumber L1 L2 L3 x Store 1 11 5 4 x Store 2 6 8 10 x Rep1 1 5 2 1 x Rep2 1 6 3 3 x Rep3 2 2 1 5 x Rep4 2 3 3 3 x Rep5 2 1 4 2 Result Date Val2 Snumber TotalR TotalS x Rep1 1 8 20 x Rep2 1 12 20 x Rep3 2 8 24 x Rep4 2 9 24 x Rep5 2 7 24 A: You need to use inner join with the subquery of the same table Table1. Here below I prepared scripts for creating and inserting sample data you specified: CREATE TABLE Table1 ( Date DateTime, Val2 Varchar(5), SNumber Smallint, L1 Smallint, L2 Smallint, L3 Smallint ) Run this insert script to create data on the table. INSERT INTO Table1 VALUES(CAST(GETDATE() AS DATE), 'Store', 1, 11, 5, 4), (CAST(GETDATE() AS DATE), 'Store', 2, 6, 8, 10), (CAST(GETDATE() AS DATE), 'Rep1', 1, 5, 2, 1), (CAST(GETDATE() AS DATE), 'Rep2', 1, 6, 3, 3), (CAST(GETDATE() AS DATE), 'Rep3', 2, 2, 1, 5), (CAST(GETDATE() AS DATE), 'Rep4', 2, 3, 3, 3), (CAST(GETDATE() AS DATE), 'Rep5', 2, 1, 4, 2) And on the created table if you run the below script you will get the expected result: SELECT Date, Val2, Table1.SNumber, (L1 + L2 + L3) AS TotalR, S.TotalS FROM Table1(NOLOCK) JOIN ( SELECT SNumber, L1 + L2 + L3 AS TotalS FROM Table1(NOLOCK) WHERE Val2 = 'Store' ) S ON Table1.SNumber = S.SNumber WHERE Val2 <> 'Store' Try on SQL Fiddle ADDITION: The below script lists repos for the store with the maximum TotalS: SELECT Date, Val2, Table1.SNumber, (L1 + L2 + L3) AS TotalR, S.TotalS FROM Table1(NOLOCK) JOIN ( SELECT TOP 1 SNumber, L1 + L2 + L3 AS TotalS FROM Table1(NOLOCK) WHERE Val2 = 'Store' ORDER BY TotalS DESC ) S ON Table1.SNumber = S.SNumber WHERE Val2 <> 'Store'
{ "pile_set_name": "StackExchange" }
Q: Escaping single quote inside a variable before database update This might be a very basic question. I have a variable $name which is input through a form from html page. Now i have to update value of this $name into the database table using a sql query. When $name has single quotes in it, the database update fails. Eg. James O'Hara when it does not have single quotes, the update works fine. Is there a way to escape this single quote inside a variable before updating the database.? I dont want to strip the single quote. just want to escape it so the update goes through fine and actual name is updated in the database. Please let me know. Thanks. A: Generally, the best approach to this is to prepare a query and use a placeholder. Then pass the data to the database to populate the prepared query. An ORM such as DBIx::Class will do this for you automatically. If you are using DBI directly then you would do something like this: $sth = $dbh->prepare("SELECT * FROM users WHERE email = ?"); foreach my $email (@emails) { $sth->execute($email); $row = $sth->fetchrow_hashref; [...] }
{ "pile_set_name": "StackExchange" }
Q: Do the Pre-cogs detect suicides? Leo Crow essentially commits suicide in the movie. This is contrary to what the pre-cogs predicted, but it is a death of passion. If Agatha had been in the temple, would the pre-cogs have created a brown ball for this passionate death, which was essentially self inflicted? A: No, they don't detect suicides. From the original script by Scott Frank ANDERTON : The Precogs don't see what you intend to do, only what you will do. WITWER : Then why can't they see rapes, or assaults... or suicides? FLETCHER : Because of the nature of murder.
{ "pile_set_name": "StackExchange" }
Q: Awk command not working in csh Please let me know what is wrong with below code: #!/bin/csh set str = "peanut" set sr = "an" awk 'BEGIN { print index($str,$sr) }' The error is awk: Field is not correct. The source line number is 1. A: The $variable strings are not interpreted by Csh within the 'single quotes'. Perhaps the simplest fix is to use (GNU) Awk variables as command-line parameters: #!/bin/csh set str = "peanut" set sr = "an" awk -vstr=$str -vsr=$sr 'BEGIN { print index(str, sr)}'
{ "pile_set_name": "StackExchange" }
Q: Write the Maclaurin series for function $f\left(x\right)=\frac{1}{3x+1}\:$ We have function $f:\mathbb{R}\rightarrow \mathbb{R}$ with $$f\left(x\right)=\frac{1}{3x+1}\:$$ $$x\in \left(-\frac{1}{3},\infty \right)$$ Write the Maclaurin series for this function. Alright so from what I learned in class, the Maclaurin series is basically the Taylor series for when we have $x_o=0$ and we write the remainder in the Lagrange form. It has this shape: $f\left(x\right)=\left(T_n;of\right)\left(x\right)+\left(R^Ln;of\right)\left(x\right)=\sum _{k=0}^n\left(\frac{f^{\left(k\right)}\left(0\right)}{k!}x^n+\frac{f^{\left(n+1\right)}\left(c\right)}{\left(n+1\right)!}x^{n+1}\right)$ So when I compute derivatives of my function I can see that the form they take is:$$f^{\left(n\right)}\left(x\right)=\left(-1\right)^n\cdot \frac{3^n\cdot n!}{n!}x^n$$ Does that mean that the Maclaurin series is basically: $$f\left(x\right)=1-3x+3^2x^2-3^3x^3+....+\left(-1\right)^n\cdot 3^n\cdot x^n$$ ? But what about that remainder in Lagrange form? I don't get that part. We didn't really have examples in class, so I've no idea if what I'm doing is correct. Can someone help me with this a bit? A: Hint: Remember that $$\frac{1}{1 + x} = \sum_{n=0}^{\infty} (-1)^n x^n \,\,\,\, \text{for} \,\,\,\ |x| <1$$ Then $$\frac{1}{1 +3x} = \ldots$$ for $|3x| < 1 \implies |x| < \frac{1}{3}$
{ "pile_set_name": "StackExchange" }
Q: How to increase Checkbutton size - Tkinter Is it possible to enlarge the tiny check box of the Checkbutton object? The size is out of proportion when increasing the text size. I searched through the following link (Checkbutton) and can't find anything about the actual size of the box. Thank you for your help. A: It is not possible to change the size of the checkbutton, but you can supply your own images. So, one solution is to create your own images at various sizes.
{ "pile_set_name": "StackExchange" }
Q: How to create a tree view expanded to repeated items in Apache POI I have a requirement to transform an Excel from: A -> B -> C -> 10 A -> B -> C -> 15 A -> B -> C -> 20 D -> E -> F -> 10 D -> E -> F -> 15 D -> E -> F -> 20 To: A -> B -> C -> 10 C -> 15 C -> 20 D -> E -> F -> 10 F -> 15 F -> 20 Is there any POI method to facilitate to achieve this result? I'm already reading the excel file and generating the a result excel, but I couldn't achieve this logic :(. A: Basically transform each cell in one column keeping the last value unchangeable: To: I could achieve \o/ by this code: for (int sheetnum = START_SHEET; sheetnum < numSheets; sheetnum++) { XSSFSheet sheet = wb.getSheetAt(sheetnum); // Total Rows int rows = sheet.getPhysicalNumberOfRows(); // Variable to check the names List<XSSFCell> checkDimCellsName = new ArrayList<>(); for (int i = START_ROW_CONTENT; i < rows; i++) { List<XSSFCell> cellsName = new ArrayList<>(); XSSFRow row = sheet.getRow((short) i); for (int j = START_CELL_CONTENT; j < colsBefore + 1; ++j) { // Cell content cellsName.add(row.getCell((short) j)); row.removeCell(row.getCell((short) j)); } // Space to concat cells String space = ""; if (checkDimCellsName.isEmpty()) { for (XSSFCell cellName : cellsName) { String newDimNameCellValue = space + cellName.getStringCellValue(); cellName.setCellValue(newDimNameCellValue); checkDimCellsName.add(cellName); space += " "; } } else { for (int c = 0; c < cellsName.size(); c++) { if (checkDimCellsName.get(c).getStringCellValue().trim() .equals(cellsName.get(c).getStringCellValue().trim()) && c < cellsName.size() - 1) { cellsName.get(c).setCellValue(""); } else { checkDimCellsName.get(c).setCellValue(cellsName.get(c).getStringCellValue()); cellsName.get(c).setCellValue(space + cellsName.get(c).getStringCellValue()); } space += " "; } } int rowsCreated = 0; Collections.reverse(cellsName); for (int c = 0; c < cellsName.size(); c++) { if (cellsName.get(c).getStringCellValue().trim().length() > 0) { XSSFCell cell = row.createCell((short) START_CELL_CONTENT); cell.setCellValue(cellsName.get(c).getStringCellValue()); cell.setCellStyle(cellsName.get(c).getCellStyle()); if (c == cellsName.size() - 1) { break; } else { if (cellsName.get(c + 1).getStringCellValue().trim().length() > 0) { sheet.shiftRows(i, sheet.getLastRowNum(), 1); row = sheet.createRow(i); rowsCreated++; } } } } i += rowsCreated; rows += rowsCreated; } }
{ "pile_set_name": "StackExchange" }
Q: Designing Raspberry Pi Compute Module with Ethernet capability I recently got the new Raspberry Pi Compute Module due to the small size and ability to create custom board attaching with it. The application requirement I need is just USB, some I/Os and LAN. I realised the module development kit doesn't not come with Ethernet capability. I need LAN to create a client/server secure connection through the Pi. Anyone can share info resources on how to make this compute module ethernet capable? any schematics? A: You can also use the ENC28J60 Module, which is only a few dollars from the usual places - ebay, aliexpress etc, and won't consume your USB port. To do this, wire things up: Pi ENC28J60 ---------------------- +3V3 VCC GND GND GPIO8 CS GPIO9/MISO SO GPIO10/MOSI SI GPIO11/SCLK SCK GPIO25 NT Now, with your pi booted, open up '/boot/config.txt': sudo vi /boot/config.txt Towards the end of the file, add: dtoverlay=enc28j60 Now reboot your pi, and bask in the pleasures of network. This is described in more detail on the RaspberryPi website. A: The Broadcom BCM2835 does not have on-board ethernet so just like the standard raspberry pi you will need to add ethernet via USB. On the B/B+ the ethernet was provided via the LAN9512 USB hub/ethernet chip. So for the compute module development board you can just get a compatible USB ethernet adapter. For a device built around the compute module you might want to look at something like the LAN9512 or LAN9514. You could look at the schematics published by the Raspberry Pi Foundation to see how they did it.
{ "pile_set_name": "StackExchange" }
Q: C: 2d char pointer in a struct I want to write and print some strings in a 2d array in a struct. The struct is called Router and it is in a header file, the 2d array is defined in that struct and it's called **addTab. When I try to print one line of the array using the function viewTable the program stopped working... why? #include <stdlib.h> #include <stdio.h> #include <string.h> #include "router.h" #define N 8 #define M 3 #define sizeMess 5 Router *createRouter(){ Router *NewRouter=(Router*)malloc(sizeof(Router)); int i; NewRouter->addTab=(char **) malloc(N*sizeof(char *)); for(i=0;i<N;i++) NewRouter->addTab[i]=(char *) malloc(M*sizeof(char)); return NewRouter; } void viewTable(Router *r, int a){ int i,j; for(i=0;i<N;i++){ for(j=0;j<M;j++){ printf("raw\t col\t address\t value\t\n"); printf("%d\t %d\t",i,j); printf("%p\t",&r->addTab[i][j]); printf("%s\t\n",r->addTab[i][j]); } } } void updateTable(Router *r, int conn, char *addr1, char *addr2){ r->addTab[conn][1]=addr1; r->addTab[conn][2]=addr2; } A: First off: Don't cast the result of malloc. Assuming that you want to store char* pointers in your 2D array (as the title of your question says), you will need to define it as char *** in your Router structure, like this: typedef struct router { char ***addTab; } Router; Next, you will need to change your createRouter function, so that it can store an array of char* pointers, instead of a single byte for each element, like so: Router *createRouter(){ Router *NewRouter=malloc(sizeof(Router)); int i; NewRouter->addTab=malloc(N*sizeof(char **)); for (i=0;i<N;i++) NewRouter->addTab[i]=malloc(M*sizeof(char *)); return NewRouter; } I'm not sure how you call your updateTable function, but unless you actually fill up the entire array with char* pointers, your viewTable function will also invoke Undefined Behavior, because the printf statements will attempt to access uninitialized data. You could avoid this by using calloc instead of malloc when allocating the 2D array (or explicitly memset it), and then adding NULL checks in your viewTable function. Finally, if you're calling updateTable with char* pointers that are not string literals or they have not been allocated on the heap, you might have further issues...
{ "pile_set_name": "StackExchange" }
Q: What is the lists of fillcolor in Overleaf Latex for bar graph? How to change the default color of bar graph? How can I change the default colour of Overleaf graph template? I found a list of colour My MWE: \documentclass{article} \usepackage[margin=0.5in]{geometry} \usepackage[utf8]{inputenc} \usepackage{textcomp} \usepackage{pgfplots} \pgfplotsset{width=10cm,compat=1.16} \begin{document} \begin{tikzpicture} \pgfplotsforeachungrouped \X in {1,...,9} {\ifnum\X=1 \edef\mylst{Testing1} \else \edef\mylst{\mylst,Testing\X} \fi} \begin{axis}[symbolic x coords/.expanded=\mylst, ylabel=Number, enlargelimits=0.05, x tick label style={anchor=north west,rotate=-30}, legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}, ybar, ] \addplot coordinates {(Testing1,9) (Testing2,4) (Testing3,4) (Testing4,1) (Testing5,1) (Testing6,8) (Testing7,1) (Testing8,1) (Testing9,1)}; \addplot coordinates {(Testing1,3) (Testing2,5) (Testing3,5) (Testing4,4) (Testing5,5) (Testing6,7) (Testing7,0) (Testing8,0) (Testing9,0)}; \legend{Series 1, Series2} \end{axis} \end{tikzpicture} \end{document} A: The default colors have nothing to do with overleaf but they are stored in cycle lists. The relevant cycle list for ybar (which is the same for xbar) can be found on p. 86 of the manual v1.16, You can change it to get e.g. \documentclass{article} \usepackage[margin=0.5in]{geometry} \usepackage[utf8]{inputenc} \usepackage{textcomp} \usepackage[dvipsnames]{xcolor} \usepackage{pgfplots} \pgfplotsset{width=10cm,compat=1.16} \pgfplotsset{ /pgfplots/bar cycle list/.style={/pgfplots/cycle list={ {OliveGreen,fill=OliveGreen!30!white,mark=none}, {Plum,fill=Plum!30!white,mark=none}, {cyan!60!black,fill=cyan!30!white,mark=none}, {black,fill=gray,mark=none}, }, }, } \begin{document} \begin{tikzpicture} \pgfplotsforeachungrouped \X in {1,...,9} {\ifnum\X=1 \edef\mylst{Testing1} \else \edef\mylst{\mylst,Testing\X} \fi} \begin{axis}[symbolic x coords/.expanded=\mylst, ylabel=Number, enlargelimits=0.05, x tick label style={anchor=north west,rotate=-30}, legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}, ybar, ] \addplot coordinates {(Testing1,9) (Testing2,4) (Testing3,4) (Testing4,1) (Testing5,1) (Testing6,8) (Testing7,1) (Testing8,1) (Testing9,1)}; \addplot coordinates {(Testing1,3) (Testing2,5) (Testing3,5) (Testing4,4) (Testing5,5) (Testing6,7) (Testing7,0) (Testing8,0) (Testing9,0)}; \legend{Series 1, Series2} \end{axis} \end{tikzpicture} \end{document} Here I loaded xcolor with the dvipsnames option to get your fancy colors in, you could also use \PassOptionsToPackage{dvipsnames}{xcolor} before \usepackage{pgfplots} since it loads xcolor anyway. Alternatively you can pass the options directly to \addplot: \documentclass{article} \usepackage[margin=0.5in]{geometry} \usepackage[utf8]{inputenc} \usepackage{textcomp} \usepackage[dvipsnames]{xcolor} \usepackage{pgfplots} \pgfplotsset{width=10cm,compat=1.16} \begin{document} \begin{tikzpicture} \pgfplotsforeachungrouped \X in {1,...,9} {\ifnum\X=1 \edef\mylst{Testing1} \else \edef\mylst{\mylst,Testing\X} \fi} \begin{axis}[symbolic x coords/.expanded=\mylst, ylabel=Number, enlargelimits=0.05, x tick label style={anchor=north west,rotate=-30}, legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}, ybar, ] \addplot[fill=ForestGreen!30,draw=ForestGreen] coordinates {(Testing1,9) (Testing2,4) (Testing3,4) (Testing4,1) (Testing5,1) (Testing6,8) (Testing7,1) (Testing8,1) (Testing9,1)}; \addplot[fill=RoyalPurple!30,draw=RoyalPurple] coordinates {(Testing1,3) (Testing2,5) (Testing3,5) (Testing4,4) (Testing5,5) (Testing6,7) (Testing7,0) (Testing8,0) (Testing9,0)}; \legend{Series 1, Series2} \end{axis} \end{tikzpicture} \end{document} You can use any of the colors of your list, of course.
{ "pile_set_name": "StackExchange" }
Q: How to find the script that is activated when clicking on a button? Suppose I have a button in a webpage and I want to find the function that is revoked when the button is clicked. How do I find this script in Chrome developers tools? A: In the Chrome debugger tools, please go to the Source tab. On the extreme right, you'd see the list that says Watch, Call Stack, Scope etc. If you expand Event Listener Breakpoints, you'd see the list of event listeners you can put a break-point on. Expand the Mouse event listener, select click and proceed to click the button. It should hit the break-point. Hope it helps! Edit by Gideon: Blackboxing You may find yourself stepping into library event handlers when you use the Event Listener Breakpoints. You can avoid stepping into these every time by right-clicking and selecting 'Blackbox script' as per below:
{ "pile_set_name": "StackExchange" }