qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
41,534
I use my Raspbery PI model B for capturing images for a timelapse. I capture an image every 30 seconds (roughly) using the build in `raspistill` command within a simple bash script seen below: ``` #!/bin/bash imagePath="/home/pi/weatherPi-images/" echo "Press [CTRL+C] to stop.." echo "AutoImage process started @ "`date +"%FT%H_%M_%S"` while : do timestamp=`date +"%FT%H_%M_%S"` imageName=$imagePath$timestamp".jpg" echo "Taking picture $imageName" raspistill -o $imageName -e jpg sleep 30 done ``` Regardless of what I do after sometimes a few hours or this time after four days of straight image capturing (7600+ images) the Pi freezes / the camera LED stays red and the pi is not responding anymore. There is no recurring time interval between these crashes. The only way to fix this is by cutting the power input from the Pi and restarting it. After some research most people told that the cause for such a behaviour is a low power- / quality PSU. But in my case the PSU is no problem. It is a [5V/5A/25W](http://cdn-reichelt.de/documents/datenblatt/D400/RS-25-SPEC.pdf) power supply which is directly connected to the mains power (which is stable over the year / no blackouts) and has a big power overhead for such a use case. The output voltage is set to ~ 5.1V (±0.05V) so even if the Raspberry Pi draws a lot of power, the voltage is never dropping below 5V. Right before the Raspberry Pi crashed this time I got this in the : [`kern.log`](https://paste.ee/p/USQ73#TRkp0A65xuMye8Cib0dwW2erC3n7xumy) (click to see more) It seems that the raspistill script which is written in Python is hanging / filling up all memory. What can I do to avoid such crashes? If my Pi stays as unreliable for image capturing as it is right now I cannot use it for a long term timelapse (1+ years). One more thing to mention is that if the outside temperature is higher, the more likely the Pi crashes. The Pi is mounted outside and the temperatures here were lower than 0°C / 32°F for the last Week, today the temperatures were above freezing point again. The Pi's case temperature has been at around 10°C (50°F)for the past week and because of the higher outside temperatures was going up to 15-18°C (59-64.4°F)today My Raspberry Pi is overclocked with `raspi-config` to 1 GHz, this was never an issue as the CPU has a heatsink on it and is always below 40°C (104°F). The Pi had an uptime of 35 days before the crash. System information: **lsb\_release -a** ``` No LSB modules are available. Distributor ID: Raspbian Description: Raspbian GNU/Linux 8.0 (jessie) Release: 8.0 Codename: jessie ``` **uname -a** ``` Linux horizon 4.1.13+ #826 PREEMPT Fri Nov 13 20:13:22 GMT 2015 armv6l GNU/Linux ``` **lsusb** ``` Bus 001 Device 004: ID 7392:7811 Edimax Technology Co., Ltd EW-7811Un 802.11n Wireless Adapter [Realtek RTL8188CUS] Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. LAN9500 Ethernet 10/100 Adapter / SMSC9512/9514 Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub ``` **EDIT:** `raspistill` [is written in C](https://github.com/raspberrypi/userland/blob/master/host_applications/linux/apps/raspicam/RaspiStill.c). This makes the crash even more strange to me. **EDIT2:** Some more research brought me to [this article](http://www.blackmoreops.com/2014/09/22/linux-kernel-panic-issue-fix-hung_task_timeout_secs-blocked-120-seconds-problem/). Testing the suggested fixes now, for a long timespan (7+ days).
2016/01/23
[ "https://raspberrypi.stackexchange.com/questions/41534", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/40352/" ]
The OOM killer prints a table summarizing its evaluation when it decides it must kill a process. Generally the biggest one goes. That table is at line 244 in your paste from comments, it begins: ``` Jan 23 16:16:10 horizon kernel: [3070531.743375] [ pid ] uid tgid total_vm rss nr_ptes nr_pmds swapents oom_score_adj name Jan 23 16:16:10 horizon kernel: [3070531.743405] [ 96] 0 96 2954 1 7 0 167 -1000 systemd-udevd Jan 23 16:16:10 horizon kernel: [3070531.743421] [ 467] 0 467 1259 39 6 0 18 0 cron Jan 23 16:16:10 horizon kernel: [3070531.743437] [ 471] 0 471 956 31 4 0 33 0 systemd-logind Jan 23 16:16:10 horizon kernel: [3070531.743454] [ 480] 106 480 987 57 6 0 19 0 avahi-daemon Jan 23 16:16:10 horizon kernel: [3070531.743470] [ 483] 105 483 1390 57 5 0 52 -900 dbus-daemon Jan 23 16:16:10 horizon kernel: [3070531.743485] [ 493] 0 493 634 120 5 0 37 0 dhcpcd Jan 23 16:16:10 horizon kernel: [3070531.743501] [ 496] 106 496 961 15 6 0 40 0 avahi-daemon Jan 23 16:16:10 horizon kernel: [3070531.743516] [ 507] 65534 507 565 4 5 0 26 0 thd Jan 23 16:16:10 horizon kernel: [3070531.743531] [ 528] 0 528 7838 211 11 0 85 0 rsyslogd Jan 23 16:16:10 horizon kernel: [3070531.743546] [ 626] 107 626 1413 48 6 0 64 0 ntpd Jan 23 16:16:10 horizon kernel: [3070531.743561] [ 666] 0 666 1779 29 6 0 72 0 wpa_supplicant Jan 23 16:16:10 horizon kernel: [3070531.743577] [ 672] 0 672 1005 1 6 0 30 0 agetty Jan 23 16:16:10 horizon kernel: [3070531.743592] [ 673] 0 673 960 1 5 0 30 0 agetty Jan 23 16:16:10 horizon kernel: [3070531.743607] [ 720] 0 720 25347 1338 22 0 690 0 php5-fpm Jan 23 16:16:10 horizon kernel: [3070531.743622] [ 739] 0 739 471 1 5 0 26 0 mysqld_safe Jan 23 16:16:10 horizon kernel: [3070531.743637] [ 800] 33 800 25347 9 20 0 707 0 php5-fpm Jan 23 16:16:10 horizon kernel: [3070531.743652] [ 801] 33 801 25347 9 20 0 707 0 php5-fpm Jan 23 16:16:10 horizon kernel: [3070531.743667] [ 1243] 110 1243 79494 461 41 0 6867 0 mysqld ``` There's more, including **at least 50 python processes** that seem to have been spawned in conjunction with `cron` and `sh` processes, which are also still running. The last one above is `mysqld`, which has a modest amount of RSS (461 KB) but by far the largest virtual mem size (~80 MB). Of course, the real culprit is the hundreds of cron/sh/python instances. Here's a guess: After `mysqld` is gone, since it was not the real cause of the problem, the problem persists, and the kernel decides to off one of the python processes. However, it is (possibly, I'm guessing) in an *[uninterruptible sleep](https://en.wikipedia.org/wiki/Sleep_(system_call)#Uninterruptible_sleep)* state ('**D**' in tools such as `top`). This is caused by a hardware I/O failure. For technical reasons, it is not something the kernel will do anything about except wait; if it is a device containing the root filesystem then there may be piles of processes suffering the same fate and the system is fubar'd at that point. The fact that it was able to print a log in that case is interesting, but I/O failure may be because of only a specific part (and not all) of a storage device. Hence, some things accessing it will be fine, others will be stuck in **D**. The normal approach with a spinning disk is to then run a bad blocks check to isolate them and decide whether to chunk it, or just blacklist the bad blocks. With an SD card, the latter is not an option.
Same issue with a Pi Zero while trying to set up LED lights using Hyperion. Had an issue where the Pi would shut off and my capture card I was using would also shut off and fail to be recognized. I ran a test and my CPU was just getting hammered from something that shouldn't take too much of it. Entered the code above which has worked great so far. ``` over_voltage=4 force_turbo=1 ``` I suppose this is a voltage issue given the solution but my CPU is also running normally again. It's also worth also noting that the raspi-config file that you can easily access through SSH didn't work for my Pi Zero as it mentioned you need a Pie 1 or higher to access overclocking settings so had to pull the SD card to my computer and change the file that way.
42,994,378
I have this array ``` Array ( [0] => stdClass Object ( [TransactionNo] => OPM-EC-K-LFMCD2-21.4 [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21 [ItemCode] => BBG150400005 [ItemName] => BIG BAG [OriginalPrice] => 289900.00 [Price] => 289900.00 [QtyBegining] => 0 [QtyIn] => 4 [QtySales] => 0 [QtyMutasi] => 0 [QtyStock] => 4 [QtyOpname] => 0 [QtyAdjust] => -4 [TotalAdjust] => -1159600.00 [rak] => [line] => [TransDate] => 2017-03-31 10:46:00.000 [CustomerCode] => K-LFMCD2 [CreatedBy] => 1208496. [Remark] => re [Remark2] => re [SOTerakhir] => [TglSoTerakhir] => ) [1] => stdClass Object ( [TransactionNo] => OPM-EC-K-LFMCD2-21.5 [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21 [ItemCode] => BBG150500063 [ItemName] => BIG BAG [OriginalPrice] => 479900.00 [Price] => 479900.00 [QtyBegining] => 0 [QtyIn] => 0 [QtySales] => 0 [QtyMutasi] => 0 [QtyStock] => 0 [QtyOpname] => 1 [QtyAdjust] => 0 [TotalAdjust] => .00 [rak] => SS [line] => SS [TransDate] => 2017-03-31 10:46:00.000 [CustomerCode] => K-LFMCD2 [CreatedBy] => 1208496. [Remark] => re [Remark2] => re [SOTerakhir] => [TglSoTerakhir] => ) [2] => stdClass Object ( [TransactionNo] => OPM-EC-K-LFMCD2-21.5 [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21 [ItemCode] => BBG150500063 [ItemName] => BIG BAG [OriginalPrice] => 479900.00 [Price] => 479900.00 [QtyBegining] => 0 [QtyIn] => 1 [QtySales] => 0 [QtyMutasi] => 0 [QtyStock] => 1 [QtyOpname] => 0 [QtyAdjust] => 0 [TotalAdjust] => .00 [rak] => [line] => [TransDate] => 2017-03-31 10:46:00.000 [CustomerCode] => K-LFMCD2 [CreatedBy] => 1208496. [Remark] => re [Remark2] => re [SOTerakhir] => [TglSoTerakhir] => ) [3] => stdClass Object ( [TransactionNo] => OPM-EC-K-LFMCD2-21.6 [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21 [ItemCode] => BBG150500081 [ItemName] => BIG BAG [OriginalPrice] => 229900.00 [Price] => 229900.00 [QtyBegining] => 0 [QtyIn] => 0 [QtySales] => 0 [QtyMutasi] => 0 [QtyStock] => 0 [QtyOpname] => 1 [QtyAdjust] => 0 [TotalAdjust] => .00 [rak] => SS [line] => SS [TransDate] => 2017-03-31 10:46:00.000 [CustomerCode] => K-LFMCD2 [CreatedBy] => 1208496. [Remark] => re [Remark2] => re [SOTerakhir] => [TglSoTerakhir] => ) ) ``` My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way. ``` <table class="table "> <thead> <tr> <th>No</th> <th>ItemCode</th> <th>ItemName</th> <th>TransNo</th> <th>Original Price</th> <th>Price</th> <th>QtyBeginning</th> <th>QtyIn</th> <th>QtySales</th> <th>QtyMutasi</th> <th>QtyStock</th> <th>QtyOpname</th> <th>QtyAdjust</th> <th>TotalAdjust</th> <th>Rak</th> <th>Line</th> </tr> </thead> <tbody> <?php $x=0; foreach ($datadetail as $data) { $x++;?> <tr> <td><?=$x;?></td> <td><?=$data->ItemCode;?></td> <td><?=$data->ItemName;?></td> <td><?=$data->StokOpnameTransNo;?></td> <td><?=$data->OriginalPrice;?></td> <td><?=$data->Price;?></td> <td><?=$data->QtyBegining;?></td> <td><?=$data->QtyIn;?></td> <td><?=$data->QtySales;?></td> <td><?=$data->QtyMutasi;?></td> <td><?=$data->QtyStock;?></td> <td><?=$data->QtyOpname;?></td> <td><?=$data->QtyAdjust;?></td> <td><?=currency($data->TotalAdjust);?></td> <td><?=$data->rak;?></td> <td><?=$data->line;?></td> </tr> <?php } ?> </tbody> </table> ``` the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this [![enter image description here](https://i.stack.imgur.com/E775N.png)](https://i.stack.imgur.com/E775N.png) it just like grouping by `ItemCode`. SO after every itemcode I want to sum `QtyBeginning,QtyIn,QtyOut etc`.
2017/03/24
[ "https://Stackoverflow.com/questions/42994378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6354277/" ]
First I working for improving my English. Second: I have a solution for this issue, try this I hope some help. Idea -> I try to compare Item code from array return by SQL (You mutch sort **Itemcode** by asc order. then try thís code php Code ``` <?php class Item{ protected $data; public function _construct($itemData){ $_arr = array( 'QtyBegining' => $itemData->QtyBegining, 'QtyIn' => $itemData->QtyIn, 'QtySales' => $itemData->QtySales, 'QtyStock' => $itemData->QtyStock, 'QtyOpname' => $itemData->QtyOpname, 'QtyAdjust' => $itemData->QtyAdjust, 'TotalAdjust' => $itemData->TotalAdjust ) $this->data = $_arr; } public function setData($key, $value){ $this->data[$key] = $value; } public function getData($key){ return $this->data[$key]; } public $QtyBegining; public $QtyIn; public $QtySales; public $QtyStock; public $QtyOpname; public $QtyAdjust; public $TotalAdjust; } ?> ``` --- ``` <tbody> <?php $x=0; $revertItemcode = null; $revertSum = null; foreach ($datadetail as $data) { $hasNewItemcode = false; if($revertItemcode == null) { //If first Item $revertItemcode = $data->ItemCode; //Set revert itemcode to new Itemcode $revertSum = new Item($data); }else{ //If have not equa with revert item code if($revertItemcode != $data->ItemCode;){ $hasNewItemcode = true; } } //Sum with revert item if equa Itemcode if(!$hasNewItemcode){ $revertSum->setData('QtyBegining', $revertSum->getData('QtyBegining') + $data->QtyBegining); $revertSum->setData('QtyIn', $revertSum->getData('QtyIn') + $data->QtyIn); $revertSum->setData('QtySales', $revertSum->getData('QtySales') + $data->QtySales); $revertSum->setData('QtyStock', $revertSum->getData('QtyStock') + $data->QtyStock); $revertSum->setData('QtyOpname', $revertSum->getData('QtyOpname') + $data->QtyOpname); $revertSum->setData('QtyAdjust', $revertSum->getData('QtyAdjust') + $data->QtyAdjust); $revertSum->setData('TotalAdjust', $revertSum->getData('revertSum') + $data->TotalAdjust); } $x++; ?> <?php //Echo sumary row with revert item code. if($hasNewItemcode):?> <tr class="sumary-item-code"> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td><?=$revertSum->getData('QtyBegining');?></td> <td><?=$revertSum->getData('QtyIn');?></td> <td><?=$revertSum->getData('QtySales');?></td> <td><?=$revertSum->getData('QtyMutasi');?></td> <td><?=$revertSum->getData('QtyStock');?></td> <td><?=$revertSum->getData('QtyOpname');?></td> <td><?=$revertSum->getData('QtyAdjust');?></td> <td><?=currency($revertSum->getData('TotalAdjust'));?></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <?php //Set revert itemcode to new Itemcode $revertSum = new Item($data); ?> <?php endif;?> <tr> <td><?=$x;?></td> <td><?=$data->ItemCode;?></td> <td><?=$data->ItemName;?></td> <td><?=$data->StokOpnameTransNo;?></td> <td><?=$data->OriginalPrice;?></td> <td><?=$data->Price;?></td> <td><?=$data->QtyBegining;?></td> <td><?=$data->QtyIn;?></td> <td><?=$data->QtySales;?></td> <td><?=$data->QtyMutasi;?></td> <td><?=$data->QtyStock;?></td> <td><?=$data->QtyOpname;?></td> <td><?=$data->QtyAdjust;?></td> <td><?=currency($data->TotalAdjust);?></td> <td><?=$data->rak;?></td> <td><?=$data->line;?></td> </tr> <?php } ?> </tbody> ```
You could use ``` <?php $x=0; foreach ($datadetail as $data) { $x++; $value= $data->QtyBeginning + $data->QtyIn + $data->QtyOut; ?> <tr> <td><?=$x;?></td> <td><?=$data->ItemCode;?></td> <td><?=$value;?></td> <td><?=$data->ItemName;?></td> <td><?=$data->StokOpnameTransNo;?></td> <td><?=$data->OriginalPrice;?></td> <td><?=$data->Price;?></td> <td><?=$data->QtyBegining;?></td> <td><?=$data->QtyIn;?></td> <td><?=$data->QtySales;?></td> <td><?=$data->QtyMutasi;?></td> <td><?=$data->QtyStock;?></td> <td><?=$data->QtyOpname;?></td> <td><?=$data->QtyAdjust;?></td> <td><?=currency($data->TotalAdjust);?></td> <td><?=$data->rak;?></td> <td><?=$data->line;?></td> </tr> <?php } ?> ```
19,958,566
I have the below that I am trying to replicate this mock-up --> ![DoorPanelImage](https://i.stack.imgur.com/vD0w8.jpg) I am stuck on how to make my elements display horizontally? Would I need to make a list or another "table"? Was able to accomplish it using `style` but it seems like I shouldn't need to. Here's what I have so far --> ``` <div id="Row1" class="row"> <div id="Door1" class="col-md-2 panel panel-primary" > <div id="Door1Head" class="panel-heading"> <span class="badge">1</span> <h3 class="panel-title">RE031159</h3> <span class="glyphicon glyphicon-arrow-up"></span> </div> <div class="panel-body"> <ul class="list-group"> <li class="list-group-item"> 12315 Carregeenan WG-16 4000 lbs </li> <li class="list-group-item"> 1063545 Carp meal spread 1042 lbs </li> </ul> </div> </div> <div id="Door2" class="col-md-2"> <span class="badge">2</span> </div> <div id="Door3" class="col-md-2"> <span class="badge">3</span> </div> <div id="Door4" class="col-md-2"> <span class="badge">4</span> </div> <div id="Door5" class="col-md-2"> <span class="badge">5</span> </div> ``` ``` <div id="Row2" class="row"> <div id="Door6" class="col-md-2"> <span class="badge">6</span> </div> <div id="Door7" class="col-md-2"> <span class="badge">7</span> </div> <div id="Door8" class="col-md-2"> <span class="badge">8</span> </div> <div id="Door9" class="col-md-2"> <span class="badge">9</span> </div> <div id="Door10" class="col-md-2"> <span class="badge">10</span> </div> </div> ``` For bigger picture, I am using Bootstrap 3 within an MVC 5 app. I will be populating the info in the mock-up from a SQL DB using EF6. I am imagining that I will be using some `@foreach` loops to build each "card".
2013/11/13
[ "https://Stackoverflow.com/questions/19958566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46724/" ]
Not sure this is exactly what you are looking for, but I'd work at having a single row and getting my panels to just iterate inside the row. Something like this: ``` <div class="row"> <div class="col-2 col-sm-5 col-md-3 col-lg-2 panel panel-primary"> <div class="panel-heading"> <span class="badge">01</span> <h3 class="panel-title">Panel Title</h3> </div><!-- /.panel-heading --> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> </div><!--/span--> </div><!-- /.row --> ``` [Working Bootply example with responsive panels](http://bootply.com/93946)
the col-lg- should be in total 12 for every row you can find this and many other informations at the docu: <http://getbootstrap.com/2.3.2/scaffolding.html> besides this you can also realize something like this without bootstrap by few css lines: ``` width:20% height:250px; display:block; float:left; ```
17,244
More than two years after <http://meta.math.stackexchange.com/q/4569/>, this may be the time for reconsideration. A brief update: 1. In July 2012, when the aforementioned discussion took place, the site received $11000$ questions. In October 2014, the number was $41000$. ([Source](http://data.stackexchange.com/math/query/215244/total-questions-per-month)) [In addition to the above numbers, about $500$ questions asked in July 2012 have subsequently been deleted, compared to $2600$ from October 2014. (Source: special moderator search abilities.)] 2. In 2012, only Stack Overflow disallowed questions by unregistered users. By now, [several other sites](https://meta.stackexchange.com/a/227114/) followed: Physics, Electrical Engineering, Programmers, and Ask Ubuntu. 3. Unregistered users sometimes lose access to their accounts after asking. So they lose ability to edit or comment on their questions, which creates noise: updates and comments posted as answers, or a new identical copy of the question posted. All this takes the time and energy of reviewers, editors, and moderators; and the users themselves are [not happy either](http://meta.math.stackexchange.com/q/16583/). 4. Split accounts are a [known problem](http://meta.math.stackexchange.com/q/10275/147263) for the closure of exact duplicates. 5. Unregistered users cannot delete own posts. So instead they [deface or blank it](http://meta.math.stackexchange.com/q/16320/), leading to chaos: votes to close as unclear, rollbacks, votes to close with custom reason "OP wishes to delete", votes to delete, flags for moderator attention. 6. The quality... well, you know. Back in the days, Qiaochu Yuan wrote > > StackOverflow has less of a need for growth and more of a need to improve the quality of content, but I don't think we're there yet. > > > I think we may be there now. Registration requirement will not magically improve the quality of questions, but if there are fewer of them overall, the arriving questions can be attended to more thoroughly.
2014/11/07
[ "https://math.meta.stackexchange.com/questions/17244", "https://math.meta.stackexchange.com", "https://math.meta.stackexchange.com/users/-1/" ]
It's... uh... been a while since this request was made. We require a few things before turning a switch like this - it's pretty harmful to small sites to have what is a large chunk of potential askers to be blocked. But... Maths isn't a small site, and it hasn't been one for a loooong time. So when this request was first passed into my radar two years ago, it was pretty quickly approved. Just... might've... forgotten to ask the right people to flip switches. And it didn't get into my radar again until this past weekend. Sorry about the delay, but without further ado, these switches are being flipped as I'm writing this answer - **registration will now be required in order to ask a question**.
Yes, I agree with you that atleast email verification should be a must. Another important disadvantage is that it helps people build their own reputation. I've often noticed questions asked anonymously and then answered by registered accounts to earn reputation. I tried it myself and earned 236 reputation from just 4 self-answered questions.
212,054
For this year's April Fools, Google has a Pac-Man option on GoogleMaps. However, it cryptically references clues in which you can play the Pac-Man maps on, as apparently not all cities are supported. There's a list of clues i[t has on its FAQ page](https://support.google.com/maps/answer/6178227?hl=en), but I don't understand most of them. Which cities can I play Pac-Man in?
2015/03/31
[ "https://gaming.stackexchange.com/questions/212054", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/18916/" ]
On the desktop version, you can go anywhere with enough roads for Pac-Man to move around (I did it around my house), but on the app it's limited to the places previously mentioned by Thebluefish.
12 (radiating streets) also works for DC, which was my first guess. :P ======================================================================
4,563
In my custom component, I need to enter date and time. Joomla's standard calendar-element supports a date picker - but no time picker. Can anyone help me and point me to an alternative date and time picker?
2014/09/24
[ "https://joomla.stackexchange.com/questions/4563", "https://joomla.stackexchange.com", "https://joomla.stackexchange.com/users/371/" ]
The only downside to @johanpw's solution is by using #datetimepicker2 that means this field type can only be used once. Good solution otherwise! Instead try the following in your /modules/mod\_yourmodule/fields/datetime.php ``` $id = str_replace('jform[','',str_replace(']','',$this->name)); return '<div id="datetimepicker'.$id.'" class="input-append date">'. '<input name="'.$this->name.'" data-format="MM/dd/yyyy HH:mm:ss PP" value="'.$this->value.'" type="text" />'. '<span class="add-on">'. '<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>'. '</span>'. '</div>'. '<script type="text/javascript">'. 'jQuery(function() {'. 'jQuery("#datetimepicker'.$id.'").datetimepicker({'. 'language: "en",'. 'pick12HourFormat: true,'. 'format: "yyyy-MM-dd hh:mm:ss"'. '});'. '});'. '</script>'; ``` I've also added in `'format: "yyyy-MM-dd hh:mm:ss"'` so you can use it properly within a component with a DateTime SQL field if you desire. I also had issues where the input box would disappear after selecting a date, this could just be me but if anyone else experiences this try this to your admin css: ``` .input-append.date { display: inline-block!important; } ```
JHTML::\_( 'behavior.modal' ); echo JHTML::calendar('2015-04-03','name','id','%d.%m.%Y %H:%I');
39,066,298
My file structure is: ``` dist css style.css index.html js bundle.js src css style.css index.html js main.js node_modules webpack.config.js package.json ``` My webpack.config.js looks like: ``` module.exports = { entry: './src/js/main.js', output: { path: __dirname, filename: './dist/js/bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loader: 'babel', query: { presets: ['es2015'] } }, { test: /\.vue$/, loader: 'vue' } ] } }; ``` I run: ``` webpack-dev-server --content-base dist --hot ``` And it builds and seems like it's working. localhost:8080 shows the expected result but hot-reload does just not work. When I change a file I can see in terminal that a rebuild is happening but nothing happens in the browser. Am I missing something in the config?
2016/08/21
[ "https://Stackoverflow.com/questions/39066298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515187/" ]
**100% Working Solution** You have to just follow 3 steps and you will get your hot reloading as you expected 1. Include "publicPath" key in "Output" property of webpack config. "publicPath" should contain path to your bundle.js file so that dev-server will know if there is any change in your bundle.js file and it will reload your application. Your config should look like this - > > > ``` > output: { > path: __dirname, > publicPath:"/dist/js/", > filename: './dist/js/bundle.js' > } > > ``` > > 2. Add "devServer" option in config file - > > > ``` > devServer:{ > contentBase:"/src/", > inline:true, > stats:"errors-only" > } > > ``` > > Please note that **contentBase** should point to the path where you put your index.html file which contain your script tag in your case it will be "/src/" 3. At last you have to make sure 'src' attribute of your 'script' tag in index.html points to bundle.js starting from "<http://localhost:port>" as follow - > > `<script src="http://localhost:portnumber + value in publicPath + bundle.js"></script>` > > > in your case it will look like this - ``` <script src="http://localhost:8080/js/dist/bundle.js" type="text/javascript"></script> ``` And finally remember `webpack-dev-server doesn't compile your js file or make build or watch on your js` file it dose everything in memory to watch on your js file you have to run `webpack --watch` in seprate window
Try this: In your `package.json` file, delete the line that contains `"test" "echo \"Error: no test specified\" && exit 1"` under the scripts object, and replace it with: ``` ... "scripts": { "start": "webpack-dev-server --hot" }, ... ``` Then to restart your project, just use `npm start`. This worked for me when I ran into this problem. Edit: Can you share your `package.json` file? Try adding this to webpack.config.js as well ``` devServer: { inline: true, port: 3000, hot: true }, ```
59,374,786
I am following [Transfer data with the Data Movement library](https://learn.microsoft.com/en-us/azure/storage/common/storage-use-data-movement-library) to upload a video (mp4) from my local machine to Azure Blob Storage. Here the code. ``` using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.Azure.Storage.DataMovement; using System.Net; using System.Text; using System.IO; using System.Collections.Generic; using Newtonsoft.Json; namespace AzureUpload { class Program { static void Main(string[] args) { try { CloudStorageAccount account = CloudStorageAccount.Parse("<<ConnectionString>>"); ExecuteChoice(account); } catch (Exception e) { Console.ReadLine(); } Console.ReadLine(); } public static void ExecuteChoice(CloudStorageAccount account) { TransferLocalFileToAzureBlob(account).Wait(); } public static string GetSourcePath() { return "E:\\SampleVideo.mp4"; } public static CloudBlockBlob GetBlob(CloudStorageAccount account) { CloudBlobClient blobClient = account.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("<<Container>>"); container.CreateIfNotExistsAsync().Wait(); CloudBlockBlob blob = container.GetBlockBlobReference("MoD0604"); blob.Properties.ContentType = "video/mp4"; // -- added this line to set ContentType as my video file is mp4 return blob; } public static async Task TransferLocalFileToAzureBlob(CloudStorageAccount account) { string localFilePath = GetSourcePath(); CloudBlockBlob blob = GetBlob(account); Console.WriteLine("\nTransfer started..."); await TransferManager.UploadAsync(localFilePath, blob); Console.WriteLine("\nTransfer operation complete."); } } } ``` The sample provided in the link do not have the following line in **GetBlob** method ``` blob.Properties.ContentType = "video/mp4"; // -- added this line to set ContentType as my video file is mp4. ``` I tried with ContentType and without ContentType. In both the cases, it looks like file is uploaded to the Blob. The only difference seems to be with ContentType as shown in below picture. [![enter image description here](https://i.stack.imgur.com/ru1CQ.png)](https://i.stack.imgur.com/ru1CQ.png) The issue is while trying to download any of the files, it resulted in a warning error and later neither of the file played and the following error is shown. [![enter image description here](https://i.stack.imgur.com/AAwqB.png)](https://i.stack.imgur.com/AAwqB.png) Please let me know what I am missing here.
2019/12/17
[ "https://Stackoverflow.com/questions/59374786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2922388/" ]
You can add seconds like this: ``` echo $newTime = date('H:i:s', strtotime("$eta + $newseconds seconds")); ``` output: ``` 14:12:06 ``` Try it [here](http://sandbox.onlinephpfunctions.com/code/7307992f0f0b20e150160df7ca224f43b9c7f0e1). As you see, you can enclose the whole calculation between `" "`, so it's more readable. Also, you need to call `strtotime` once, which makes the script faster. You can learn more about `strtotime` in the [official documentation](https://www.php.net/strtotime).
Why not using PHP 's own `DateTime` class? ``` $seconds = 6; $time = '14:12:00'; echo DateTime::createFromFormat('H:i:s', $time) ->modify('+' . $seconds . 'seconds') ->format('H:i:s'); ``` Using the `DateTime` class enabled method chaining and you can use all methods this object includes. Read more in the documentation under [PHP: DateTime - Manual](https://www.php.net/manual/en/class.datetime.php).
2,859,005
I have a large data-set of emails sent and status-codes. ``` ID Recipient Date Status 1 someone@example.com 01/01/2010 1 2 someone@example.com 02/01/2010 1 3 them@example.com 01/01/2010 1 4 them@example.com 02/01/2010 2 5 them@example.com 03/01/2010 1 6 others@example.com 01/01/2010 1 7 others@example.com 02/01/2010 2 ``` In this example: * all emails sent to **someone** have a status of **1** * the middle email (by date) sent to **them** has a status of **2**, but the latest is **1** * the last email sent to **others** has a status of **2** What I need to retrieve is a count of all emails sent to each person, and what the **latest** status code was. The first part is fairly simple: ``` SELECT Recipient, Count(*) EmailCount FROM Messages GROUP BY Recipient ORDER BY Recipient ``` Which gives me: ``` Recipient EmailCount someone@example.com 2 them@example.com 3 others@example.com 2 ``` How can I get the most recent status code too? The end result should be: ``` Recipient EmailCount LastStatus someone@example.com 2 1 them@example.com 3 1 others@example.com 2 2 ``` Thanks. (Server is Microsoft SQL Server 2008, query is being run through an OleDbConnection in .Net)
2010/05/18
[ "https://Stackoverflow.com/questions/2859005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138033/" ]
You cannot easily do this is a single query because count(\*) is a group function whereas the latest status comes from a specific row. Here is the query to get the latest status for each user: ``` SELECT M.Recipient, M.Status FROM Messages M WHERE M.Date = (SELECT MAX(SUB.Date) FROM MESSAGES SUB WHERE SUB.Recipient = M.Recipient) ```
You can use the ranking functions for this. Something like (not tested): ``` WITH MyResults AS ( SELECT Recipient, Status, ROW_NUMBER() OVER( Recipient ORDER BY ( [date] DESC ) ) AS [row_number] FROM Messages ) SELECT MyResults.Recipient, MyCounts.EmailCount, MyResults.Status FROM ( SELECT Recipient, Count(*) EmailCount FROM Messages GROUP BY Recipient ) MyCounts INNER JOIN MyResults ON MyCounts.Recipient = MyResults.Recipient WHERE MyResults.[row_number] = 1 ```
33,122,216
We've configured Apache to redirect to an instance of tomcat through a diferent port of the AJP default 8009 . It only works for the default port but it's not working with the one we set (8109) on the worker.properties This is our scenario **worker.properties on /etc/apache2** ``` worker.list=sacmimexico # Set properties for sacmimexico worker.sacmimexico.type=ajp13 worker.sacmimexico.host=localhost worker.sacmimexico.port=8109 ``` **server.xml on /usr/share/instance-tomcat-7.0.42/sacmimexico/conf/** ``` <!-- Define an AJP 1.3 Connector on port 8009 --> <Connector port="8109" protocol="AJP/1.3" redirectPort="8143" /> ``` **mod\_jk.log on /var/log/apache2** ``` [Wed Oct 14 05:29:18 2015] [17752:140024424515392] [info] init_jk::mod_jk.c (3189): mod_jk/1.2.30 initialized [Wed Oct 14 05:29:18 2015] [17753:140024424515392] [info] init_jk::mod_jk.c (3189): mod_jk/1.2.30 initialized [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] jk_open_socket::jk_connect.c (622): connect to 127.0.0.1:8009 failed (errno=111) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] ajp_connect_to_endpoint::jk_ajp_common.c (959): Failed opening socket to (127.0.0.1:8009) (errno=111) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [error] ajp_send_request::jk_ajp_common.c (1585): (sacmimexico) connecting to backend failed. Tomcat is probably not started or is listening on the wrong port (errno=111) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] ajp_service::jk_ajp_common.c (2540): (sacmimexico) sending request to tomcat failed (recoverable), because of error during request sending (attempt=1) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] jk_open_socket::jk_connect.c (622): connect to 127.0.0.1:8009 failed (errno=111) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] ajp_connect_to_endpoint::jk_ajp_common.c (959): Failed opening socket to (127.0.0.1:8009) (errno=111) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [error] ajp_send_request::jk_ajp_common.c (1585): (sacmimexico) connecting to backend failed. Tomcat is probably not started or is listening on the wrong port (errno=111) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] ajp_service::jk_ajp_common.c (2540): (sacmimexico) sending request to tomcat failed (recoverable), because of error during request sending (attempt=2) [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [error] ajp_service::jk_ajp_common.c (2559): (sacmimexico) connecting to tomcat failed. [Wed Oct 14 05:29:22 2015] sacmimexico 199.187.122.163 0.100588 [Wed Oct 14 05:29:22 2015] [17757:140024328361728] [info] jk_handler::mod_jk.c (2618): Service error=-3 for worker=sacmimexico ``` **jk.conf on /etc/apache2/mods-available** ``` <IfModule mod_jk.c> JkWorkersFile "/etc/apache2/workers.properties" JkLogFile "/var/log/apache2/mod_jk.log" JkLogLevel info JkLogStampFormat "[%a %b %d %H:%M:%S %Y] " JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories JkRequestLogFormat "%w %V %T" </IfModule> ``` **default on /etc/apache2/sites-available** ``` JkMount /sacmimexico/* sacmimexico ``` Versions: Apache 2 :Apache/2.2.16 (Debian) Tomcat 7 : Apache Tomcat/7.0.42 mod-jk : 1.2.30-1squeeze1 We know that Tomcat is working on that port 8109 Anyone knows what's happening? Thanks Albert
2015/10/14
[ "https://Stackoverflow.com/questions/33122216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5444447/" ]
In this particular case, this is your shortest method ``` <input type="button" value="1" onclick="pressNumber(1)"> <input type="button" value="2" onclick="pressNumber(2)"> function pressNumber(number) { document.getElementById("calc-output").innerHTML = number; } ``` The problem in your original code was that you are calling a function with `()`in a place where you have to assign a function.
Note that onclick events always come with a link to the div that triggered the event. You should make use of that to capture which button was clicked. e in below function will refer to the clickevent. e.target will refer to the div, e.target.id will refer to the id of said div. ``` function buttonClicked(e){ console.log(e.target.id); console.log('clicked in',document.getElementById(e.target.id).parentNode.id); } ``` You could then attach said function to your div like so. ``` document.getElementById(buttonDivName).addEventListener("click", buttonClicked) ```
31,415,844
Python allows dictionaries to be compared with `==` ``` import copy child = {'name': 'child'} parent_1 = {'name': 'parent', 'child': child} parent_2 = copy.deepcopy(parent_1) print(parent_1 == parent_2) ``` Prints `True`, as you would expect it to. Python also allows dictionaries to reference each other circularly. ``` child = {'name': 'child'} parent_1 = {'name': 'parent', 'child': child} child['parent'] = parent_1 # Create the circular reference ``` However, trying to use the `==` operator on dictionaries with circular references raises an error. ``` parent_2 = copy.deepcopy(parent_1) print(parent_1 == parent_2) ``` Returns ``` C:\Python34\python.exe -i C:/Users/anon/.PyCharm40/config/scratches/scratch_5 Traceback (most recent call last): File "C:/Users/anon/.PyCharm40/config/scratches/scratch_5", line 11, in <module> print(parent_1 == parent_2) RuntimeError: maximum recursion depth exceeded in comparison ``` How can I check two dictionaries with circular references for equality?
2015/07/14
[ "https://Stackoverflow.com/questions/31415844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2859614/" ]
You need to write your own comparison procedure that takes four arguments, two things to compare, and two stacks of dictionaries/lists (one for each thing being compared). If either thing being compared is contained in the corresponding stack, return true if they are both in their own stack in the same position, and false otherwise. Otherwise, if they are dictionaries, make sure that they have the same sets of keys (otherwise return false), and recurse on each value, adding the dictionaries to the two stacks. If they are lists, make sure they are the same length (or return false) and recurse on each pair of members, adding the lists to the two stacks. To get things started, call the recursive procedure with the things being compared and two empty stacks. You can wrap this in another procedure that only takes two arguments. ``` def my_compare(a, b): return my_compare_helper(a, b, [], []) def my_index(thing, stack): for i in range(len(stack)): if thing is stack[i]: return i return -1 def my_compare_helper(a, b, a_stack, b_stack): a_loc = my_index(a, a_stack) b_loc = my_index(b, b_stack) if a_loc != -1 or b_loc != -1: return a_loc == b_loc a_stack = [a] + a_stack b_stack = [b] + b_stack if isinstance(a, list): if not isinstance(b, list) or len(a) != len(b): return False for a_thing, b_thing in zip(a, b): if not my_compare_helper(a_thing, b_thing, a_stack, b_stack): return False return True if isinstance(a, dict): if not isinstance(b, dict): return False a_keys = sorted(a.keys()) b_keys = sorted(b.keys()) if a_keys != b_keys: # Keys can't be recursive. return False for key in a_keys: if not my_compare_helper(a[key], b[key], a_stack, b_stack): return False return True return a == b ``` Sample usage: ``` >>> a = [1, 2, {}] >>> a[1] = a >>> a[2]['x'] = a >>> b = [1, 2, {}] >>> b[1] = b >>> b[2]['x'] = b >>> my_compare(a, b) True >>> ```
``` import copy child = {'name': 'child'} parent_1 = {'name': 'parent', 'child': child} child['parent'] = parent_1 # Create the circular reference parent_2 = copy.copy(parent_1) print(parent_1 == parent_2) ``` If you use `copy.copy` instead of `copy.deepcopy`, it runs without an error. > > The difference between shallow and deep copying is only relevant for > compound objects (objects that contain other objects, like lists or > class instances): > > > • A shallow copy constructs a new compound object and then (to the > extent possible) inserts references into it to the objects found in > the original. > > > • A deep copy constructs a new compound object and then, recursively, > inserts copies into it of the objects found in the original. > > > <https://docs.python.org/2/library/copy.html> It is maybe a storage issue, that using deepcopy() forces actual recursion, whereas copy() can just check the references
12,529,489
I created a new project and working with eclipse (used `eclipsify` command). basically, I moved the `app` directory from an old project to the new one I created. the problem is that eclipse doesn't recognize the views. I get errors like: > > views.html.viewTopic cannot be resolved to a type > > > I tried to `play compile` but it didn't help. so I got 40 errors. all of them connected to the fact that the views aren't compiled and therefore, the eclipse doesn't recognize them (my guess of course). **what can I do?** by the way, the old project compiled and ran without a problem (I used intellij)
2012/09/21
[ "https://Stackoverflow.com/questions/12529489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000971/" ]
According to jetbrains, the issue with templates is fixed. If you have play 2 generated source sources included in the IDEA project then you should exclude this folder from the project <http://www.jetbrains.com/idea/webhelp/configuring-folders-within-a-content-root.html> and do File | Invalidate caches and restart. If you have an SBT project, open it in IDEA via File | Import Project | Sbt type project Make sure to use the latest Scala and Play 2 plugins.
OK, I solved it. * I created a new app again * moved `app` dir * **only then** ran the command `play idea`
1,910,881
What is the height of a regular PDF page in pixels? I heard it was something like this: ``` Dim pgSize As New iTextSharp.text.Rectangle(595, 792) ``` but I am adding an image that takes up maybe half the height, and even though pgSize looks like a full page and the image takes up only half of it, I am getting a height of like 619 for the image? I do not know if it is in the same units?
2009/12/15
[ "https://Stackoverflow.com/questions/1910881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117700/" ]
Your page size depends on what you set it when you create the document, probably using the PageSize object (eg. PageSize.LETTER). Once you've established that, most elements in iTextSharp use points and 1 in = 2.54 cm = 72 points. So if you used a standard letter page (8.5x11) it would be 612 by 792. I'm not sure I understand your second question about the image, but I believe that all the units in iTextSharp are points.
``` Dim xDoc as new Document(PageSize.A4) ```
57,434,481
I am quite new to SQL. I couldn't find solution and I want your expertise here. I have one table "boxes" and contains the color and type and condition. I want to get the number of types per color WHERE Condition = 'NEW'. Thanks in advance :) My tale looks like that: ``` Boxes COLOR TYPE CONDITION red x NEW green y NEW green x NEW blue c OLD red b OLD red a OLD ``` I want to put the data from here into another table called "ColorPerType" expected output: ``` ColorPerType Color NumberOfTypes red 1 green 2 blue 0 ```
2019/08/09
[ "https://Stackoverflow.com/questions/57434481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7272307/" ]
You need a [`SELECT...INTO`](https://learn.microsoft.com/en-us/sql/t-sql/queries/select-into-clause-transact-sql?view=sql-server-2017) statement if `ColorPerType` does not exist: ``` select color, sum(case when condition = 'new' then 1 else 0 end) as NumberOfTypes into ColorPerType from boxes group by color ``` See the [demo](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=d088dfde18480aebc5f8ce127c7cd520). If the table `ColorPerType` already exists use this: ``` insert into ColorPerType (color, NumberOfTypes) select color, sum(case when condition = 'new' then 1 else 0 end) as NumberOfTypes from boxes group by color ``` See the [demo](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=8c1af138306d136f7c51cbae1403d8f4). Results: `ColorPerType` table ``` > color | NumberOfTypes > :---- | ------------: > blue | 0 > green | 2 > red | 1 ```
That depends, when you say you need a new table, do you want this table to update when new data goes in the original table? If so, you need a view not a table. `CREATE VIEW ColourPerType AS SELECT b.Color, COUNT(b.Type) FROM Boxes b WHERE b.Condition = 'NEW' GROUP BY b.Color`
64,036,650
This C# code is tested as working, but looks inefficient to me. How can I avoid all of the overhead in each `foreach` interation for say a 1,000 rows? ``` SqlConnection con = new SqlConnection(strConn); // strConn is set elsewhere in the code string strSQL = "select pkCustomer from Customer where YearEndDeactivateInd = 1"; SqlDataAdapter adap = new SqlDataAdapter(strSQL, con); DataTable dt = new DataTable(); con.Open(); adap.Fill(dt); foreach (DataRow row in dt.Rows) { string strSQL1 = "update Ticket set activeInd = 0 where fkCustomer = " + row["pkCustomer"].ToString(); SqlDataAdapter adap1 = new SqlDataAdapter(strSQL1, con); DataTable dt1 = new DataTable(); adap1.Fill(dt1); } con.Close(); ``` I am updating one table based on the results of another. Should I pursue using batch update instead?
2020/09/23
[ "https://Stackoverflow.com/questions/64036650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4056146/" ]
`size_t` is an unsigned integral. This means that `i` can never be negative. When `i` is equal to `0`, and you subtract `1`, it will become a very large number, not `-1`. The condition `i >=0` basically says keep running this loop until `i` is less than zero. Because of the type of `i`, this condition is never met. This is something your compiler could probably point out to you. I'm not sure which compiler you are using. But for example, if you are using gcc, you can add the flag `-Wsign-compare``-Wtype-limits`. Edit: Changed to proper gcc flag. Credits go to @Deduplicator
Many compilers will warn you if a comparison is always trivially true (or false). In this case, an unsigned type like `size_t` can never hold a sub-zero value. Of course, you must profess interest in getting warned, paying heed is optional. For demonstration purposes, see [the following program compiled on coliru using gcc and clang](//coliru.stacked-crooked.com/a/28a66772eb6e3135) ``` int main() { for (unsigned i = 10; i >= 0; i--) /**/; } ``` If you want to work on that whole range, and stay with the single unsigned loop-variable, rearranging a bit gets it done: ``` for (size_t i = 11; i-->0; ) /**/; ``` Of course, `i-->0` can be simplified to `i--`, but then I couldn't link "*[What is the "-->" operator in C++?](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c)*".
2,166,690
PostgreSQL has a useful function called `GREATEST`. It returns the largest value of those passed to it as documented [here](http://www.postgresql.org/docs/8.4/interactive/functions-conditional.html). Is there any equivalent in SQLite? *As a note, I only need it to work with 2 arguments.*
2010/01/30
[ "https://Stackoverflow.com/questions/2166690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37181/" ]
`SELECT MAX(1,2,..)` ref: <https://sqlite.org/lang_corefunc.html#maxoreunc> > > **`max(X,Y,...)`** > > > The multi-argument max() function returns the argument with the maximum value, or return NULL if any argument is NULL. The multi-argument max() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to max() define a collating function, then the BINARY collating function is used. Note that max() is a simple function when it has 2 or more arguments but operates as an aggregate function if given only a single argument. > > >
using a second value in `MAX(value1, value2)` would be the equivalent Example: ``` UPDATE products SET Quantity = MAX(Quantity - @value, 0)... ``` if (`Quantity - value`) return a **"Negative Number `-0`"** then **`Max( , 0)`** will return **0** because 0 is bigger than -0 / -1 / -2 ... and so on **`Max( , 1)`** will return **1** if the same condition (`Quantity - value`) return **0** or a Negative Number .. etc, you get the idea ! > > if we assume that both `Quantity` and `@value` could be **NULL** then use the combination: `IFNULL(MAX(Quantity-@value,0),0)` > > `IFNULL(..., 0)` will return the second value of your choice **IF** the first one is **NULL** > > >
52,113,568
I've the following Dataframe: ``` a b c d e 0 NaN 2.0 NaN 4.0 5.0 1 NaN 2.0 3.0 NaN 5.0 2 1.0 NaN 3.0 4.0 NaN 3 1.0 2.0 NaN 4.0 NaN 4 NaN 2.0 NaN 4.0 5.0 ``` What I try to to is to generate a new Dataframe without the NaN values. There are always the same number of NaN Values in a row. The final Dataframe should look like this: ``` x y z 0 2 4 5 1 2 3 5 2 1 3 4 3 1 2 4 4 2 4 5 ``` Does someone know an easy way to do this? Any help is appreciated.
2018/08/31
[ "https://Stackoverflow.com/questions/52113568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10205233/" ]
Using array indexing: ``` pd.DataFrame(df.values[df.notnull().values].reshape(df.shape[0],3), columns=list('xyz'),dtype=int) x y z 0 2 4 5 1 2 3 5 2 1 3 4 3 1 2 4 4 2 4 5 ``` --- If the `dataframe` has more inconsistance values across rows like 1st row with 4 values and from 2nd row if it has 3 values, Then this will do: ``` a b c d e g 0 NaN 2.0 NaN 4.0 5.0 6.0 1 NaN 2.0 3.0 NaN 5.0 NaN 2 1.0 NaN 3.0 4.0 NaN NaN 3 1.0 2.0 NaN 4.0 NaN NaN 4 NaN 2.0 NaN 4.0 5.0 NaN pd.DataFrame(df.apply(lambda x: x.values[x.notnull()],axis=1).tolist()) 0 1 2 3 0 2.0 4.0 5.0 6.0 1 2.0 3.0 5.0 NaN 2 1.0 3.0 4.0 NaN 3 1.0 2.0 4.0 NaN 4 2.0 4.0 5.0 NaN ``` Here we cannot remove `NaN's` in last column.
You can use panda's method for dataframe [`df.fillna()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html?highlight=fillna#pandas.DataFrame.fillna) This method is used for converting the NaN or NA to your given parameter. > > df.fillna(param to replace Nan) > > > ``` import numpy as np import pandas as pd data = { 'A':[np.nan, 2.0, np.nan, 4.0, 5.0], 'B':[np.nan, 2.0, 3.0, np.nan, 5.0], 'C':[1.0 , np.nan, 3.0, 4.0, np.nan], 'D':[1.0 , 2.0, np.nan, 4.0, np.nan,], 'E':[np.nan, 2.0, np.nan, 4.0, 5.0] } df = pd.DataFrame(data) print(df) A B C D E 0 NaN NaN 1.0 1.0 NaN 1 2.0 2.0 NaN 2.0 2.0 2 NaN 3.0 3.0 NaN NaN 3 4.0 NaN 4.0 4.0 4.0 4 5.0 5.0 NaN NaN 5.0 df = df.fillna(0) # Applying the method with parameter 0 print(df) A B C D E 0 0.0 0.0 1.0 1.0 0.0 1 2.0 2.0 0.0 2.0 2.0 2 0.0 3.0 3.0 0.0 0.0 3 4.0 0.0 4.0 4.0 4.0 4 5.0 5.0 0.0 0.0 5.0 ``` If you want to apply this method to the particular column, the syntax would be like this > > df[column\_name] = df[column\_name].fillna(param) > > > ``` df['A'] = df['A'].fillna(0) print(df) A B C D E 0 0.0 NaN 1.0 1.0 NaN 1 2.0 2.0 NaN 2.0 2.0 2 0.0 3.0 3.0 NaN NaN 3 4.0 NaN 4.0 4.0 4.0 4 5.0 5.0 NaN NaN 5.0 ``` You can also use Python's `replace()` method to replace `np.nan` ``` df = df.replace(np.nan,0) print(df) A B C D E 0 0.0 0.0 1.0 1.0 0.0 1 2.0 2.0 0.0 2.0 2.0 2 0.0 3.0 3.0 0.0 0.0 3 4.0 0.0 4.0 4.0 4.0 4 5.0 5.0 0.0 0.0 5.0 df['A'] = df['A'].replace() # Replacing only column A print(df) A B C D E 0 0.0 NaN 1.0 1.0 NaN 1 2.0 2.0 NaN 2.0 2.0 2 0.0 3.0 3.0 NaN NaN 3 4.0 NaN 4.0 4.0 4.0 4 5.0 5.0 NaN NaN 5.0 ```
6,983,170
I'm aware users may turn support for Javascript on/off in their browsers. But, does anyone know if some corporations have the practice of locking down systems such that the user no longer has the ability to turn Javascript on/off? I'm considering building an enterprise web application that depends on Javascript scripting on the client side browser. Let's assume for the sake of discussion all users of this application are fine with enabling Javascript in their browsers as long as they are able to. Just wondering if I might possibly encounter situations where the user is not permitted to turn his/her browser's Javascript support on/off. If so, I wonder what other options are available to crunch numbers in the client's browser (and then the same question would apply).
2011/08/08
[ "https://Stackoverflow.com/questions/6983170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431080/" ]
My understanding is that some companies use a proxy which actually removes javascript from the HTML for the page. That means that even if javascript is on, it won't be executed, because the browser never sees it. The safe bet is to presume that JS may not be available, and code expecting that.
I think the vast majority desktop users in a company will have access to Javascript (or at least the option to enable/disable it). I can't think of a reason why this would not be the case. However it might be disabled on remote servers which are used by a large number of users for the sake of security. Some of these machines are either very old or run very old software. So for example if one of them was running IE6, the administrator for that particular server might disable Javascript completely to prevent any malicious attacks. In these cases, the machines are meant to be used for web browsing.
57,316,618
I want to enable Authentication/Authorization on a web app for all pages but one. I have a metadata page that I want to remain public while the rest of the app requires authentication. Based on many other [stackoverflow](https://stackoverflow.com/questions/55920079/allowing-public-access-to-only-1-endpoint-of-azure-application/57313377#57313377) [posts](https://stackoverflow.com/questions/48712457/is-it-possible-to-disable-aad-auth-on-specific-azure-functions?rq=1) and [blogs](https://blogs.msdn.microsoft.com/jpsanders/2017/02/06/azure-traffic-manager-probe-degraded-due-to-401-from-azure-web-app/), I have enabled Authentication/Authorization on the app and set 'Action to take when request is not authenticated' to 'Allow Anonymous requests (no action).' I created an authorization.json file and put it in the site root: ``` { "routes": [{ "path_prefix": "/", "policies": { "unauthenticated_action": "RedirectToLoginPage" } },{ "path_prefix": "/metadata", "policies": { "unauthenticated_action": "AllowAnonymous" } }] } ``` I expected that with this setup, unauthenticated requests to the base site and all pages except `/metadata` would require login. However, I am not redirected to login from any page. I have ensured I am logged out of Azure and using a private session, but I can still get right in. As an experiment, I changed the authentication setting to redirect unauthenticated requests to AD login, and all pages redirected to login, as expected, but this does break other functionality since the `/metadata` page is protected.
2019/08/01
[ "https://Stackoverflow.com/questions/57316618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11870335/" ]
As the [posts](https://stackoverflow.com/questions/55920079/allowing-public-access-to-only-1-endpoint-of-azure-application/57313377#57313377) you provided, set `authorization.json` under `wwwroot` and set webapp `Action to take when request is not authenticated` as `Allow Anonymous requests (no action)` then **restart webapp** will work fine. **Note: Remember to restart your app service to make changes effective.**
I'm not sure why, but EasyAuth just would not work with my app. I tried rearranging file and URL structures, placing authorization.json at different places in the file tree... nothing worked. I eventually started looking for other solutions. What I landed on was OpenID Connect v2 using the Microsoft Identity platform. Repo and tutorials [here](https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/1-WebApp-OIDC/1-1-MyOrg). Using this, you can decorate classes or methods with `Authorize` or `AllowAnonymous` attributes to define authorization behavior. It was certainly more effort (and banging head against wall) to get this working, but it is working, so that's cool. I also believe this setup will allow me to apply role-based restrictions, which is ideal.
67,462
If I'm using an image of [Pocahontas](https://en.wikipedia.org/wiki/Pocahontas) for commercial purposes, how do I go about figuring out what license I need to purchase? She is a historic figure, but with much fictional rendering. I could use her historic image or a fictional render. How does that work?
2016/02/23
[ "https://graphicdesign.stackexchange.com/questions/67462", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/61126/" ]
1. Pick your Pantone colours. *It's important to pick these in a light that you will view them in typically. If your designs will be viewed outside, see what they look like in daylight (if you can, at different times of the day as the light will change and time permitting on a cloudy / sunny / rainy day).* 2. Once you have picked your Pantone, then you should the be able to make your CMYK match too. 3. Now you pick your RGB. Remember that so far we have picked colours that your eye see with reflected light and RGB is projected light ([see this for more info](https://graphicdesign.stackexchange.com/questions/60/what-is-the-difference-between-cmyk-and-rgb-are-there-other-color-spaces-i-shou)). Don't try to get an exact match, remember different monitors have different contrast and lightness settings, so these can effect your colours quite a lot. Pick you colour that work well over multiple monitors (and if possible check it on a TV as well, I recommend this as you never know when your logo will appear on a TV or projector at an event).
I don't think it matters which order you pick your colors in since they're all used differently. The point of Pantone is that you get the exact color you pick every time it's printed anywhere. CMYK can vary from printer to printer and RGB can vary from display to display. Also, you can't just pick a Pantone color in Illustrator/Photoshop, then change the color system to CMYK/RGB to get those values and think it will be equivalent. The conversion color values will vary depending on your color profile. It's an ok way to start, but you'll have to test and probably tweak them to make sure they work for your artwork.
55,721,841
i am using this function to generate random number between 1000 and 100. but here according to me, in (max - min) + min, max- min =900 and min= 100, so it should not generate numbers between 900 and 100? but it is returning numbers greater than 900 also how? I am confused. and do tell how to check the range for the numbers random function is generating? any help with this? ``` x = Math.floor(Math.random() * (1000 - 100) + 100); console.log(x); ```
2019/04/17
[ "https://Stackoverflow.com/questions/55721841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9711911/" ]
The function Math.random() returns a number between 0 and 1. When use "Math.random() \* (1000 - 100)", this part of the code generates a number between 0 and 1 then multiplies it by 900, which will give you a number between 0 and 900. Now in the last block you do add 100 to the previously generated number which results in a number between 0 and 900 + 100, which gives a result between 100 and 1000.
**Multiply by (1000 -200) instead as you already have +100** Because in case random number generated is anything greater than `800` you end exceeding range as you're adding `100` in it everytime ```js x = Math.floor(Math.random() * (1000 - 200) + 100); console.log(x); ``` **Thumb rule :-** ``` Math.floor(Math.random() * - ( max - ( 2 * min ) ) + min ) ```
13,359,710
I've been working with `libgdx` for 2 days, and I'm starting to get the hang of it. I'm comfortable with deployment on Android and desktop, but I've got no clue about how to run/debug or deploy the `HTML5` version. When I run as web application, the link gives me an `http error 404`. I did what they say on the libgdx wiki, but that ain't working, so, help would be welcome. BTW, the app's working fine on Android and desktop.
2012/11/13
[ "https://Stackoverflow.com/questions/13359710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1781393/" ]
I ran into this problem for over an hour before realizing that when I selected "run as web application" and eclipse asked me to point to the war directory, I was silly enough to have been selecting the root directory of the project. Once I went back and pointed to the actual war folder, it ran without issue. Silly I know, but might not be a bad idea to check, esp if anyone is setting this up at 1 am like I am lol.
It's a bit difficult to deploy the app correctly. In the wiki of Libgdx (in google code) you can find in one of the first entries how to deploy and debug the app. The easiest way is to install and configure a Tomcat server, do the steps of the wiki and that's all. If you don't want deploy the app, only test it, you can do it directly from eclipse with the embedded server jetty included on the GWT Sdk. Hope this helps you.
36,502,439
I have a bit of a unique problem to solve and I'm stuck. I need to design a program that does the following: 1. Inputs two series of numbers (integers) from the user. 2. Creates two lists based on each series. 3. The length of each list must be determined by the value of the first digit of each series. 4. The rest of the digits of each series of numbers becomes the contents of the list. Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
2016/04/08
[ "https://Stackoverflow.com/questions/36502439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5597574/" ]
For those have issues with error message: Learn to configure HTTP settings, below is the solution that worked for me. Am using Android studio 2.3.3: Go to <http://developer.android.com/studio/intro/studio-config.html> Step 1: Follow the instructions on: Set up Android studio proxy. Step 2: Follow the instructions on : Android plugin for gradle HTTP proxy setting. You will see proxy settings under : # project wide gradle settings, copy the code there and paste it into the empty space in gradle properties file which is under the build gradle in Android studio. Make sure you are connected to internet while on this process. Wait until the the error disappears. Step 3: you may see another message pop up stating: some folders may have been missing syn now. Just click on syn now. I hope this help, thanks all.
I faced the same issue. Make sure that you have made an entry in path in environment variable for gradle ``` C:\Program Files\Android\Android Studio\gradle\gradle-3.2\bin ``` After disable offline mode and setting the path in environment variables, the issue was fixed and Gradle was build cleanly.
465,586
> > **Possible Duplicate:** > > [Hundreds of failed ssh logins](https://serverfault.com/questions/17870/hundreds-of-failed-ssh-logins) > > > Recently I have been spending more time on my production servers in efforts to puppetize several configs and I happened to issue a `find /var/log -mmin1` and it returned the `/var/log/secure` file (among others). Being curious as to recent activity being logged to this specific file, I started tailing it and several of these entries were being logged: ``` Jan 9 22:15:59 myhost sshd[22916]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=58.213.48.82 user=apache Jan 9 22:16:01 myhost sshd[22916]: Failed password for apache from 58.213.48.82 port 36464 ssh2 Jan 9 22:16:01 myhost sshd[22917]: Received disconnect from 58.213.48.82: 11: Bye Bye Jan 9 22:16:03 myhost unix_chkpwd[22922]: password check failed for user (apache) Jan 9 22:16:03 myhost sshd[22919]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=58.213.48.82 user=apache Jan 9 22:16:04 myhost sshd[22919]: Failed password for apache from 58.213.48.82 port 37392 ssh2 Jan 9 22:16:05 myhost sshd[22920]: Received disconnect from 58.213.48.82: 11: Bye Bye Jan 9 22:16:06 myhost unix_chkpwd[22925]: password check failed for user (apache) Jan 9 22:16:06 myhost sshd[22923]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=58.213.48.82 user=apache Jan 9 22:16:08 myhost sshd[22923]: Failed password for apache from 58.213.48.82 port 38244 ssh2 Jan 9 22:16:08 myhost sshd[22924]: Received disconnect from 58.213.48.82: 11: Bye Bye ``` Not too friendly looking, but I did notice that the requests were coming from the save IP address destined for varying local ports. So I did a `whois 58.213.48.82`, and it returned this: ``` [Querying whois.apnic.net] [whois.apnic.net] % [whois.apnic.net node-4] % Whois data copyright terms http://www.apnic.net/db/dbcopyright.html inetnum: 58.208.0.0 - 58.223.255.255 netname: CHINANET-JS descr: CHINANET jiangsu province network descr: China Telecom descr: A12,Xin-Jie-Kou-Wai Street descr: Beijing 100088 country: CN admin-c: CH93-AP tech-c: CJ186-AP mnt-by: APNIC-HM mnt-lower: MAINT-CHINANET-JS mnt-routes: MAINT-CHINANET-JS .... ``` This, again doesn't look friendly. So is this what a potential attack looks like? And how should I handle it? Setup an entry in IPTables to block any requests from the given IP?
2013/01/09
[ "https://serverfault.com/questions/465586", "https://serverfault.com", "https://serverfault.com/users/87836/" ]
The strongest reason to not go with a single domain (and forest) is if you absolutely have to have separate admins in each forest. That's the security boundary. If the same folks are going to have the full set of keys, then make it easy on them. To be clear, I'm not talking about delegation for certain tasks - this is the group of people who are going to be enterprise admins. This doesn't change my recommendations much, because you can delegate things out as needed, as I said above. If part of the org has local admins that need to be able to edit the GPO that is assigned to their OU, you can give that to them, as an example. However, if they need total control over their part of the domain, to the point that they need to be able to lock you out of it, then you need separate forests, and might have a tough time sharing exchange. So, since you're sharing "security and exchange", it sounds like a single domain is still the right way to go.
Personally, if this is a centralisation project, I would use one domain and use OUs to separate things. This saves having to have full redundancy for each child domain, makes roaming and movement easier and cuts down massively on configuration and complexity. There are almost no downsides if you configure sites and services properly.
27,777,759
Unable to convert a JPEG image into a 300 DPI PNG image using ImageMagick. After conversion the PNG image is 72 DPI only. I'm using ImageMagick 6.9.0-0 Q16 x86 and Ghostscript v9.15. Below is the line I use in my Perl script: ``` system("\"$imagemagick\" -set units PixelsPerInch -density 300 \"$jpg\" \"$png\""); ```
2015/01/05
[ "https://Stackoverflow.com/questions/27777759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099825/" ]
Adjusting the units & density will not alter the underlining image data, but updates meta info for rendering libraries. Important for vector to raster, but not very useful for raster to raster. To adjust the DPI of an image, use the [-resample](http://www.imagemagick.org/script/command-line-options.php#resample) operation. ``` convert source.jpg -resample 300 out.png ``` You verify the DPI resolution with the following... ``` identify -format "%[resolution.x] %[resolution.y]\n" out.png ```
I'm wondering where the 72dpi is coming from. Assuming you are using X and some kind of Unix, ImageMagick defaults to using the screen resolution (72 dpi). I'm not sure what it does under OSX/XQuartz but it's likely similar. Is your screen resolution set to 72dpi (!?). I'm with @emcconville @ikegami - just do this straight from ImageMagick on the commandline - passing the right options to be sure. There are image manipulation modules that you can use from perl without having to resort to system commands as well such as [`Imager::Transformations`](https://metacpan.org/pod/Imager::Transformations), [`Image::Magick`](https://metacpan.org/pod/Image::Magick), and [`GD`](https://metacpan.org/pod/GD). Here's how to convert with `GD`. ``` perl -MGD -E 'my $imgjpg = GD::Image->newFromJpeg("img.jpg"); open my $imgpng, ">", "img.png" or die; print $imgpng $imgjpg->png();' ``` With most image manipulation packages the original resolution show be maintained during conversion - though some (including `GD`) will default to lower color depths (8 bit) unless passed a Truecolor flag. *e.g.* `GD::Image->newFromJpeg("img.jpg", 1);`
12,026
<http://blog.ine.com/2008/07/14/private-vlans-revisited/> Has anyone tried private vlan's under Linux? Any experiences with them? My real question is does anybody have howtos regarding this?
2011/04/26
[ "https://unix.stackexchange.com/questions/12026", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/6960/" ]
I don't know if Linux supports Cisco's concept of "private VLANs" per se, but what private VLANs essentially are is a link-layer firewall controlling which switch ports can talk to which other switch ports. So if you've got a Linux box with several Ethernet devices and are bridging between them (e.g. with the `brctl` tool), I think the tool you want is called `ebtables`. If you're familiar with `iptables`, it shouldn't be too hard to pick up from the man page. Note, though, that [describing all of the private VLAN concepts at once using `ebtables` might be complicated](https://lists.linux-foundation.org/pipermail/bridge/2009-June/006542.html). And if you want to share PVLAN groupings with a Cisco switch (assuming that's possible), I'm guessing this isn't the way to go about it.
I don't know what you mean by "private" VLAN's, but Linux does VLANs. The `ip` command from iproute2 can configure them. You do have to have a NIC and driver that supports it, but most do these days.
6,907,074
must create a rule that captures the first preg\_replace bar url: `http://localhost/item/other` must take the rule just 'item' regardless of what comes after
2011/08/02
[ "https://Stackoverflow.com/questions/6907074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769082/" ]
You should use the php [parse\_url()](http://php.net/manual/en/function.parse-url.php) function An example would be: ``` $parts = parse_url("http://localhost/item/other"); $path_parts= explode('/', $parts[path]); $item = $path_parts[1]; echo $item; ```
It does not look like you have a specific question. I am assuming you are about write some routes script. ``` $request_uri = explode('/', $_SERVER['REQUEST_URI']); $delimiter = array_shift($request_uri); $controller = array_shift($request_uri); $action = array_shift($request_uri); if(preg_match('/item/i', $controller)) { // do something right } else { // do something wrong } ```
22,718,922
I was watching the [presentation](http://www.youtube.com/watch?v=3q8xYFDYLeI) : " Why Do Monads Matter? " I simplified one code [example](https://github.com/londonhaskell/londonhaskell-2012-10-24-why-do-monads-matter/blob/master/Pref.hs) which compiles and runs (please see below) but I still don't understand how it works. More precisely: I don't understand the composePref function. According to the type definition it should take **2** parameters of Ize type and return one result of Ize type. (Ize means "whatdoyoucallit"/thingy/something in Hungarian.) But it takes **three** parameters (f g x), could someone please explain how the composePref function works and what are the types of f, g, x, y and c ? I have to admit that I am very beginner in Haskell. Maybe I don't understand how currying works in this case ? ``` module Dependence where main = putStrLn (f "foo" cfg) where f = right `composePref` right `composePref` left cfg = 2 left :: Ize left s = \i -> (repeatString i "< ") ++ s right ::Ize right s = \i -> s ++ (repeatString i " >") repeatString :: Integer -> String -> String repeatString i s = if (i <= 0) then "" else s ++ repeatString (i - 1) s type Ize = String -> Integer -> String composePref :: Ize -> Ize -> Ize composePref f g x = \c -> let y = (g x) c in (f y) c ``` Produces output: ``` < < foo > > > > ```
2014/03/28
[ "https://Stackoverflow.com/questions/22718922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1198559/" ]
If you expand the type of the last `Ize` in your function you get: ``` composePref :: Ize -> Ize -> (String -> Integer -> String) composePref f g x = \c -> let y = (g x) c in (f y) c ``` which is the same as ``` composePref :: Ize -> Ize -> String -> Integer -> String ``` which is also the same as: ``` composePref :: Ize -> Ize -> String -> (Integer -> String) ``` which matches your definition of `composePref` more closely. Now `f` and `g` are both `Ize` while `x` is a String and `c` is an `Integer`
You could use the following alternative definition, if this makes things clearer ``` composePref :: Ize -> Ize -> Ize composePref f g = \x -> \c -> let y = (g x) c in (f y) c ```
37,068,834
I am posting JSON Array to a webservice but i am unable to solve it. In the below code "str" is the JSONArray converted to string. JSONArray consists of JSONObjects and each JSONObject consists of 3 paramaters (ID,Question,Answer). ``` ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("feedbackjson", str)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://172.16.10.64:8080/plugleadservices/rest/feedbackmanagement/feedbacknew"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpParams httpParameters = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); //is = entity.getContent(); result = EntityUtils.toString(entity).toString(); } catch (Exception e) { Log.e("Loading Runnable Error in http connection :", e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("Loading Runnable Error converting result :", e.toString()); } JSONObject json_data = new JSONObject(result); System.out.println("#### Status Message : " +json_data.getString("statusMessage").toString()); System.out.println("#### Company ID : " +json_data.getInt("company_id")); ``` this is the error what i am getting ``` 05-06 14:50:48.459: W/System.err(8368): org.json.JSONException: End of input at character 0 of 05-06 14:50:48.459: W/System.err(8368): at org.json.JSONTokener.syntaxError(JSONTokener.java:450) 05-06 14:50:48.459: W/System.err(8368): at org.json.JSONTokener.nextValue(JSONTokener.java:97) 05-06 14:50:48.459: W/System.err(8368): at org.json.JSONObject.<init>(JSONObject.java:156) 05-06 14:50:48.459: W/System.err(8368): at org.json.JSONObject.<init>(JSONObject.java:173) 05-06 14:50:48.459: W/System.err(8368): at com.plugleads.feedback.FeedBackQuestionsActivity.callWebservice(FeedBackQuestionsActivity.java:712) 05-06 14:50:48.459: W/System.err(8368): at com.plugleads.feedback.FeedBackQuestionsActivity.checkBoxes(FeedBackQuestionsActivity.java:371) 05-06 14:50:48.459: W/System.err(8368): at com.plugleads.feedback.FeedBackQuestionsActivity.isValidData(FeedBackQuestionsActivity.java:350) 05-06 14:50:48.459: W/System.err(8368): at com.plugleads.feedback.FeedBackQuestionsActivity$1.onClick(FeedBackQuestionsActivity.java:166) 05-06 14:50:48.459: W/System.err(8368): at android.view.View.performClick(View.java:4785) 05-06 14:50:48.459: W/System.err(8368): at android.view.View$PerformClick.run(View.java:19884) 05-06 14:50:48.460: W/System.err(8368): at android.os.Handler.handleCallback(Handler.java:739) 05-06 14:50:48.460: W/System.err(8368): at android.os.Handler.dispatchMessage(Handler.java:95) 05-06 14:50:48.460: W/System.err(8368): at android.os.Looper.loop(Looper.java:135) 05-06 14:50:48.460: W/System.err(8368): at android.app.ActivityThread.main(ActivityThread.java:5343) 05-06 14:50:48.460: W/System.err(8368): at java.lang.reflect.Method.invoke(Native Method) 05-06 14:50:48.460: W/System.err(8368): at java.lang.reflect.Method.invoke(Method.java:372) 05-06 14:50:48.460: W/System.err(8368): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 05-06 14:50:48.460: W/System.err(8368): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700) ``` I want to pass below JSONArray to Webservice ``` [ { "fk_Company_id":4, "q_Answer":"no", "q_Name":"qwhgdfqw" }, { "fk_Company_id":2, "q_Answer":"yes", "q_Name":"sdfsdf" }, { "fk_Company_id":2, "q_Answer":"yes", "q_Name":"xcvfdgd" }, { "fk_Company_id":2, "q_Answer":"no", "q_Name":"xfgdf" }] ``` Thanks in Advance.
2016/05/06
[ "https://Stackoverflow.com/questions/37068834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416975/" ]
You can simply add the numbers via the constructor of the `new List<int>` ``` var itemsToAddInMetadata = new List<int> { 22, 33, 65 }; userUpdateRequest.AppMetadata = new Dictionary<string, dynamic> { { "toysNumber", new List<int>(itemsToAddInMetadata) { 2, 3, 9, 7 } } }; ```
Try something like that: ``` userUpdateRequest.AppMetadata["toysNumber"].AddRange(new[] {22, 33, 65, ...}) ```
40,797,533
I'm going straight to the point here. I want to create a simple window within an image. outside the window will have a opacity like on the sample picture. I'm not really good when it comes to css so please bear with me. ```css .section2{ } .section2 .row{ margin: 0; } .the-container{ position: relative; width: 100%; height: 450px; } .the-container .text-center{ background: #fff; opacity: .9; } .img-canvas{ position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; width: 100%; height: 100%; background-image: url(https://www.aman.com/sites/default/files/styles/1371x706/public/amanpulo-location-1200-x-825.jpg?itok=4BQy9j-X); background-size: 100% 100%; background-position: 50% 50%; background-attachment: scroll; z-index: -1; } .window{ position:absolute; width:50%; height:50%; background-size: cover; top:0; left:25%; z-index: -1; opacity: 1; } ``` ```html <section class="section2" style="height:100vh;"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="the-container"> <div class="img-canvas"></div> <div class="window"></div> </div> </div> </div> </section> ``` something like this: [![enter image description here](https://i.stack.imgur.com/GOfvZ.png)](https://i.stack.imgur.com/GOfvZ.png) and here's a fiddle for you to manipulate the code: <https://jsfiddle.net/Lk21vL01/> thanks in advance.
2016/11/25
[ "https://Stackoverflow.com/questions/40797533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3113490/" ]
Try to print the array in the console when you get undefined and check your array size in the log. ``` for (var g = 0; g < pastWinners.length; g++) { for (var i = 0, j = pastWinners.length; i < j; i++) { if (obj[pastWinners[g][i]] == undefined){ console.log(`row ${g}, col ${i}`); console.log(obj[pastWinners]); } if (obj[pastWinners[g][i]]) { //this is line 331 obj[pastWinners[g][i]]++; } else { obj[pastWinners[g][i]] = 1; } } } ```
Also you should check for the existence of `pastWinners[g]` before you loop through it or try to access a child array using `if (pastWinners[g] != null) {` The reason for this is that if `pastWinners[g]` for some reason is not defined, then your script will attempt to do this: `undefined[i]` or get the value of [i] from undefined -- which it cant because undefined is not an array -- which breaks your script ```js var pastWinners = [ [2, 9, 19, 23, 38, 40], [17, 25, 31, 35, 38, 43], [8, 10, 17, 30, 33, 43], [10, 17, 26, 28, 36, 43], [14, 20, 25, 28, 34, 41], [8, 13, 21, 23, 25, 43], [10, 11, 18, 24, 27, 30], [21, 22, 23, 26, 33, 39], [6, 21, 23, 29, 36, 40], [10, 12, 16, 21, 25, 42], [1, 11, 20, 27, 34, 37], ]; for (var g = 0; g < pastWinners.length; g++) { if (pastWinners[g] != null) { // check for valid item for (var i = 0, j = pastWinners[g].length; i < j; i++) { if (pastWinners[g][i] != null) { pastWinners[g][i]++; } else { pastWinners[g][i] = 1; } } } } console.log(pastWinners); ```
158,637
Our communication department recently asked us (the security team) a question. They send out a lot of mail, especially mails like 'your password is set to expire' are hot topics here. The question was: Should we write out the links? We have 'domain.com/passwordreset'. Should we add 'www'? Should we add 'https'? Should we just make it a link of text 'Click here'? I checked some email I personally got from banks and noticed that it is usually a string that then contains a link, but those companies do that because they want to track who clicks the links and the links are thus really long. The URLs our communication department is trying to communicate are short URLs that they would love for people to remember outside of the email as well. I looked around, but could not find any practical experience with this online. So my question is: What would be the 'best' option and why?
2017/05/03
[ "https://security.stackexchange.com/questions/158637", "https://security.stackexchange.com", "https://security.stackexchange.com/users/136167/" ]
A policy I've seen used by some banks and government agencies in the Netherlands is never to include any links in mails, but just to refer to "our website" or "our webportal". The main idea here is that they're explicitly telling customers never to click on any links in emails (supposedly) coming from them. This way they hope to reduce the chance of people visiting links mentioned in phishing mails and entering their credentials there. People are always forced to enter the URL of the webpage in their browser (or use bookmarks), which can be a bit of a drawback looking at it from an UX perspective, but it can work as a security measure. Unfortunately, I have no idea how effective this is, and thus if it's a useful strategy.
The most important thing is to make sure that people actually change their passwords, so making it as easy as possible to click on a link and remember it afterwards is important. First, you should definitely make it an https link, you should never point people down an insecure connection to change a password. As for the format of the data there's no particularly right answer, you could just hide the link behind text like "Change Your Password" a la: `<a href="https://www.example.com/passwordreset">Change Your Password</a>` which would look like this: [Change Your Password](https://www.example.com/passwordreset) or you could have a bare link `<a href="https://www.example.com/passwordreset">https://www.example.com/passwordreset</a>` which would look like this: [<https://www.example.com/passwordreset>](https://www.example.com/passwordreset) Most browsers and email programs automatically recognize links whether they are wrapped in html or not, for example I've simply typed <https://www.example.com/passwordreset> in, but most browsers will show a link. Most users do not memorize links to be honest and won't remember your password reset url, some might though, so if that's an important goal putting the bare link in makes sense.
4,317
I'm deleting my academia stackexchange account so I don't really care if this my last question will be marked as duplicate or off-topic. The reason why I'm asking this question is that I feel the academia stackexhange community right now heavily focused on hierarchy of this forum such as preventing duplicate, off-topics, etc. rather than actually answer the people's questions. I think every-time if someone, whom specially is new in this forum, asks a question a lot of experienced people will rush to the newly posted question in order to edit its content and discuss its relevance and find duplicates when it is applicable. I think this rush created a censorship, which does not allow new users to express their questions or ideas. Furthermore, I believe every question, which is asked by unique person, has some originality even if it shares its topic with other similar questions and I think it's not fair to mark every question as duplicate or off-topic because his/her questioner is not an experienced user in this forum. I know, even this my last question will be marked as duplicate, off-topic and will be closed, on hold, or even deleted. But, I'm happy that I just expressed my ideas and I don't really care if even I don't receive any response because my account will be deleted anyway.
2018/09/16
[ "https://academia.meta.stackexchange.com/questions/4317", "https://academia.meta.stackexchange.com", "https://academia.meta.stackexchange.com/users/-1/" ]
The goal of Academia.SE (similar to the other stack exchange sites) is to develop a useful Q&A that *applies to a broader audience than the individuals asking questions*. This is why we close questions that are too specific to a single individual, or mark as duplicates questions that have already been answered. These approaches filter out the messy individual circumstances and *give the best chances for **other people** to find answers here* without having to ask their own question. Closing a question as duplicate is never an attempt to censor a particular question or questioner, it seeks to point you toward information already here. Additionally, we can't really answer "what should I do?" questions: you have to make your own decisions based on what you value. Your advisor is likely to be a better place to get information when you need to make a particular decision, because they know you and your circumstances better (though even then you may disagree).
I'm sorry you feel that way, and thank you for taking the time to post your experience. Looking over your posts, I'm not sure I understand why you feel that way... your [last question](https://academia.stackexchange.com/questions/116888/should-i-withdraw-my-paper-from-a-journal-which-even-didnt-give-me-the-manuscri) (>10k users) was pretty well received and good discussion helped improve the question even more. There is a well-recognized phenomenon of older users rushing to close questions, but try to view it from their side... many new users post without checking history, and in many cases the answer has already been discussed. This site has been around for over six years at this point, we have quite a body of knowledge built up. Sometimes mistakes happen, but overall it tends to work fairly well. That said, as you point out, it's not perfect. I'm sorry you're not feeling welcome, and I really would urge you to reconsider your decision. You've only been a member for a few weeks now, but in that short time you've contributed a few pretty interesting questions. Don't let one bad experience ruin that for you.
49,615,788
I don't know data structure of array in MATLAB. Does it use a FiFo? I try to delete the last element from a column and row vector. The time complexity depends on size **`N`**. How to delete last element in **`O(1)`**? Seminally **`pop()`**.
2018/04/02
[ "https://Stackoverflow.com/questions/49615788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9587261/" ]
**DISCLAIMER: This is not a real suggestion, it is merely a stupid way to actually obtain an O(1) run-time** Right, with the disclaimer given, it is actually possible to make an O(1) pop command in "Matlab". The solution is to not do it in Matlab, but in Python. Confused? Basically, you convert the vector to a Python list with `py.list()`, whereafter the O(1) `pop` command is possible to execute. Thus you can do something like: ``` a = randn(1,1e4); li=py.list(a); b = li.pop; ``` However, as you might have guessed typecasting and running python through Matlab is not exactly what I would call fast. So even though we can maintain a constant run-time that constant is simply too large for it to be of any use. In the figure, blue is the Matlab/Python solution, whereas red(-ish) is the best solution, as given by Tommaso and Cris. [![Timed runs](https://i.stack.imgur.com/7pqVr.png)](https://i.stack.imgur.com/7pqVr.png) As it is clear, we maintain what looks like O(1), but at an cost. Code for reference: ``` num_averages = 100; num_sims = 10000; time_store = nan(num_sims, num_averages); for i = 1:num_averages building_array = rand(1,num_sims); li = py.list(building_array); for j = 1:num_sims tic; li.pop; time_store(j, i) = toc; end end ``` **EDIT:** The size at which this approach is faster than the pure Matlab solution is actually within some reasonable limit ~150000. [![Larger sized array](https://i.stack.imgur.com/Kii1R.png)](https://i.stack.imgur.com/Kii1R.png) Note: The fluctuations in this figure are larger as my patience ran out and thus I reduced the number of averages to 5. Make no mistake, this solution is still stupid and should not be used. The conversion is linear in size, converting back again destroys it even more. Thus the only case, where this solution is actually better is if you are *solely* interested in the popped element, though, in this case, a for-loop with indexing does the same thing a lot faster.
Depends on array length, use `tic <_code_under_test_> toc`, to measure the time ``` A = ones(1,50); B = ones(1,10); tic A(1) = []; toc tic A(49) = []; toc tic B(1) = []; toc tic B(9) = []; toc Elapsed time is 0.000195 seconds. Elapsed time is 0.000085 seconds. Elapsed time is 0.000061 seconds. Elapsed time is 0.000051 seconds. ``` You can see, it's faster to delete the last element of array than the first.
30,095
other Facts: Window(s) size 3.5 feet\* 5 feet (width) Fan (2 nos.) Specifications [Product page - specifications](http://www.ushainternational.com/Products/fans/#!/subcat27/prodid169) Sweep size: 400 MM RPM: 1280 Air Delivery: 75 CMM (What is the formula to convert CMM to CFM?) Volume of the premise : 7200 Cubic Feet High and Low Temperature day cycle (extreme during the year): [Month Wise Temperature Chart for the Location is available here](http://www.accuweather.com/en/in/vadodara/202439/month/202439?monyr=5/01/2013) Summer: 45 Celcius - 29 Celcius (Comfort Target 22 Celcius) Winter: 26 Celcius - 8 Celcius (Comfort Target 26 Celcius) Purpose: To take the advantage of Temperature gradient between external temperature and internal temperature. Use fans during the time period when beneficial and put on Air Conditioner (Cooling and Heating) when compulsorily required to achieve last lag of the temperature target. Note: Premise is a concrete building with no insulation, so its temperature follows the external temperature. (Heats up after external temperature goes higher and cools down after external temperature goes down) (1) How effectively a single pedestal fan (blowing inward) can bring the outside air in the room if blades are 2 feet away from a fully open window (with the distant window of same size at the other end of the house is kept open)? (2) How effectively a pedestal fan (blowing outward) can throw the air from the room out of window if blades are 1 foot away from a fully open window (with the distant window of same size at the other end of the house is kept open)? or (3) How effective will be two pedestal fans (one inward and one outward placed at distant fully open windows of the house) for displacing the indoor air with outside air?
2013/07/28
[ "https://diy.stackexchange.com/questions/30095", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/13661/" ]
While this doesn't directly answer your question, maybe you should consider a true [window fan](http://www.homedepot.com/p/Lasko-8-in-Electrically-Reversible-Twin-Window-Fan-with-Thermostat-2138/203067772#.UfUmtY2KK8A) such as this one ![window fan](https://i.stack.imgur.com/nyCew.jpg) It delivers **740 CFM**, has a thermostat, is not too expensive (less than $50) and will be much more effective in ensuring the flow of outside air into the room. It's also reversible, so it can be used as an exhaust fan as well. If you need more airflow, some models go up to nearly 3000 CFM (over 90 CMM) like [this one](http://www.homedepot.com/p/Lasko-16-in-Electrically-Reversible-Window-Fan-2155A/100405673#.UfU_m42KK8A).
I think CFM is overrated. I use six Lasku U15700 blower style fans I bought from Sam's club several years ago when they were $40 each. They are rated at 438 CFMs when on high and can really move air around my home when I have them set up to draw air in from outside and give that air a place to go outside from inside on the other end of the house. Creating negative pressure as air blows out one end of my home makes air coming in on the other side easy to do so... with or without a fan to assist it. Cheap fans with much higher CFMs does not mean they do a better job at ventilating the air in your house. There's no doubt an Air King 9155 or 9166 will get the job done for you with CFMs between 2400 and 3000 CFMs, but one also has to factor the amount of power they use too, therefore I use timers on all my big appliances and fans and use my power company's Time Advantage rates. That said during the summer does require some careful planning and it boils down to a formula of using 85/15; that is from 8 pm ET to 2 pm ET my power rate is the same as it is in the winter, but from 2 pm to 8 pm ET every weekday I have to use 15% of my total daily power consumption to break even to normal daily summer rates. The whole goal here is reduce my power consumption and thus lower my power bill in the summer.
94,737
In my native language, the stuff is called "aluminium foil". In English, I always heard people use the phrase "tin foil" for that. I adopted that phrase thinking that despite the foil being made of aluminium (and not tin as it used to be) this is what people call it. Recently a native American English speaking person took the phrase literally and wondered why I would want *tin* foil, because aluminium foil is much more common these days... I checked [the wikipedia article on the matter](https://en.wikipedia.org/wiki/Tin_foil) and found this quote: > > Actual tin foil was superseded by cheaper and more durable aluminium foil after World War II. Despite this, **aluminium foil is still referred to as "tin foil" in many regions**. > > > What regions use the term "tin foil" what use "aluminium foil"? Does the majority of English speakers understand "tin foil" as "aluminium foil"? I'd happily adopt the more correct phrase "aluminium foil", but *a-lu-mi-ni-um* is quite a mouth full. Even in my native language it is commonly abbreviated with just "alu". IS there something like that in English? I think the shortness of tin is what kept people using it. **What's the best phrase to refer to aluminium foil?**
2016/06/25
[ "https://ell.stackexchange.com/questions/94737", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/36942/" ]
Several commenters have wondered if the commonality of "tin foil" in the ngrams in other answers is affected by the phrase "tin foil hat" specifically. According to the ngram below, I would say not--as "tin foil hat" is quite a flat line compared to the others. ![](https://books.google.com/ngrams/chart?content=tin+foil%2Caluminum+foil%2Caluminium+foil%2C+tin+foil+hat&year_start=1800&year_end=2008&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Ctin%20foil%3B%2Cc0%3B.t1%3B%2Caluminum%20foil%3B%2Cc0%3B.t1%3B%2Caluminium%20foil%3B%2Cc0%3B.t1%3B%2Ctin%20foil%20hat%3B%2Cc0) Now, whether or not the prevalence in modern-day speaking of "tin foil" is affected by the cultural term "tin foil hat" is another question; one we don't really have documentary evidence to support or disprove. I will say that from my AmE perspective, "tin foil" sounds distinctly British, and personally I say "aluminum foil" about half the time, and simply "foil" the rest of the time. It surprises me to see many AmE speakers weighing in as "tin foil" users. It's not something I hear in my area (north Texas) often. So! Clearly this one is anecdotal, and varies highly among individual respondents (and doesn't even seem to have a high regional correlation). So I would say this: if you prefer "aluminum", and aluminum is technically scientifically correct, and everyone will understand you when you say it... That sounds like a lot of good evidence to go with it :) As long as you understand "tin foil" when you hear it, I don't see any reason to use it yourself if you don't want to.
I've studied dialects and accents in both the US and Ireland. I'm a linguistic Anthropologist. Without being complicated I can say the majority of people in the Northeastern part of the US say either tin foil or aluminum foil interchangebly. People in Ireland say "aluminium" except for younger people in and around affluent parts of Dublin who say "aluminum" foil as they speak something of a presige dialect based on American speech. Most just say "foil." Tin-foil is a simple anachronism and not a dialect word. It's used throughout the English speaking world and easily understood.
9,524,640
Lets say I have the following: ``` class MyClass { // ... } void doSomething (MyClass instance) { // Is instance passed by reference or by value (copied)? } void main () { MyClass instance = MyClass(); doSomething(instance); } ``` In `doSomething()` is `instance` passed by reference? Or is the class duplicated in memory? Or something else?
2012/03/01
[ "https://Stackoverflow.com/questions/9524640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126280/" ]
This is passed by value ``` void doSomething (MyClass instance) ``` This is passed by reference ``` void doSomething (MyClass& instance) ``` This is passed by const reference ``` void doSomething (const MyClass& instance) ``` Also `MyClass` doesn't need to by constructed by assignment. So: ``` MyClass mc=MyClass(); ``` is effectively the same as: ``` MyClass mc; //no parens needed for default constructor (no args). ``` EDIT: This is passed by const reference to a const function, a const function can be called on a const object as it guarantees not to modify the object state. ``` void doSomething (const MyClass& instance) const ``` Const correctness is considered good practice in C++ unlike many less strict languages. see me: <http://en.wikipedia.org/wiki/Const-correctness> <http://www.gotw.ca/gotw/006.htm>
Yes, it is copied. When you call `doSomething`, the `MyClass` copy constructor is called, to create a new instance. This instance will remain in scope for the duration of the `doSomething` function. When the function ends, the `MyClass` destructor will be invoked for this instance. (Note that if you haven't written a copy constructor, one is created for you by default.) So if you add an explicit copy constructor and destructor: ``` class MyClass { public: MyClass() { std::cout << "MyClass constructor" << std::endl; } MyClass(const MyClass& other) { std::cout << "MyClass copy constructor" << std::endl; } MyClass::~MyClass() { std::cout << "MyClass destructor" << std::endl; } } void doSomething (MyClass instance) { std::cout << "doSomething method"; } void main () { MyClass instance = MyClass(); std::cout << "invoking doSomething" << std::endl; doSomething(instance); std::cout << "returned from doSomething" << std::endl; } ``` This will output the following: * MyClass constructor * invoking doSomething * MyClass copy constructor * doSomething method * MyClass destructor * returned from doSomething * MyClass destructor
27,353,122
I have a link like this: <http://domain.com/page.php?product=brown+rice> And then in the page.php page I GET the product: ``` $product = $_GET['product']; <?php echo $product; ?> ``` But it only prints : brown rice without the `+` How to get the + in the get method?
2014/12/08
[ "https://Stackoverflow.com/questions/27353122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4238328/" ]
**Please refer the below url, it is already answerd in stackoverflow,** [PHP - Plus sign with GET query](https://stackoverflow.com/questions/2671840/php-plus-sign-with-get-query) If you'll read the entirety of that bug report you'll see a reference to [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt). Which states that + is **reserved**. PHP is correct in translating an unencoded + sign to a space. You could use urlencode() the ciphertext when returning it to the user. Thus, when the user submits the ciphertext for decryption, you can urldecode() it. PHP will do this automatically for you if it comes in via the GET string as well. **Bottom line:** The + must be submitted to PHP as the encoded value: %2B
Just write <http://example.com/page.php?product=brown%2Brice> **%2B** changes to plus, because **B2** (hex) is a '+' in **ASCII** table
3,928,597
I've run into this issue before, but I can't remember how to solve it. I have created a bare bones (can't get any simpler) controller, and am just trying to echo something to the browser, and I am getting this message: ``` Fatal error: Uncaught exception 'Zend_Session_Exception' with message 'Session must be started before any output has been sent to the browser ... ``` Here's my **entire** controller. It's displaying 'success', but it also displays the error message. How can I silence that error message so I can simply echo something to the browser? ``` <?php class CacheController extends Zend_Controller_Action { public function clearAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); try { $result = Model_Cache::emptyCache(array('foobar'=>1)); if ($result['status'] == true) { echo 'Success'; } else { echo 'Error: ' . $result['message']; } } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } } } ```
2010/10/13
[ "https://Stackoverflow.com/questions/3928597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48523/" ]
What the error sounds like it is saying is that you are not starting the Zend\_Session before data is being sent to the browser. Typically I have something like I pasted below in my bootstrap to start the Zend\_Session. ``` protected function _initSessions() { Zend_Session::start(); } ``` That should get you going in the Zend Framework. If you are using this tool outside the framework just use that inner line of code near the top of your PHP scripts before you echo or print anything. Hope that helps!
Possible the session is started through your application.ini or php.ini (session autostart) ? If you use an ide try to search for "spaces". Sometimes searching for " " (with spaces) helps.
3,595,884
Consider a website build using python and django. In many cases it uses 3rd party modules beside standard python library - such as pytz, South, timezones or debug toolbar. What is standard or just convenient way to deploy such application to production hosting with all the prerequisites (timezones, etc) installed automatically? I'm new to python, and sorry if this question is lame.
2010/08/29
[ "https://Stackoverflow.com/questions/3595884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327827/" ]
Fabric is definitely a nice way to accomplish this. There is a fairly extensive blog write up on the process at <http://www.caktusgroup.com/blog/2010/04/22/basic-django-deployment-with-virtualenv-fabric-pip-and-rsync/>. The key to fabric is "fabfile.py" - there's an example of one that does a deployment at <http://bitbucket.org/copelco/caktus-deployment/src/tip/example-django-project/caktus_website/fabfile.py>. The variation of this that I've used to deploy to a Linode instance is <http://gist.github.com/556508>
There are at least two options available. Jacob Kaplan-Moss, one of the co founders of Django has [written](http://jacobian.org/writing/django-apps-with-buildout/) about packaging an application using [`buildout`](http://buildout.org/) and [`djangorecipe`](http://pypi.python.org/pypi/djangorecipe). There is also the versatile [`fabric`](http://docs.fabfile.org/0.9.1/). You should be able to tackle your problem using either of these alone or in combination with some custom scripts.
2,592,700
How do I prevent SQL injection when it comes to ColdFusion? I'm quite new to the language/framework. Here is my example query. ``` <cfquery name="rsRecord" datasource="DataSource"> SELECT * FROM Table WHERE id = #url.id# </cfquery> ``` I see passing in `url.id` as a risk.
2010/04/07
[ "https://Stackoverflow.com/questions/2592700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23528/" ]
Use a `<cfqueryparam>` tag for your id: <http://www.adobe.com/livedocs/coldfusion/6.1/htmldocs/tags-b20.htm> ``` <cfquery name="rsRecord" datasource="DataSource"> SELECT * FROM Table WHERE id = <cfqueryparam value = "#url.id#" CFSQLType = "CF_SQL_INTEGER"> </cfquery> ```
* use a parameterized stored procedure * cfqueryparam * error handling around individual query * error handling for site via `<cferror>` * logic that limits the number of request that come from a specific IP in a given time * ensure the database user account only has access to the specific actions it should
49,319,383
$ Flutter doctor terminal command not working on ubuntu, giving error message "curl: (35) gnutls\_handshake() failed: Error in the pull function. "
2018/03/16
[ "https://Stackoverflow.com/questions/49319383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039274/" ]
I'm using Ubuntu 18.04 LTS. Assuming you have successfully downloaded and extracted [flutter\_linux\_v0.5.1-beta.tar.xz](https://storage.googleapis.com/flutter_infra/releases/beta/linux/flutter_linux_v0.5.1-beta.tar.xz) (latest update until now) onto your preferred directory. ``` export PATH=`pwd`/flutter/bin:$PATH ``` Running this command in your ubuntu terminal (Ctrl + Alt + T) adds flutter commands PATH variable to your system path for **temporary** session. As soon as you close the terminal, the system path is removed. **In order for ubuntu terminal to remember flutter commands permanently, you need to:** > > 1.) open up terminal and cd to $HOME. for eg: user@linux:~$ > > > 2.) open the hidden file `.bashrc` with your desired editor. It resides in $HOME. > > > 3.) add the following line > `export PATH=/home/yourname/flutter/bin:$PATH` > somewhere as a newline in `.bashrc` file preferably as a last line edit & save file. > > > 4.) run `source /home/yourname/.bashrc` in terminal to process your recent changes. > > > 5.) finally, run `echo $PATH` to see flutter dir is in your system path along with other such paths. for eg: `/home/yourname/flutter/bin` > > > Now close current terminal and reopen new terminal to check `flutter doctor`. It should process along with all other available flutter commands everytime now onwards. Thank you ! :)
This is not Flutter nor "flutter doctor" specific, it's to do with curl. Googling this error seems to bring up results that are either related to; * Virtualbox * Networking * Some combination of the above two
7,434
Its there any API for all Drugs existed if yes can you explain when can I find IT.
2016/03/31
[ "https://opendata.stackexchange.com/questions/7434", "https://opendata.stackexchange.com", "https://opendata.stackexchange.com/users/9516/" ]
One effective currency conversion API for me is [money.js](http://openexchangerates.github.io/money.js/) Features: 165+ Currencies, updated often, infinite free requests. You simply give it the currencies you wish to convert, and off you go! It's really simple & easy to use. For example: ``` fx.convert(1, {from: 'GBP', to: 'EUR'}) ``` Will return 1 pound (GBP) in euros, with immense precision. Right now, it returned `1.254187176646604`. Additionally, that line of code can be made even simpler! ``` fx.settings = { to: "EUR" }; fx.convert(1, {from: "GBP"}); // Using EUR from previously set fx.settings. ```
I created a Free Currency Exchange API, Some of it's features are * Free & Blazing Fast response * No Rate limits * 150+ Currencies, Including Common Cryptocurrencies * It's Daily Updated The API is user friendly, to get the currency list with EUR as base currency use this URL: <https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur.json> More Details for the API is available at <https://github.com/fawazahmed0/currency-api>
30,050,675
I'm an angular beginner and it does not seem to respond to me. I'm trying to to a simple ng-click to add and subtract to a counter. I get his error: ``` Error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=FirstController&p1=not%20a%20function%2C%20got%20undefined... ``` this is index.html: controller.js: ```js var app = angular.module('app', []); app.controller('FirstController', function($scope) { $scope.word = "ever"; $scope.counter = 0; $scope.add = function(amount) { $scope.counter += amount; }; $scope.subtract = function(amount) { $scope.counter -= amount; }; }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!DOCTYPE html> <html ng-app> <head> <title>Simple App</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> </head> <body> <div ng-controller="FirstController"> <h4>The simplest adding machine ever</h4> <button ng-click="add(1)" class="button">Add</button> <a ng-click="subtract(1)" class="button alert">Subtract</a> <h4>Current count: {{ counter }}</h4> </div> <script type="text/javascript" src="js/controller.js"></script> </body> </html> ``` Any help will be appreciated. Thanks
2015/05/05
[ "https://Stackoverflow.com/questions/30050675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048664/" ]
I think you forgot to specify what app you use , try the following code : ``` <html ng-app="app"> ```
``` 1. modify html file Here is solution for your problem.Add following line inside your html code <html ng-app='app'> inside <head> tag add script : <script src="app.js"></script> 2. modify controller.js app.controller('FirstController',function($scope){}); Error occured because you added extra space between "'FirstController'," and "function($scope){})" ```
5,046,691
Can structs have the same name as a class? Am I allowed to pass around structs into functions? Structs are a light-weight class? Basically without the functions. It's a container that holds vars. I'm just wondering if I made a function, can I pass in a struct like normally passing in any other object?
2011/02/18
[ "https://Stackoverflow.com/questions/5046691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438339/" ]
In C++, `struct` and `class` are effectively identical. The only difference is that members of a `struct` are `public` by default, and members of a `class` are `private` by default. You can use them exactly the same way as you use classes. They do need unique names (within the same namespace), so you can't have the struct use the same name as a class.
No. Names are unique identifiers. You can't name an int with the same name as a char, can you? (answer is No) Yes. Structs can have functions and you can pass them to functions, just like any other variable.
146,652
I'd like to make my screensaver look just like an unlocked desktop. The idea would be to take a screenshot just before activating the screensaver, and use that screenshot in the screensaver. Has anyone done this before?
2014/09/23
[ "https://apple.stackexchange.com/questions/146652", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/84528/" ]
You can use [**ScriptSaver**](http://swannman.github.io/scriptsaver/). 1. Set the AppleScript to a script containing the following: ``` do shell script "/usr/sbin/screencapture /path/to/folder/screensaver.png" ``` /path/to/folder must exist and be empty, or at least contain no other images 2. Set the screen saver to display after the AppleScript to Classic. 3. In System Preferences, set the folder for the Classic screensaver to the /path/to/folder.
This seems to do exactly what you want. I use it to secure a machine that shows a dashboard. It works great. <http://www.monkeybreadsoftware.de/Software/Transparent.shtml>
109,434
I admit that I spend most of my time googling for a solution when faced with a problem. So, when it comes to interviewing, sometimes the question is really tough or there are questions you never tried before. I understand this is to assess how much do we understand about theory but sometimes I also wondering, perhaps interviewer wants to know how are we going to solve the problem? I am struggling with this question, with regards to a developer role: **Am I allowed to use search engines when doing an interview assessment**?
2018/03/21
[ "https://workplace.stackexchange.com/questions/109434", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/50103/" ]
Your potential employer is very likely interested in having you correctly completing the assigned tasks in a given time. That you already knew how to handle it or that you searched for help it has little impact on the outcome, as long as you can be on schedule. Someone said that knowledge is not about keeping all the information in your head, but knowing where to find it when it is needed. This is the very case.
If you are going to have *Google* in performing the job then it seems reasonable to use *Google* for the assessment. But it should still be your own work. Don't copy solutions as a whole. If the assessment does not match your real skills it will eventually come out. If it lands you a job you are not qualified for you will be frustrated and possibly fired. Take it to an extreme. Does refer to the documentation count as cheating? If they want a controlled result then they should have timed tasks at their location with either no access to the Internet or limited (E.G. msdn.microsoft.com/en-us). This is just my opinion but I think is should be like 8 super easy questions if you miss you are out. And then 1 or 2 challenging questions in 2-4 hours. A two week take home to build a full web site to me is ridiculous - that is a company that has no idea how to measure core skills. I see tech questions that appear to be interview question and I will typically pass unless the question is interesting to me. If you are going to post for an answer on the stack exchange network then use a name that does not trace back to you.
65,688,657
Context ======= I'm running Jenkins on Windows, writing declarative pipelines. I'm trying to put multiple commands in a single `bat` step, while still making the step fail if any of the included commands fail. Purpose of this is twofold. * The best practices document suggests that creating a step for every little thing might not be the best idea (might also be solved by putting more stuff in batch files, but my builds aren't that big yet) * I want to execute some commands in a Visual Studio command prompt, which is achieved by first `call`ing a `.bat` file that sets the environment, and then doing any necessary commands. Code ==== I wrote the following Groovy code in my `Jenkinsfile`: ``` def ExecuteMultipleCmdSteps(String... steps) { bat ConcatenateMultipleCmdSteps(steps) } String ConcatenateMultipleCmdSteps(String... steps) { String[] commands = [] steps.each { commands +="echo ^> Now starting: ${it}"; commands += it; } return commands.join(" && ") } ``` The problem/question ==================== I can't get this to work reliably. That is, in a single `Jenkinsfile`, I can have multiple calls to `ExecuteMultipleCmdSteps()`, and some will work as intended, while others will fail with `java.lang.NoSuchMethodError: No such DSL method 'ExecuteMultipleCmdSteps' found among steps [addBadge, ...` I have not yet found any pattern in the failures. I thought it only failed when executing from within a `warnError` block, but now I also have a problem from within a `dir()` block, while in a different `Jenkinsfile`, that works fine. This problem seems to be related to `ExecuteMultipleCmdSteps()` being a variadic function. If I provide an overload with the correct number of arguments, then that overload is used without problem. I'm at a loss here. Your input would be most welcome. Failed solution =============== At some point I thought it might be a scoping/importing thing, so I enclosed `ExecuteMultipleCmdSteps()` in a class (code below) as suggested by [this answer](https://stackoverflow.com/a/39830673/114197). Now, the method is called as `Helpers.ExecuteMultipleCmdSteps()`, and that results in a `org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such static method found: staticMethod Helpers ExecuteMultipleCmdSteps org.codehaus.groovy.runtime.GStringImpl org.codehaus.groovy.runtime.GStringImpl` ``` public class Helpers { public static environment public static void ExecuteMultipleCmdSteps(String... steps) { environment.bat ConcatenateMultipleCmdSteps(steps) } public static String ConcatenateMultipleCmdSteps(String... steps) { String[] commands = [] steps.each { commands +="echo ^> Now starting: ${it}"; commands += it; } return commands.join(" && ") } ``` Minimal failing example ======================= Consider the following: ``` hello = "Hello" pipeline { agent any stages { stage("Stage") { steps { SillyEcho("Hello") SillyEcho("${hello}" as String) SillyEcho("${hello}") } } } } def SillyEcho(String... m) { echo m.join(" ") } ``` I'd expect all calls to `SillyEcho()` to result in `Hello` being echoed. In reality, the first two succeed, and the last one results in `java.lang.NoSuchMethodError: No such DSL method 'SillyEcho' found among steps [addBadge, addErrorBadge,...` Curiously succeeding example ============================ Consider the following groovy script, pretty much equivalent to the failing example above: ``` hello = "Hello" SillyEcho("Hello") SillyEcho("${hello}" as String) SillyEcho("${hello}") def SillyEcho(String... m) { println m.join(" ") } ``` When pasted into a Groovy Script console (for example the one provided by Jenkins), this succeeds (`Hello` is printed three times). Even though I'd expect this example to succeed, I'd also expect it to behave consistently with the failing example, above, so I'm a bit torn on this one.
2021/01/12
[ "https://Stackoverflow.com/questions/65688657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114197/" ]
> > is not working as I expect > > > It definitely doesn't work the way it except you to. The overload of `erase` you use looks like ``` string& erase( size_type index = 0, size_type count = npos); ``` Description of the overload from cppreference: > > Removes min(count, size() - index) characters starting at index. > > > So what you really do by `svg.erase(0, svg.find("//") + 1)` is you erase all the characters from index [0] up to [index of the last `'/'` you found] Instead you should do the following: 1. Search for `"//"` in your string, name this position A. 2. Search for `'\n'` in your string, name this position B. 3. Erase interval [A; B] from the string or [A; svg.length()] if you didn't find B 4. Repeat until there is no more position A P.s. I'd recommend to search from the end rather than from beginning because it would be easier to erase a piece form string if it is closer to the end than to the beginning P.p.s. Also be sure to use iterators if you want to remove exactly intervals because the only overload of `erase` that removes intervals is ``` iterator erase( const_iterator first, const_iterator last ); ```
In the end this was the solution I found ``` std::string trim(const std::string &str) { size_t first = str.find_first_not_of(' '); if (std::string::npos == first) { return str; } size_t last = str.find_last_not_of(' '); return str.substr(first, (last - first + 1)); } bool startsWith(const std::string &input, const std::string &start) { return input.find(start) != std::string::npos; } std::string myString = R"svg( <svg height={size} width={size}> <rect {...rectProps} x={x0h} y={y0h} /> // <rect {...rectProps} x={x1h} y={y0h} /> <rect {...rectProps} x={x0h} y={y1h} /> // <rect {...rectProps} x={x1h} y={y1h} /> </svg> )svg"; std::istringstream stream(myString); std::string line; std::string myFinalString; while (std::getline(stream, trim(line))) { if (!startsWith(line, "//")) { myFinalString += line + "\n"; } } ```
19,320,747
Whenever I append a `:` character in Vim in Python mode, it either: * indents the line * dedents the line * does nothing What is it even trying to do, and how do I get rid of this behavior?
2013/10/11
[ "https://Stackoverflow.com/questions/19320747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272865/" ]
[Nathan Grigg's answer](https://stackoverflow.com/a/21820207/456550) set me on the right track. I had to make a few changes for my setup. I had to use `:setlocal indentkeys-=<:>`, because in my case `:set indentkeys?` showed `indentkeys=0{,0},!^F,o,O,e,<:>,=elif,=except`. Also, putting `:setlocal indentkeys-=<:>` in `.vim/after/ftplugin/python.vim` did not work to make the change permanent. I found that there is a built-in vim python indent file that runs AFTER this after-ftplugin file. To diagnose, open a Python file for editing, and run `:scriptnames`. That will show you a list of all the vim scripts that have run, in order of precedence. The scripts at the bottom of that list have been applied most recently, and take precedence. See [this question on SuperUser](https://superuser.com/questions/166902/why-does-vim-ignore-files-in-vim-after-ftplugin) for more info. When I did that, it showed me a built-in vim file at `/my-install-path/vim/7.4.1830/share/vim/vim74/indent/python.vim`. Sure enough, that was setting `<:>` as part of the indent keys. To fix it, I set an autocommand in .vimrc, and that really gets the last word. ``` autocmd FileType python setlocal indentkeys-=<:> ``` **Update** I had to add `:setlocal indentkeys-=:` after all. Here's what I have in my `.vimrc` now. ``` autocmd FileType python setlocal indentkeys-=<:> autocmd FileType python setlocal indentkeys-=: ```
*TL;DR* I disabled autoindentation by typing: > > **:set indentexpr=** > > > then hitting the ENTER key. It's a quick fix without needing to understand *indentkeys* .. Thanks to [Christian Long](https://stackoverflow.com/users/456550/christian-long) for the docs to [indentkeys](http://vimdoc.sourceforge.net/htmldoc/options.html#%27indentkeys%27), where I noticed (my emphasis): > > A list of keys that, when typed in Insert mode, cause reindenting of > the current line. *Only happens if 'indentexpr' isn't empty*. > > > Tip - you might want to save a copy of the existing value of *indentexpr* before you clear it out. To see that (and any other values that are set) just type: > > :set > > > HTH
2,033,115
I am trying to refine my knowledge of N\_Tier arch Inside the BLL, and In case I am using custom business objects in BLL, like CustomerInfo {FN, LS, ...}, Consider that I have Customer table and Currency table, Customer is having a default currency, thus there is a FK Currency\_ID in Customer table, at UI layer, we need to show Currency symbol instead of Currency\_ID. (SELECT...INNER JOIN..) Can I put the Currency symbol as a property in CustomerInfo, instead of putting a reference of CurrencyInfo inside CustomerInfo. I think No is the answer, but Why? What can go bad? Should every business table (excluding validation lookups) in database maps to a business object? I think business objects (objects which contain the data brought form DAL) should be carefully mapped to tables in database, this can increase the maintainability. But BLL can contain any objects for business operations and business validations. Please give me some books titles, or links to master the N-tier arch and the debates about it. Thanks
2010/01/09
[ "https://Stackoverflow.com/questions/2033115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225537/" ]
Use proxy `static constexpr const char type_name_str[] = {"type name"};` for passing string as template parameter. Defining string using `[]` is important. ``` #include <iostream> template<typename T, const char* const t_name> struct TypeName { public: static constexpr const char* Name() { return t_name; }; }; static constexpr const char type_name_str[] = {"type name"}; int main() { std::cout<<TypeName<float, type_name_str>::Name(); return 0; } ```
Maybe not what the OP is asking, but if you use `boost`, you can create a macro like this for example: ``` #define C_STR(str_) boost::mpl::c_str< BOOST_METAPARSE_STRING(str_) >::value ``` Then use as follows: ``` template<const char* str> structe testit{ }; testit<C_STR("hello")> ti; ```
5,124
Ansible seems to have a clear advantage over competition like chef and puppet because it is agent-less and saves a certain degree of overhead. I have read several comparisons of the various configuration tools and while each tool has its own strengths and weaknesses, I realize that much of it is down to personal preference. The benefit of being agent-less is a no-brainer but are there any advantages of the master/agent architecture with respect to configuration management tools?
2018/10/05
[ "https://devops.stackexchange.com/questions/5124", "https://devops.stackexchange.com", "https://devops.stackexchange.com/users/5288/" ]
I've found an interesting discussion on the topic [configuration management pull vs push topology](https://serverfault.com/questions/568187/configuration-management-push-versus-pull-based-topology) [One contributor](https://serverfault.com/a/568372/392485) writes that pull systems (master/agent) offer more flexibility and are easier to scale.
IMHO the only advantage of a master/agent pull architecture is that it can be used in a firewalled network (when the actual configuration is located outside that network) without opening up holes in the firewall, while the push architecture cannot. In terms of flexibility, I think the most important issue is the minimal setup required on a node to become remotely manageable. Once this requirement is met both architectures can handle updates. A master/agent architecture needs the agent installed, configured and running. On one hand Puppet and Chef aren't (yet) by default installed on most systems, while sshd (needed by Ansible) is. On the other hand even Ansible needs sshd running and credentials configured on the node to be accessible, so I'd say there's not much of a difference from this perspective - especially if the minimal setup is achieved via customized system images. In terms of scalability, I'd consider the master/agent architecture less scalable (but just a bit): * if the master attempts to actively keep a live system state (i.e. the map of all the agents and their states) that would chew up some time/resources. Without a master, Ansible isn't susceptible to such scalability issue. Granted, even master/agent architectures can offer a scalable approach to providing an overall system state similar to Ansible's (and probably they all do nowadays). * in the old days, when the master would actually drive the agent configuration tasks (as mentioned in the post you referenced in your answer), the scalability of such architecture could suffer a lot. But this is not a big deal anymore since for all the tools mentioned in your question the configuration is just transferred to the local node which then performs the tasks. * when it comes to transferring the configs to the local nodes, a pull architecture is limited only by the capacity of serving those configurations (common to both architectures), but a master/agent one needs to also run the logic driving transfers and actually making the transfers, if applicable (it's possible to just instruct the agents to pull their own configs), which limits how fast the master can propagate configs to a large number of agents.
52,542,638
I'm making a rock paper scissors game for school and I have a working game but its 213 lines long. I was trying to shorten it up some by adding switch case in place of my if statements. Are there some instances where a switch case just won't work and it has to be an if statement? ``` String weaponChoice = keyboard.nextLine(); switch (weaponChoice) { case "Rock": System.out.println("You Chose Rock"); break; case "Paper": System.out.println("You Chose Paper"); break; case "Scissors": System.out.println("You chose Scissors"); break; default: System.out.println(weaponChoice + " is not a valid answer the computer gets a point!"); compScore++; break; } ``` I had the above code in an if statement and switched it over no problem but the below code I'm not sure how to change it over. ``` String getComputerChoiceVariable = getComputerChoice(); System.out.println("The computer chose " + getComputerChoiceVariable); if (weaponChoice.equals(getComputerChoiceVariable)) { System.out.println("It's a draw!"); ties++; } else if ((weaponChoice.equals("Rock")) && (getComputerChoiceVariable.equals("Scissors"))) { System.out.println("You won!"); userScore++; } else if ((weaponChoice.equals("Paper")) && (getComputerChoiceVariable.equals("Rock"))) { System.out.println("You won!"); userScore++; } else if ((weaponChoice.equals("Scissors")) && (getComputerChoiceVariable.equals("Paper"))) { System.out.println("You won!"); userScore++; } else if (weaponChoice.equals("Rock") && getComputerChoiceVariable.equals("Paper")) { System.out.println("You Lost!"); compScore++; } else if (weaponChoice.equals("Paper") && getComputerChoiceVariable.equals("Scissors")) { System.out.println("You Lost!"); compScore++; } else if (weaponChoice.equals("Scissors") && getComputerChoiceVariable.equals("Rock")) { System.out.println("You Lost!"); compScore++; } ``` Maybe something like ``` switch (weaponChoice,getComputerChoiceVariable){ case "Rock",case "Scissors": System.out.println("You won!"); } ``` But Java doesn't like that I get a ton of errors. Can a switch take two parameters? I'm super new to Java. Could I somehow use the && to compare cases?
2018/09/27
[ "https://Stackoverflow.com/questions/52542638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A `switch` statement can test the value of only one expression. It is possible to nest `switch` statements, but that's overly verbose and is no better than a series of `if`/`else` statements. As an aside, you may want to validate the user's weapon of choice, so someone doesn't choose Lizard, Spock, Foo, or something else unexpected. You can concatenate the strings into one so it can be tested. I would use a separator such as `"|"` to make the choices clear. Also, different cases have the same logic, avoiding repetition. ``` switch(weaponChoice + "|" + computerChoice) { case "Rock|Scissors": case "Scissors|Paper": case "Paper|Rock": System.out.println("You won!"); userScore++; break; case "Rock|Paper": case "Paper|Scissors": case "Scissors|Rock": System.out.println("You lost!"); compScore++; break; default: System.out.println("It's a draw!"); ties++; } ``` This is concise and it lists all similar cases together, without repetition.
You don't necessarily need to make a switch of your code to shorten it. You can put the tree options in a list, and compare the user's choice with the value that that comes after the computer's choice to see if the user won. If you have the list `[Rock, Paper, Scissors]`, the computer chose Rock. Find the element after it, so Paper in this case. Now you only have to see if that value is equal to the user's choice, and if that's the case, the user won. ``` List<String> choices = Arrays.asList("Rock", "Paper", "Scissors"); if (playerChoice.equals(computerChoice)) { System.out.println("Draw!"); } else if (playerChoice.equals(choices.get((choices.indexOf(computerChoice) + 1) % 3))) { System.out.println("You won!"); } else { System.out.println("You lost!"); } ``` Here `choices.indexOf(computerChoice)` finds the current positions of the computer's choice in the list. It add's one to find the next element in the list and uses the remainder operator (`% 3`) to make sure that if the next index is higher than the last element in the list, it flips back to the first element.
23,139,202
In PHP using method chaining how would one go about supplying a functional call after the last method being called in the chain? Also while using the same instance (see below). This would kill the idea of implementing a destructor. > > The end result is a return value and functional call of private "insert()" from the defined chain properties (of course) without having to call it publicly, no matter of the order. > > > Note, if I echo (\_\_toString) the methods together it would retrieve the final generated unique code which is normal behavior of casting a string. **Example below:** ``` class object { private $data; function __construct($name) { // ... some other code stuff } private function fc($num) { // some wicked code here } public function green($num) { $this->data .= fc($num*10); return $this; } public function red($num) { $this->data .= fc($num*25); return $this; } public function blue($num) { $this->data .= fc($num*1); return $this; } // how to get this baby to fire ? private function insert() { // inserting file_put_content('test_code.txt', $this->data); } } $tss = new object('index_elements'); $tss->blue(100)->green(200)->red(100); // chain 1 $tss->green(0)->red(100)->blue(0); // chain 2 $tss->blue(10)->red(80)->blue(10)->green(0); // chain 3 ``` Chain **1**, **2**, and **3** would generated an unique code given all the values from the methods and supply an action, e.g. automatically inserting in DB or creating a file (used in this example). As you can see no string setting or casting or echoing is taking place.
2014/04/17
[ "https://Stackoverflow.com/questions/23139202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804013/" ]
You could keep a list of things that needs to be initialised and whether they have been so in this instance or not. Then check the list each time you use one of the initialisation methods. Something like: ``` class O { private $init = array ( 'red' => false , 'green' => false , 'blue' => false ); private function isInit() { $fin = true; foreach($this->init as $in) { $fin = $fin && $in; } return $fin; } public function green($n) { $this->init['green'] = true; if($this->isInit()) { $this->insert(); } } public function red($n) { $this->init['red'] = true; if($this->isInit()) { $this->insert(); } } public function blue($n) { $this->init['blue'] = true; if($this->isInit()) { $this->insert(); } } private function insert() { echo "whee\n"; } } ``` But personally I think this would be more hassle then it's worth. Better imo to expose your `insert` method and let the user of you code tell when the initialisation is finished. So something that should be used like: ``` $o->red(1)->green(2)->blue(0)->insert(); ``` -update- If it's the case that it's impossible to predict what functions need to be called you really do need to be explicit about it. I can't see a way around that. The reason is that php really can't tell the difference between ``` $o1 = new A(); $o2 = $o1->stuff(); ``` and ``` $o2 = (new A())->stuff(); ``` In a language that allows overloading `=` I guess it would be possible but really really confusing and generally not a good idea. It is possible to move the explicit part so that it's not at the end of the call chain, but I'm not sure if that would make you happier? It would also go against your desire to not use another instance. It could look something like this: ```php class O { public function __construct(InitO $ini) { // Do stuff echo "Whee\n"; } } class InitO { public function red($n) { return $this; } public function green($n) { return $this; } public function blue($n) { return $this; } } $o = new O((new InitO())->red(10)->red(9)->green(7)); ``` You can of course use just one instance by using some other way of wrapping but the only ways I can think of right now would look a lot uglier.
Ok let's see a code example ``` <?php // map dummy class class map { // __call magic method public function __call($name, $args) { return $this; } } // now we chain $map = new map; // let's find me $map->start('here') ->go('right') ->then() ->turn('left') ->and('get water') ->dontEat() ->keep('going') ->youShouldSeeMe('smiling'); ``` here we don't know what the last method would be and we need to trigger a kinda operation or event once we hit the end. According to data structure we can call this the LIFO stack. (Last in first out) so how did i solve this on PHP? > > // i did some back tracing > > > ... back to the \_\_call function ``` function __call($name, $args) { $trace = debug_backtrace()[0]; $line = $trace['line']; $file = $trace['file']; $trace = null; $getFile = file($file); $file = null; $getLine = trim($getFile[$line-1]); $line = null; $getFile = null; $split = preg_split("/(->)($name)/", $getLine); $getLine = null; if (!preg_match('/[)](->)(\S)/', $split[1]) && preg_match('/[;]$/', $split[1])) { // last method called. var_dump($name); // outputs: youShouldSeeMe } $split = null; return $this; } ``` And whoolla we can call anything once we hit the bottom. **\*(Notice i use null once i am done with a variable, i come from C family where we manage memory ourselves)** Hope it helps you one way or the other.
28,952,944
I recently noticed a bug due to a mismatched parameter order in the class to its interface parameter order. I felt that this should have been a compile error. I found out that Interfaces do not constrain the parameter names. So if you see my example below I have `firstParameter` and `secondParameter` reversed, I also have `parameterOne` and `parameterTwo`, both as valid builds. This may build just fine, but you will likely run into runtime errors. On the other hand, it does require the order of the types of the parameters to match. So I thought perhaps I do not need to place the parameter names in the interface and just the value types, but that does not work and the interface would still need to provide a description of what the types are in terms of what a consumer would place there. **My Question** Is there a way to guarantee at build time that a class matches the interface parameter names? I would prefer not to do this manually. The reason this is important is even though the method variables cannot be setup to be used by the interface, someone consuming a service reference or other use of an interface would see the Interface parameters at the time of setup and that is the expected use of the parameters. If I cannot rely on a contract to be exact, what is the point of a contract in the first place? ``` interface IParameterTest { void TwoStringParameters(string firstParameter, string secondParameter); void TwoStringParametersAndAnInt(string firstParameter, string secondParameter, int thirdParameter); } public class ParameterTest : IParameterTest { //Builds and matches interface //public void TwoStringParameters(string firstParameter, string secondParameter) //{ // throw new NotImplementedException(); //} //Builds and does not match interface //public void TwoStringParameters(string secondParameter, string firstParameter) //{ // throw new NotImplementedException(); //} //Builds and does not match interface public void TwoStringParameters(string parameterOne, string parameterTwo) { throw new NotImplementedException(); } //Builds and matches interface public void TwoStringParametersAndAnInt(string firstParameter, string secondParameter, int thirdParameter) { throw new NotImplementedException(); } //Does not build or match interface //public void TwoStringParametersAndAnInt(int firstParameter, string secondParameter, string thirdParameter) //{ // throw new NotImplementedException(); //} } ```
2015/03/09
[ "https://Stackoverflow.com/questions/28952944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1558269/" ]
> > Is there a way to guarantee at build time that a class matches the interface parameter names? I would prefer not to do this manually. > > > Not within the C# language. However: * You could write a unit test to check, reasonably easily. Not quite build time, but still early enough to catch errors before they're big problems. * You could write a Roslyn code diagnostic to flag it as an error (and even provide a code fix for it). Of course, the unit test could be written via Roslyn as well, but you could do it fairly easily just using plain reflection. It's not entirely clear from your question whether you've spotted the really nasty problem with parameter names being wrong, by the way - it's not just in terms of human readability, but it can significantly affect behaviour if you use named arguments. For example, suppose you have code like this: ``` public interface IFoo { void Foo(int x, int y); } public class FooImpl : IFoo { public void Foo(int y, int x) { ... } } ... IFoo foo = new FooImpl(); foo.Foo(x: 10, y: 20); // Equivalent to foo.Foo(10, 20) ``` Now if someone decides to use `var` instead, the compile-time type of `foo` is changed, so suddenly the named arguments map to different parameters. ``` var foo = new FooImpl(); foo.Foo(x: 10, y: 20); // Equivalent to foo.Foo(20, 10) ``` Perfectly valid code... but with a different meaning to the previous code. There are other times that changing the compile-time type of a variable can affect things, but that's *usually* around overloading etc... this is in the simple case where there really is just one method.
As Jon says, C# doesn't really care what the parameters are called, but if you wanted to reflectively assert the parameter names for yourself; either at start up or in a unit test, you could use something like this: ``` public class Program { public static void Main(string[] args) { var assembly = Assembly.GetAssembly(typeof(Program)); var types = assembly .GetTypes() .Where(x => x.IsClass && x.GetInterfaces().Any()); foreach (var type in types) { var interfaces = type.GetInterfaces().Where(x => x.Assembly == assembly); foreach (var iface in interfaces) { var classMethods = type.GetMethods(); foreach (var interfaceMethod in iface.GetMethods()) { var classMethod = classMethods.First(x => x.ToString() == interfaceMethod.ToString()); Debug.Assert( interfaceMethod.GetParameters().Select(x => x.Name).SequenceEqual(classMethod.GetParameters().Select(x => x.Name)), "Incorrect parameter names in method: " + type.Name + "." + classMethod.Name); } } } } public interface ITest { void MethodA(string first, string second); } public class TestA : ITest { public void MethodA(string first, string second) { } } public class TestB : ITest { public void MethodA(string second, string first) { } } } ```
133,564
Wave theory does not account for the photon model, which was developed only to explain quantum effects like photoelectric effect. Then why do we talk about a photon's reflection and rarefaction, as that would require it to have wave properties? This has been mentioned here: (<http://en.m.wikipedia.org/wiki/Photon>) It is light that has wave-particle duality, not photon; it simply is a means of explaining the particle nature of light.
2014/09/02
[ "https://physics.stackexchange.com/questions/133564", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/56742/" ]
It is certainly possible to clone mammals. Scientists have done that. One can replicate many things well enough for them to be functionally indistinguishable for all practical purposes. Industrial mass production processes do just that. Some of the chips in your computer are fabricated with such a precision, that some of their structures (e.g. gate insulation layers) are reproduced with an uncertainty of a few atomic layers. Can these chips be re-engineered and replicated? Yes, if you had the money, you could do that. Why is all of this possible? Because none of these things require reproduction at the level of the quantum mechanical uncertainty. Life uses some quantum mechanical effects e.g. in photosynthesis, but most of it is just ordinary chemistry ruled by thermodynamics. Similarly, solids can be structured atom by atom, because the atomic state in them is determined by their chemical environment, and not by individual excitation of each atom. There are plenty of researchers who are now capable of arranging single atoms one by one on suitable substrates. Now, let's look at systems that could not be reproduced: a true quantum computer in the middle of a computation would basically lose its information, if we tried to read it out and replicate it. What we could reproduce, is the quantum computer itself, but we could not clone its internal state. So the answer to your question is: it depends. Some systems are reproducible "well enough" and some are fundamentally not reproducible without destruction of the original. Now to your question about distinguishability: if we are reproducing macroscopic items, we can always tell them apart. The same is true for single atoms that are far enough away. Only if we can bring two atoms close enough together, do they become indistinguishable. This can, obviously, not happen for macroscopic objects, which can never even come close enough to lose track of which is which.
Best answer I could find - Anyone care to chime in on this? I can say with 100% certainty, it would not be the same person. The amount of information contained in a human body is astronomical. This creates a higher mathematical probability (nearing infinity) that some of that information would be lost. Even if applying a future chaos theory to extract missing coherent data from a fading signal would not work due to the biological body always being in constant flux. The Neurotransmitters which send chemical messages between neurons are never at rest, thus recreating that snapshot of a moment of the brain precisely in time would be impossible. Even computer programs never make exact copies of programs over time due to these quantum chaotic fluctuations. <http://www.sciencegymnasium.com/2013/11/the-metaphysics-of-teleportation.html>
1,457,568
Looking at the posts here for email address validation, I am looking to be much more liberal about the client side test I am performing. The closest I have seen so far is: ``` ^([\w-\.]+)@((\[[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}\.)|(([\w-]+\.)+)) ([a-zA-Z]{2,4}|[0–9]{1,3})(\]?)$ ``` That will not match this#strnage@foo.com, which according to RFC is valid * Uppercase and lowercase English letters (a-z, A-Z) * Digits 0 through 9 * Characters ! # $ % & ' \* + - / = ? ^ \_ ` { | } ~ * Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively. I want a pretty simple match: * Does not start with . * Any character allowed up to the @ * Any character allowed after the @ * No consecutive . or @ allowed * Part after the last . (tld) must be [a-z0-9-] I will use \i to make the search case insensitive. The consecutive characters is where I am getting hung up on.
2009/09/22
[ "https://Stackoverflow.com/questions/1457568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170579/" ]
The following has been useful for me for quite sometime now. ``` function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } ```
Perfect validation regex is probably hard to match, but I've used this one for quite some time: ``` /^([\w-\.\+])+\@([\w-]+\.)+([\w]{2,6})+$/ ``` Only changed it recently to match 6-char TLDs.
26,515,303
i have got following problem with Joomla! 3.3.4: after entering text to the Browser Page Title window in article options, the title doesn't change. In that place is only displayed the global sitename. In older Joomla everything works properly.
2014/10/22
[ "https://Stackoverflow.com/questions/26515303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3872323/" ]
To change the field title you need to edit the menu item options. When you go to the detail view of menu item in question, navigate to the **Page Display** tab. The first field is **Browser Page Title**, enter the title you want to appear and save. That should sort it out for you...
Please try to switch to the default template and if it works there is something wrong with your template. In order to set browser title you could use setTitle() method. ``` <?php $this->setTitle( $title ); ?> ``` You could check setTitle usage at: [Joomla Docs](http://docs.joomla.org/Customising_the_dynamic_page_title). If you want to set title in article template you could make an addition to: ``` /templates/*template_name/html/article/default.php ``` An example code that could set the article title to browser title would be: ``` <?php $this->setTitle( $this->item->title ); ?> ``` Hope this helps
74,016
The explosive growth of Stack Exchange sites is making things really kind of difficult at times. For example: I'm trying to get help with working with Shibboleth on Ubuntu. Does that mean I should be asking on SO (for the Shibboleth), askUbuntu (for the Ubuntu), Server Fault (since I'm trying to set up the Service Provider security) or Webmasters (since ultimately this is a web application)? It's hard enough framing the question without worrying that the response will be "wrong site, go ask on xxxx."
2011/01/05
[ "https://meta.stackexchange.com/questions/74016", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/142055/" ]
Good troubleshooting techniques require the ability to break the problem up into smaller chunks that involve as few dependencies as possible. For instance, your example indicates that the root problem is "get help working with shibboleth" - all else is irrelevant unless you've already determined that it's not working due to, for install, Ubuntu. In this way, a good troubleshooter works through their problem one part of the stack at a time until they find the root cause. This may involve several questions on several different sites. So we expect users to choose one site that they believe is best suited to the problem. The active users of the site will triage the question and migrate it if necessary. If it's too broad, as in your example, then they will generally ask a few questions that will help the user figure out how to troubleshoot the problem and get it to the point where they know who to ask. So no, I don't think this is a problem. However, if you can point out several examples where this is demonstrated then perhaps we can discuss it more specifically.
You say too much overlap, then mention a problem that itself covers many areas. It's not the fact that the websites overlap that causes you an issue, and in fact this helps you because your problem might be suitable on several sites. The problem of a given question being relevant on many sites is not a new one at all, and it's one [I've written about many times](https://meta.stackoverflow.com/search?q=laser+sharp+focus+user%3A2915). Unfortunately, you propose two problems (sites overlap, and some questions belong on multiple sites) but you don't offer any suggestions. About the best we can offer is that you pick a site that you feel is best for your problem, or a site you feel fits your field best, and submit your questions there. The experts in the community you choose will help move the question to the right arena if needed. But the important thing to remember about why these sites are successful is that they attract and keep experts. If we start allowing off-topic questions on a regular basis without moving them, the experts will eventually leave due to a poor signal to noise ratio. So while balkanization seems to be a bad aspect of these sites, it's necessary to cultivate the community of experts that make these sites so useful. The overlap actually helps tie the communities together.
1,176,069
Example from Mac OS X: ``` [[aView animator] setFrame:NSMakeRect(100.0,100.0,300.0,300.0)]; ``` I have tried something similar in UIKit, but it seems the animator method is not there for UIView. So there's no "implicit" animation?
2009/07/24
[ "https://Stackoverflow.com/questions/1176069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62553/" ]
I recommend not using "SELECT \*", that's typically CPU/time/whatever more consuming than explicitely listing the fields you want to have, and it is more readable for someone else because you don't have to remember which are the fields contained in the table. +1 for the BETWEEN it will impact on performance, making your query faster.
Do you have any constraints you are imposing on the parameters? You could also optimize the query by removing unnecessary parameters if you have constraints which make the specifications listed in double. Such as, your query is logically equivalent to: ``` "SELECT *,rowid FROM tblEvent_basic WHERE service_id = ? AND ( \ end_time != ? AND \ end_time > ? ) \ ORDER BY start_time ASC;" ``` with ``` rc = sqlite3_bind_int( sql_stmt,1,service_id); rc = sqlite3_bind_text(sql_stmt,2,ts.end, 5, SQLITE_TRANSIENT); rc = sqlite3_bind_text(sql_stmt,3,ts.start, 5, SQLITE_TRANSIENT); ``` .. with the assumption that ts.start <= ts.end. Application logic can often save the work of the database engine, if you have well-defined parameters.
3,239,207
How do I open a file that is an Excel file for reading in Python? I've opened text files, for example, `sometextfile.txt` with the reading command. How do I do that for an Excel file?
2010/07/13
[ "https://Stackoverflow.com/questions/3239207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381259/" ]
This may help: This creates a node that takes a 2D List (list of list items) and pushes them into the excel spreadsheet. make sure the IN[]s are present or will throw and exception. this is a re-write of the Revit excel dynamo node for excel 2013 as the default prepackaged node kept breaking. I also have a similar read node. The excel syntax in Python is touchy. thnx @CodingNinja - updated : ) ``` ###Export Excel - intended to replace malfunctioning excel node import clr clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') ##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel C:\Program Files\Microsoft Office\Office15\EXCEL.EXE ##Need to Verify interop for version 2015 is 15 and node attachemnt for it. from Microsoft.Office.Interop import * ##Excel ################################Initialize FP and Sheet ID ##Same functionality as the excel node strFileName = IN[0] ##Filename sheetName = IN[1] ##Sheet RowOffset= IN[2] ##RowOffset ColOffset= IN[3] ##COL OFfset Data=IN[4] ##Data Overwrite=IN[5] ##Check for auto-overwtite XLVisible = False #IN[6] ##XL Visible for operation or not? RowOffset=0 if IN[2]>0: RowOffset=IN[2] ##RowOffset ColOffset=0 if IN[3]>0: ColOffset=IN[3] ##COL OFfset if IN[6]<>False: XLVisible = True #IN[6] ##XL Visible for operation or not? ################################Initialize FP and Sheet ID xlCellTypeLastCell = 11 #####define special sells value constant ################################ xls = Excel.ApplicationClass() ####Connect with application xls.Visible = XLVisible ##VISIBLE YES/NO xls.DisplayAlerts = False ### ALerts import os.path if os.path.isfile(strFileName): wb = xls.Workbooks.Open(strFileName, False) ####Open the file else: wb = xls.Workbooks.add# ####Open the file wb.SaveAs(strFileName) wb.application.visible = XLVisible ####Show Excel try: ws = wb.Worksheets(sheetName) ####Get the sheet in the WB base except: ws = wb.sheets.add() ####If it doesn't exist- add it. use () for object method ws.Name = sheetName ################################# #lastRow for iterating rows lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row #lastCol for iterating columns lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column ####################################################################### out=[] ###MESSAGE GATHERING c=0 r=0 val="" if Overwrite == False : ####Look ahead for non-empty cells to throw error for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset): for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset): if col.Value2 >"" : OUT= "ERROR- Cannot overwrite" raise ValueError("ERROR- Cannot overwrite") ##out.append(Data[0]) ##append mesage for error ############################################################################ for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset): for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset): ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__() ##run macro disbled for debugging excel macro ##xls.Application.Run("Align_data_and_Highlight_Issues") ```
``` import pandas as pd import os files = os.listdir('path/to/files/directory/') desiredFile = files[i] filePath = 'path/to/files/directory/%s' Ofile = filePath % desiredFile xls_import = pd.read_csv(Ofile) ``` Now you can use the power of pandas DataFrames!
35,155,475
I redraw the graphics of the `Tab` for the `TabControl` but I can't set the `Width` of it. What I want is that the text of the `Tab` and the icon is contained in its size. Now is something like this: [![tabs are overlaid](https://i.stack.imgur.com/RQQjG.png)](https://i.stack.imgur.com/RQQjG.png) My Code ``` private void tabControlForm_DrawItem(object sender, DrawItemEventArgs e) { try { using (Brush br = new SolidBrush(TabColors[tabControlForm.TabPages[e.Index]])) { Rectangle rect = e.Bounds; rect.Width += 10; e.Graphics.FillRectangle(br, rect); SizeF sz = e.Graphics.MeasureString(tabControlForm.TabPages[e.Index].Text, e.Font); e.Graphics.DrawString(tabControlForm.TabPages[e.Index].Text, e.Font, Brushes.Black, rect.Left + (rect.Width - sz.Width) / 2, rect.Top + (rect.Height - sz.Height) / 2 + 1); using (var src = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("Castor.Gestionale.images.close-button.png"))) { e.Graphics.DrawImage(src, rect.Right - 18, rect.Top + 10); } e.Graphics.DrawRectangle(Pens.DarkGray, rect); e.DrawFocusRectangle(); } } catch {} } ``` Thanks
2016/02/02
[ "https://Stackoverflow.com/questions/35155475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396650/" ]
Unfortunately, there isn't built-in property to control the width of the `TabPages'` tab header of the `TabControl` *individually* (Edit: apparently, there is `TabControl.ItemSize` to control it collectively. See TaW's answer to fix the width of all tab pages under a tab control). But a little trick you could do is to give additional `spaces` in the left or in the right of the `TabPage.Text` to give you enough space for your icon. Without space: [![enter image description here](https://i.stack.imgur.com/89cvg.png)](https://i.stack.imgur.com/89cvg.png) With 7 spaces: [![enter image description here](https://i.stack.imgur.com/plUmP.png)](https://i.stack.imgur.com/plUmP.png) It should be enough to put your icon
Use it... --------- ``` private void FrmSqlMain_Load(object sender, EventArgs e) { myTabControl.SizeMode = TabSizeMode.Normal; myTabControl.DrawMode = TabDrawMode.OwnerDrawFixed; } ```
3,143,607
I have to take a piece of data, and apply a large number of possible variables to it. I really don't like the idea of using a gigantic set of if statements, so i'm looking for help in an approach to simplify, and make it easier to maintain. As an example: ``` if (isSoccer) val = soccerBaseVal; else if (isFootball) val = footballBaseVal; .... // 20 different sports if (isMale) val += 1; else val += 5; switch(dayOfWeek) { case DayOfWeek.Monday: val += 12; ... } ``` etc.. etc.. etc.. with possibly in the range of 100-200 different tests and formula variations. This just seems like a maintenance nightmare. Any suggestions? EDIT: To further add to the problem, many variables are only used in certain situations, so it's more than just a fixed set of logic with different values. The logic itself has to change based on conditions, possibly conditions applied from previous variables (if val > threshold, for instance). So yes, i agree about using lookups for many of the values, but I also have to have variable logic.
2010/06/29
[ "https://Stackoverflow.com/questions/3143607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61164/" ]
A common way to avoid large switching structures is to put the information into data structures. Create an enumeration `SportType` and a `Dictionary<SportType, Int32>` containing the associated values. The you can simply write `val += sportTypeScoreMap[sportType]` and you are done. Variations of this pattern will help you in many similar situations. ``` public enum SportType { Soccer, Football, ... } public sealed class Foo { private static readonly IDictionary<SportType, Int32> sportTypeScoreMap = new Dictionary<SportType, Int32> { { Soccer, 30 }, { Football, 20 }, ... } private static readonly IDictionary<DayOfWeek, Int32> dayOfWeekScoreMap = new Dictionary<DayOfWeek, Int32> { { DayOfWeek.Monday, 12 }, { DayOfWeek.Tuesday, 20 }, ... } public Int32 GetScore(SportType sportType, DayOfWeek dayOfWeek) { return Foo.sportTypeScoreMap[sportType] + Foo.dayOfWeekScoreMap[dayOfWeek]; } } ```
Here are a few ideas: 1 Use lookup tables: ``` var val = 0; SportType sportType = GetSportType(); val += sportvalues[sportType]; ``` You can load the table from the database. 2 Use the factory pattern: ``` var val = 0; val += SportFactory.Create(sportType).CalculateValue(); ``` The [Dynamic Factory Pattern](http://www.joeyoder.com/papers/PLoP2008_25_Welicki+Yoder+Wirfs-Brock.pdf) is useful in situations were new (sport) types are added frequently to the code. This pattern uses reflection to prevent the factory class (or any global configuration) from being changed. It allows you to simply add a new class to your code. Of course the use of an dynamic factory, or even a factory can be overkill in your situation. You're the only one who can tell.
28,171,474
I have one query that returns multiple rows, and another query in which I want to set criteria to be either one of values from those multiple rows , so basicly I want the subquery to look something like this: ``` select * from table where id= (multiple row query); ``` Where `multiple row query` returns multiple rows. So if the values from those rows are 1,2,3 then I want to set id to be 1 or 2 or 3.
2015/01/27
[ "https://Stackoverflow.com/questions/28171474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4043273/" ]
`=` can be used when the subquery returns only 1 value. When subquery returns more than 1 value, you will have to use `IN`: ``` select * from table where id IN (multiple row query); ``` For example: ``` SELECT * FROM Students WHERE Marks = (SELECT MAX(Marks) FROM Students) --Subquery returns only 1 value SELECT * FROM Students WHERE Marks IN (SELECT Marks FROM Students ORDER BY Marks DESC LIMIT 10) --Subquery returns 10 values ```
Use `MAX` in your `SELECT` query to return one value… EXAMPLE ``` INSERT INTO school_year_studentid (student_id,syr_id) VALUES ((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year)) ``` instead of ``` INSERT INTO school_year_studentid (student_id,syr_id) VALUES ((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year)) ``` try it without MAX it will return more than one value
64,802,322
I have an origin repo in GitHub and I have created a local fork that I am developing on. I have a GitHub Action that runs a Bandit security check, but when I push changes and create a Pull request from a branch in my fork, the Bandit test runs on the code that is currently in the origin repo, not on the new code in the PR. How can I run the GitHub Action Workflow on the code that is inside the Pull Request? FYI: here is the "on" statement currently in the yml file: ``` name: Security scan on: push: branches: - master pull_request_target: branches: [main, dev] ```
2020/11/12
[ "https://Stackoverflow.com/questions/64802322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14625012/" ]
> > [...] we’ve added a new `pull_request_target` event, which behaves in an almost identical way to the `pull_request` event with the same set of filters and payload. However, instead of running against the workflow and code from the merge commit, the event runs against the workflow and code from the base of the pull request. > > > Source: <https://github.blog/2020-08-03-github-actions-improvements-for-fork-and-pull-request-workflows/> You can still checkout the code from the pull request with the following step: ``` - uses: actions/checkout@v2 with: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} ``` Source: <https://github.community/t/running-code-from-forks-with-pull-request-target/126688/6>
Triggers the workflow on push or pull request events > > Using `pull_request` > > > ``` name: CI on: [push, pull_request] jobs: python-tests: runs-on: ubuntu-latest steps: ... ```
3,053,216
Hi all I have (just like the rest) inherited some struts 1 code. I have had need to add a few more pages to this project. **What I cannot figure out is how to map several distinct but similarly natured input elements to my ActionForm.** Let me elaborate. I create a new `<Input>` element dynamically as the user inputs more and more items (I use the YUI autocomplete form element and for each entered input I add it as an input element to my form and draw a new YUI autocomplete - complex sounding, I know) So... My form looks a bit like (... after some prettifying and some such...): ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>My Cool App - Test Case Builder</title> <link rel="stylesheet" type="text/css" href="../script/yui/fonts/fonts-min.css" /> <link rel="stylesheet" type="text/css" href="../skins/myCoolApp/button/button.css" /> <link rel="stylesheet" type="text/css" href="../script/yui/autocomplete/assets/skins/sam/autocomplete.css" /> <link rel="stylesheet" type="text/css" media="screen" href="../skins/myCoolApp/testcase.css" /> <!-- YUI JAVA SCRIPTS --> <script type="text/javascript" src="../script/yui/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" src="../script/yui/element/element-min.js"></script> <script type="text/javascript" src="../script/yui/button/button-min.js"></script> <script type="text/javascript" src="../script/yui/datasource/datasource-min.js"></script> <script type="text/javascript" src="../script/yui/autocomplete/autocomplete-min.js"></script> <!-- APP JAVA SCRIPTS --> <script type="text/javascript" src="../script/myCoolApp/myCoolApp.js" ></script> <script type="text/javascript" src="../script/myCoolApp/stack.js" ></script> <script type="text/javascript" src="../script/myCoolApp/testcase/testcase.js"></script> <script type="text/javascript" src="../script/myCoolApp/testcase/default-data.js" ></script> <script type="text/javascript" src="../script/myCoolApp/testcase/data-structs.js" ></script> <script type="text/javascript" src="../script/myCoolApp/testcase/ui-elements.js" ></script> </head> <body class="cf010"> <div id="wrap"> <div id="header"> <div id="main-header"> COOL APP </div> </div> <div id="main-body"> <div id="content"> <div class="col main"> <div id="main"> <form method="post" id="testcaseForm" class="typea" action=""> <fieldset> <legend>Test Case Builder</legend> <div id="tk1" class="tabcontrol"> <ul class="tabs"> <li class="first active"> <a href="#"> <span>General</span> </a> </li> <li class="last"> <a href="#"> <span>Parameters</span> </a> </li> </ul> <div id="tab0" class="tc-panel"> <dl class="cls9"> <dt> <label for="scenario">Choose Scenario:</label> </dt> <dd> <input type="text" id="scenario" name="scenario" class="text" /> <span id="scenarioToggle"></span> <div class="auto-complete" id="scenarioContainer"></div> </dd> <dt> <label for="ruleID">Choose Rule ID:</label> </dt> <dd> <input type="text" id="ruleID" name="ruleID" class="text" /> <span id="ruleIDToggle"></span> <div class="auto-complete" id="ruleIDContainer"></div> </dd> <dt> <label for="Test Case Name" accesskey="t"><span class="accesskey">T</span>est Case Name:</label> </dt> <dd> <input type="text" id="testCaseName" name="testCaseName" class="text" /> </dd> </dl> </div> <div id="tab1" class="tc-panel hidden"> <div class="toolbar" id="action-bar"> <ul> <li class="first"> <a title="select all" href="#" id="btmSelectAll" class="button"> <span>select all</span> </a> </li> <li> <a title="remove row" href="#" id="btmRemove" class="button"> <span>remove row</span> </a> </li> <li> <a title="undo last" href="#" id="btmRollBack" class="button disabled"> <span>undo last</span> </a> </li> <li class="last"> <a title="accept row" href="#" id="btmAccept" class="button disabled"> <span>accept row</span> </a> </li> </ul> </div> <div id="param.list" class="gridclip"> <table id='param.list.tbl' class='grid modela' > <caption>Test Case Summary</caption> <col/><col/><col/> <thead> <tr> <th class='hl center first'> <input class='grid-select-all' type='checkbox' /> <th> <th scope='col'>Row</th> <th scope='col'>Parameter</th> <th scope='col' class='last'>Value</th> </tr> </thead> <tfoot> <tr> <th scope='row'>Total</th> <td colspan='3'>2 parameters as Test Case input</td> </tr> </tfoot> <tbody id='param.list.tbl.body'> <tr class='odd'> <td class='rowcheck center first'> <input value='param1###value1' id='cb1' name='SelectedRows' class='grid-select-row' type='checkbox'/> </td> <td class='id'>1</td> <td>param1</td> <td class='last'>value1</td> </tr> <tr class='even'> <td class='rowcheck center first'> <input value='param2###value2' id='cb2' name='SelectedRows' class='grid-select-row' type='checkbox'/> </td> <td class='id'>2</td> <td>param2</td> <td class='last'>value2</td> </tr> <tr class='odd'> <td class='rowcheck center first' /> <td class='id'><em>new</em></td> <td> <dl class='clsTable'> <dt> <input type='text' id='param' name='param' class='text paramInput' /> </dt> <dd> <span id='paramToggle' /> </dd> <div class='auto-complete' id='paramContainer' /> </dl> </td> <td class='last'> <dl class='clsTable'> <dt> <input type='text' id='value' name='value' class='text valueInput' /> </dt> </dl> </td> </tr> </tbody> </table> </div> </div> </div> <!-- tabcontrol --> </fieldset> <div class="submit-box"> <input type="submit" name="formRun" id="formRun" class="form-save" value="Execute" accesskey="x" title="Run: Press Alt + [Shift] + x" /> <input type="submit" name="formSave" id="formSave" value="Save" accesskey="s" title="Save: Press Alt + [Shift] + s" /> <input type="submit" name="formLoad" id="formLoad" value="Load" accesskey="l" title="Load: Press Alt + [Shift] + l" /> <input type="submit" name="formCancel" id="formCancel" class="form-cancel" value="Cancel" accesskey="c" title="Cancel: Press Alt + [Shift] + c" /> </div> </form> </div> </div> </div> </div> </div> </body> </html> ``` As you can see the following is pretty much a duplicate: ``` <tr class='odd'> <td class='rowcheck center first'> <input value='param1###value1' id='cb1' name='SelectedRows' class='grid-select-row' type='checkbox'/> </td> <td class='id'>1</td> <td>param1</td> <td class='last'>value1</td> </tr> <tr class='even'> <td class='rowcheck center first'> <input value='param2###value2' id='cb2' name='SelectedRows' class='grid-select-row' type='checkbox'/> </td> <td class='id'>2</td> <td>param2</td> <td class='last'>value2</td> </tr> ``` The relevant part of my stuts-config.xml file is: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans> <form-bean name="TestCaseForm" type="com.blahblah.mycoolapp.forms.TestCaseForm" /> </form-beans> <action-mappings> <action path="/pages/SaveTestCase" name="TestCaseForm" type="org.springframework.web.struts.DelegatingActionProxy" scope="request"> </action> </action-mappings> <message-resources parameter="MessageResources" /> </struts-config> ``` I also use spring 2.56 (The relevant part being): ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean name="/pages/SaveTestCase" class="com.blahblah.mycoolapp.actions.TestCaseBuilderSaveAction" /> </beans> ``` My Java ActionForm class (from what I had learned off the net) is: ``` package com.blahblah.mycoolapp.forms; import java.util.ArrayList; import java.util.List; import org.apache.struts.action.ActionForm; public class TestCaseForm extends ActionForm { private static final long serialVersionUID = 2352146257739099766L; private String scenario; private String ruleID; private String testCaseName; private List<String> SelectedRows = new ArrayList<String>() ; public String getScenario() { return scenario; } public void setScenario(String scenario) { this.scenario = scenario; } public String getRuleID() { return ruleID; } public void setRuleID(String ruleID) { this.ruleID = ruleID; } public String getTestCaseName() { return testCaseName; } public void setTestCaseName(String testCaseName) { this.testCaseName = testCaseName; } public List<String> getSelectedRows() { return SelectedRows; } public void setSelectedRows(int index, String value) { this.SelectedRows.add(value); } } ``` The question is **why do I get an empty SelectedRows in my TestCaseBuilderSave Action?** Thanks all who have the patience to read such a long question... and (hopefully) thanks to all you potential saviors :) **EDIT 1:** Due to @ahiru's request I post my action class which - for the time being is just a stripped down. almost do nothing, class: ``` public class TestCaseBuilderSaveAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename=superfish.xml"); try { ServletOutputStream out = response.getOutputStream(); String contentStr = "<Yaneeve>Has been here...</Yaneeve>"; byte[] bytes = contentStr.getBytes(); out.write(bytes, 0, bytes.length); out.flush(); out.close(); }catch(Exception e){ e.printStackTrace(); } return null; } } ```
2010/06/16
[ "https://Stackoverflow.com/questions/3053216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/101715/" ]
I don't see any answer considering Grid-Css. I think it is a very elegant approach: grid-css even supports row span and and column spans. Here you can find a very good article: <https://medium.com/@js_tut/css-grid-tutorial-filling-in-the-gaps-c596c9534611>
A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS ``` .common_table{ display:table; border-collapse:collapse; border:1px solid grey; } .common_table DIV{ display:table-row; border:1px solid grey; } .common_table DIV DIV{ display:table-cell; } ``` HTML ``` <DIV class="common_table"> <DIV><DIV>this is a cell</DIV></DIV> <DIV><DIV>this is a cell</DIV></DIV> </DIV> ``` Works on Chrome and Firefox
42,979,447
I can access the same folder and file through FileZilla very easily. Definitely I am doing something wrong, but what ? My code is as below ``` try{ Bitmap bitmap = null; InputStream in; String userpass = "username:password"; String url = "http://veedeesoft.com/httpdocs/RoyalFoods/Products/Large/1.png"; HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); c.setRequestMethod("GET"); c.setDoInput(true); String basicAuth = "Basic " + new String(android.util.Base64.encode(userpass.getBytes(), Base64.DEFAULT)); c.addRequestProperty ("Authorization", basicAuth); c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); c.connect(); int status = c.getResponseCode(); if(status >= HttpStatus.SC_BAD_REQUEST){ in = c.getErrorStream(); }else{ in = c.getInputStream(); } }catch(Exception e){ e.printStackTrace(); } ```
2017/03/23
[ "https://Stackoverflow.com/questions/42979447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/983457/" ]
I think flexbox might help you, check this code: ```css #home{ background: #5F9EA0; border-radius: 25px; margin: auto; width: 200px; height: 100px; display: flex; justify-content: center; align-items: center; font-size: 25px; } ``` ```html <div id = "home"> <span>Home</span> </div> ``` Let me know if this helps you.
You can use the `display:flex` approach to center the text from top and left. ```css #home { background: #5F9EA0; border-radius: 25px; margin: auto; width: 200px; height: 100px; text-align: center; font-size: 25px; display:flex; justify-content:center; align-items:center; } ``` ```html <div id="home">Home</div> ```
45,219,753
I'm trying to add a new activity in my android app and I've got this code for it: ``` public void BSettings() { View.OnClickListener listSet = new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "settings", Toast.LENGTH_LONG).show(); Intent intent= new Intent(MainActivity.this, Settings.class); startActivity(intent); } }; b = (ImageButton) findViewById(R.id.imageButton7); b.setOnClickListener(listSet); } ``` Nevertheless, when clicking the button the app stops. The thing is that, when I only had the `toast`, it worked, so the problem may be the creation of the `intent` or the `startActivity(intent)`. What's wrong with these two lines? In the logcat, this error appears: ``` 07-20 13:44:10.714 1534-1547/? E/ActivityManager: ANR in com.android.systemui PID: 1625 Reason: Broadcast of Intent { act=android.intent.action.TIME_TICK flg=0x50000014 (has extras) } Load: 0.0 / 0.0 / 0.0 CPU usage from 12435ms to 0ms ago (2017-07-20 13:43:57.570 to 2017-07-20 13:44:10.004): 18% 1534/system_server: 13% user + 4.9% kernel / faults: 10451 minor 12 major 5.3% 1625/com.android.systemui: 4.1% user + 1.2% kernel / faults: 5162 minor 8 major 4.5% 1890/adbd: 1.3% user + 3.1% kernel / faults: 587 minor 4.1% 1257/surfaceflinger: 0.4% user + 3.6% kernel / faults: 5 minor 3.1% 1731/com.android.phone: 2.4% user + 0.6% kernel / faults: 1052 minor 1% 1296/zygote: 0.6% user + 0.4% kernel / faults: 1635 minor 0.9% 1196/kworker/0:1H: 0% user + 0.9% kernel 0.6% 1277/kworker/u3:0: 0% user + 0.6% kernel 0.8% 1256/servicemanager: 0.2% user + 0.5% kernel 0.3% 1297/audioserver: 0.2% user + 0.1% kernel 0.2% 1306/netd: 0% user + 0.2% kernel / faults: 922 minor 0.2% 1203/logd: 0% user + 0.2% kernel / faults: 41 minor 0.2% 1279/dmcrypt_write: 0% user + 0.2% kernel 0.2% 1304/media.extractor: 0.2% user + 0% kernel / faults: 16 minor 0.1% 1305/mediaserver: 0.1% user + 0% kernel / faults: 163 minor 0.1% 3/ksoftirqd/0: 0% user + 0.1% kernel 0% 4/kworker/0:0: 0% user + 0% kernel 0.1% 1829/com.android.cellbroadcastreceiver: 0% user + 0% kernel / faults: 126 minor 0% 8/rcu_preempt: 0% user + 0% kernel 0% 1254/lmkd: 0% user + 0% kernel / faults: 1 minor 0% 1284/kworker/u3:1: 0% user + 0% kernel 0% 1290/jbd2/dm-0-8: 0% user + 0% kernel 0% 1298/cameraserver: 0% user + 0% kernel / faults: 126 minor 0% 1744/com.android.settings: 0% user + 0% kernel / faults: 37 minor +0% 1899/com.google.android.gms.persistent: 0% user + 0% kernel +0% 1914/android.process.media: 0% user + 0% kernel +0% 1930/com.google.process.gapps: 0% user + 0% kernel +0% 1943/com.google.android.googlequicksearchbox:interactor: 0% user + 0% kernel +0% 1949/com.android.printspooler: 0% user + 0% kernel +0% 1971/com.android.launcher3: 0% user + 0% kernel +0% 2005/com.google.android.googlequicksearchbox:search: 0% user + 0% kernel +0% 2073/logcat: 0% user + 0% kernel +0% 2084/com.google.android.partnersetup: 0% user + 0% kernel +0% 2136/android.process.acore: 0% user + 0% kernel +0% 2160/com.android.keychain: 0% user + 0% kernel 100% TOTAL: 61% user + 26% kernel + 10% iowait + 1.2% softirq CPU usage from 54628ms to 54628ms ago (1970-01-01 00:00:00.000 to 1970-01-01 00:00:00.000) with 0% awake: ``` **EDIT** After adding the activity to the manifest, it launche the activity, but after showing the new window, it stops. Tis is Settings code: ``` public class Settings extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set); } } ``` set code: ``` <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/holo_green_dark" android:minHeight="?attr/actionBarSize" android:visibility="visible" > <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/toolbar" android:layout_gravity="center" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" /> </android.support.v7.widget.Toolbar> <ImageButton android:id="@+id/back" android:layout_width="61dp" android:layout_height="56dp" app:srcCompat="?attr/actionModeCloseDrawable" tools:backgroundTint="@android:color/holo_green_dark" tools:ignore="ContentDescription" /> <LinearLayout android:layout_width="360dp" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="1"> <TextView android:id="@+id/Configuración" android:layout_width="384dp" android:layout_height="wrap_content" android:layout_weight="0.48" android:ems="10" android:inputType="textPersonName" android:textAlignment="center" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" tools:ignore="TextViewEdits" /> <RelativeLayout android:id="@+id/AutoLayout" android:layout_width="wrap_content" android:layout_height="77dp"> <TextView android:id="@+id/auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginLeft="24dp" android:layout_marginStart="24dp" android:ems="10" android:inputType="textPersonName" android:text="@string/titulo1" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" tools:ignore="TextViewEdits" /> <TextView android:id="@+id/textView9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/autoarranuqe" android:layout_toLeftOf="@+id/interruptor" android:layout_toStartOf="@+id/interruptor" android:text="@string/text1" android:textAlignment="center" /> <Switch android:id="@+id/int" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:checked="false" android:textCursorDrawable="@android:color/holo_red_dark" tools:checked="false" /> </RelativeLayout> <RelativeLayout android:id="@+id/WIFILayout" android:layout_width="match_parent" android:layout_height="77dp"> <TextView android:id="@+id/editText16" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginLeft="22dp" android:layout_marginStart="22dp" android:ems="10" android:inputType="textPersonName" android:text="@string/t2" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" tools:ignore="TextViewEdits" /> <TextView android:id="@+id/Wifi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentStart="true" android:layout_below="@+id/editText16" android:text="TextView" android:textAlignment="center" tools:text="@string/texto2" tools:ignore="HardcodedText" /> </RelativeLayout> <RelativeLayout android:id="@+id/PlayerIDLayout" android:layout_width="match_parent" android:layout_height="103dp" android:layout_weight="0.13"> <EditText android:id="@+id/playerID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/gr" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:text="@string/texto3" android:textColor="?android:attr/textColorTertiary" android:textStyle="italic" android:inputType="" /> <TextView android:id="@+id/editText17" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginLeft="27dp" android:layout_marginStart="27dp" android:ems="10" android:inputType="textPersonName" android:text="@string/t3" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" tools:ignore="TextViewEdits" /> <Button android:id="@+id/gr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_below="@+id/editText17" android:background="@android:color/holo_green_dark" android:text="@string/bot1" android:textColor="@android:color/background_light" /> <Button android:id="@+id/br" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/gr" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignStart="@+id/gr" android:layout_below="@+id/gr" android:text="@string/bot2" /> </RelativeLayout> <RelativeLayout android:id="@+id/ILayout" android:layout_width="match_parent" android:layout_height="130dp" android:layout_weight="0.57"> <RadioGroup android:id="@+id/radio" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:weightSum="1" tools:ignore="UselessParent"> <TextView android:id="@+id/textView14" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/t0" android:textAlignment="center" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" /> <RadioButton android:id="@+id/Fra " android:layout_width="wrap_content" android:layout_height="54dp" android:checked="false" tools:text="@string/tex" /> <RadioButton android:id="@+id/En" android:layout_width="wrap_content" android:layout_height="44dp" android:checked="true" tools:text="@string/texto5" android:layout_weight="0.17" /> <RadioButton android:id="@+id/Es" android:layout_width="wrap_content" android:layout_height="48dp" android:layout_weight="0.41" android:checked="true" tools:text="@string/text4" /> </RadioGroup> </RelativeLayout> </LinearLayout> </FrameLayout> ```
2017/07/20
[ "https://Stackoverflow.com/questions/45219753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8236050/" ]
My problem was that, for some reason, my envioroment.ts file was missing. So check important files.
Could be bad path to component templateUrl, perhaps missing the `./` Before: `templateUrl: 'my-control.component.html',` After: `templateUrl: './my-control.component.html',`
42,317,927
I have an Excel VBA formula:- ``` If [G56] = "Not Applicable" Then ... ``` It is case-sensitive. I want it to ignore the case of "Not applicable".
2017/02/18
[ "https://Stackoverflow.com/questions/42317927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6845519/" ]
You can just use the LCase function: ``` If LCase([G56]) = "not applicable" Then ```
Fastest option would be ``` StrComp(LCase$("Not Applicable"), "not applicable", vbBinaryCompare) ```
62,543,909
I'm trying to install Regex on macos catalina, but I'm getting this error, how do I proceed? I tried to update `pip`, `pip3`, `pipwin`, `xcode`, but both return the same error, the same happens when I install NLTK. I was able to install on a ubuntu VM and installed everything, REGEX and NLTK, only on MacOs that I continue with this error below: ```none pip3 install regex Collecting regex Using cached regex-2020.6.8.tar.gz (690 kB) Building wheels for collected packages: regex Building wheel for regex (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/local/opt/python/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/setup.py'"'"'; __file__='"'"'/private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-wheel-j6dr4ocd cwd: /private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/ Complete output (17 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-x86_64-3.7 creating build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/__init__.py -> build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/regex.py -> build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/_regex_core.py -> build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/test_regex.py -> build/lib.macosx-10.14-x86_64-3.7/regex running build_ext building 'regex._regex' extension creating build/temp.macosx-10.14-x86_64-3.7 creating build/temp.macosx-10.14-x86_64-3.7/regex_3 clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c regex_3/_regex.c -o build/temp.macosx-10.14-x86_64-3.7/regex_3/_regex.o xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: command 'clang' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for regex Running setup.py clean for regex Failed to build regex Installing collected packages: regex Running setup.py install for regex ... error ERROR: Command errored out with exit status 1: command: /usr/local/opt/python/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/setup.py'"'"'; __file__='"'"'/private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-record-olfcxoeu/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.7m/regex cwd: /private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/ Complete output (17 lines): running install running build running build_py creating build creating build/lib.macosx-10.14-x86_64-3.7 creating build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/__init__.py -> build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/regex.py -> build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/_regex_core.py -> build/lib.macosx-10.14-x86_64-3.7/regex copying regex_3/test_regex.py -> build/lib.macosx-10.14-x86_64-3.7/regex running build_ext building 'regex._regex' extension creating build/temp.macosx-10.14-x86_64-3.7 creating build/temp.macosx-10.14-x86_64-3.7/regex_3 clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c regex_3/_regex.c -o build/temp.macosx-10.14-x86_64-3.7/regex_3/_regex.o xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: command 'clang' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /usr/local/opt/python/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/setup.py'"'"'; __file__='"'"'/private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-install-fzw0lg0t/regex/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/6h/wf23bbbj7t7dwhyzz0cjw3_r0000gn/T/pip-record-olfcxoeu/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.7m/regex Check the logs for full command output.**strong text** ```
2020/06/23
[ "https://Stackoverflow.com/questions/62543909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13035301/" ]
I am no mac super user but you could try this and check if it works. `xcode-select --install` If it says it's already installed try: `xcode-select --reset` The reason I believe it might be the issue is cause of the xcrun error that is occurring.
The underlying error seems to be: ``` invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun` ``` You can most likely solve this by installing the command line tools: ``` xcode-select --install ``` See <https://apple.stackexchange.com/questions/254380/why-am-i-getting-an-invalid-active-developer-path-when-attempting-to-use-git-a> for more details.
106,647
I need to refresh a link every 5 minutes, how to schedule cron for refreshing the url
2016/03/17
[ "https://magento.stackexchange.com/questions/106647", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/32935/" ]
Tow way to set cron : **1) cpanel cron set** ``` GoTo Cpanel->corn job setting -> set file path. ``` **2) Using magento . you have to create module .** app/etc/modules/Compnyname\_ModuleName.xml ``` <?xml version="1.0"?> <config> <modules> <Compnyname_ModuleName> <active>true</active> <codePool>local</codePool> <version>0.1.0</version> </Compnyname_ModuleName> </modules> </config> ``` app/code/local/Compnyname/ModuleName/etc/config.xml ``` <?xml version="1.0"?> <config> <modules> <Compnyname_ModuleName> <version>0.1.0</version> </Compnyname_ModuleName> </modules> <global> <helpers> <modulename> <class>Compnyname_ModuleName_Helper</class> </modulename> </helpers> <models> <modulename> <class>Compnyname_ModuleName_Model</class> <resourceModel>modulename_mysql4</resourceModel> </modulename> </models> </global> <crontab> <jobs> <modulename_cornmethodname> <schedule><cron_expr>*/5 * * * *</cron_expr></schedule> <run><model>modulename/cron::cornmethodname</model></run> </modulename_cornmethodname> </jobs> </crontab> </config> ``` **`<cron_expr>set time setting as you want</cron_expr>`** app/code/local/Compnyname/ModuleName/Helper/Data.php ``` <?php class Compnyname_ModuleName_Helper_Data extends Mage_Core_Helper_Abstract { } ``` app/code/local/Compnyname/ModuleName/Model/Cron.php ``` <?php class Compnyname_ModuleName_Model_Cron{ public function cornmethodname(){ //do something } } ``` Set your cron code in Cron.php.
you just point it to your file or page: ``` */5 * * * * curl --silent "http://example.come/some/page" >/dev/null 2>&1 ```
15,610,003
I have a space ship in a canvas. It has velocities, `ship.vx` and `ship.vy`. When it's 30px away from the canvas borders I set `ship.vx` & `ship.vy` to `0` and move the background objects in ship's opposite direction. At this moment the ship is stuck at a point. That's all good. Now if I try to move it left-right(`stuck at top/bottom`) or top-down(`stuck at left/right`) it doesn't since it is stuck in the point where `vx` & `vy` are set to `0`. If i accelerate in it's opposite direction it takes like 5 seconds to pick it's velocity (around 2), so it's basically at the same point for 5 seconds. I tried not to set `vy` to `0` when out of x-axis and vice-versa but the ship keeps moving slowly in the other axis. So what i'm trying to achieve is the ship'll get stuck when it's 30 px from border, but if i try to move or accelerate in other 3 directions it'll pretend as if it's not stuck. Any of you know any mechanisms? Thanks. ``` function stuckShip(){ if( (ship.x - ship.width < 0) || (ship.x + ship.width > w) || (ship.y + ship.height > h) || (ship.y - ship.height < 0)) { ship.vx = 0; ship.vy = 0; } } function againAndAgain(){ var angle = ship.rotation; var x = Math.cos(angle); var y = Math.sin(angle); var ax = x*thrust, ay = y*thrust; ship.vx += ax; ship.vy += ay; stuckShip(); ship.draw(context); } document.addEventListener('keydown', function(e){ switch(e.keyCode){ case 38: thrust = 0.35; break; case 37: ship.rotation -= 3; break; case 39: ship.rotation += 3; break; } } ```
2013/03/25
[ "https://Stackoverflow.com/questions/15610003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370508/" ]
I think `split` will do the job for you. ``` DF <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L, 10L), Item = c(" Sixth Sense", " LOTR1", " Harry Potter1", " Green Mile", " LOTR2", " Gladiator", " Patriot", " Braveheart", " LOTR1", " LOTR2", " Gladiator", " Patriot", " Sixth Sense", " Gladiator", " Patriot", " Sixth Sense", " Gladiator", " Patriot", " Sixth Sense", " Harry Potter1", " Harry Potter2", " Gladiator", " Patriot", " Gladiator", " Patriot", " Sixth Sense", " Sixth Sense", " LOTR", " Galdiator", " Green Mile" )), .Names = c("ID", "Item"), class = "data.frame", row.names = c(NA, -30L)) DF <- read.csv(textConnection(txt), header = TRUE, stringsAsFactors = FALSE, strip.white = TRUE) result <- split(DF$Item, DF$ID) names(result) <- gsub("(.*)", "TR\\1", names(result)) result ## $TR1 ## [1] "Sixth Sense" "LOTR1" "Harry Potter1" "Green Mile" "LOTR2" ## ## $TR2 ## [1] "Gladiator" "Patriot" "Braveheart" ## ## $TR3 ## [1] "LOTR1" "LOTR2" ## ## $TR4 ## [1] "Gladiator" "Patriot" "Sixth Sense" ## ## $TR5 ## [1] "Gladiator" "Patriot" "Sixth Sense" ## ## $TR6 ## [1] "Gladiator" "Patriot" "Sixth Sense" ## ## $TR7 ## [1] "Harry Potter1" "Harry Potter2" ## ## $TR8 ## [1] "Gladiator" "Patriot" ## ## $TR9 ## [1] "Gladiator" "Patriot" "Sixth Sense" ## ## $TR10 ## [1] "Sixth Sense" "LOTR" "Galdiator" "Green Mile" ```
Your `aggregate` command could work, but you didn't specify the arguments correctly. You would need something like: `with(DF, aggregate(Item, list(ID), FUN = function(x) c(as.character(x))))`. Alternatively, you can use the formula method for `aggregate`: ``` aggregate(Item ~ ID, DF, c) # ID Item # 1 1 Sixth Sense, LOTR1, Harry Potter1, Green Mile, LOTR2 # 2 10 Sixth Sense, LOTR, Galdiator, Green Mile # 3 2 Gladiator, Patriot, Braveheart # 4 3 LOTR1, LOTR2 # 5 4 Gladiator, Patriot, Sixth Sense # 6 5 Gladiator, Patriot, Sixth Sense # 7 6 Gladiator, Patriot, Sixth Sense # 8 7 Harry Potter1, Harry Potter2 # 9 8 Gladiator, Patriot # 10 9 Gladiator, Patriot, Sixth Sense str(.Last.value) # 'data.frame': 10 obs. of 2 variables: # $ ID : chr "1" "10" "2" "3" ... # $ Item:List of 10 # ..$ 1 : chr "Sixth Sense" "LOTR1" "Harry Potter1" "Green Mile" ... # ..$ 6 : chr "Sixth Sense" "LOTR" "Galdiator" "Green Mile" # ..$ 10: chr "Gladiator" "Patriot" "Braveheart" # ..$ 13: chr "LOTR1" "LOTR2" # ..$ 15: chr "Gladiator" "Patriot" "Sixth Sense" # ..$ 18: chr "Gladiator" "Patriot" "Sixth Sense" # ..$ 21: chr "Gladiator" "Patriot" "Sixth Sense" # ..$ 24: chr "Harry Potter1" "Harry Potter2" # ..$ 26: chr "Gladiator" "Patriot" # ..$ 28: chr "Gladiator" "Patriot" "Sixth Sense" ``` Or, you can use the "data.table" package: ``` library(data.table) as.data.table(DF)[, list(list(Item)), by = ID] # ID V1 # 1: 1 Sixth Sense,LOTR1,Harry Potter1,Green Mile,LOTR2 # 2: 2 Gladiator,Patriot,Braveheart # 3: 3 LOTR1,LOTR2 # 4: 4 Gladiator,Patriot,Sixth Sense # 5: 5 Gladiator,Patriot,Sixth Sense # 6: 6 Gladiator,Patriot,Sixth Sense # 7: 7 Harry Potter1,Harry Potter2 # 8: 8 Gladiator,Patriot # 9: 9 Gladiator,Patriot,Sixth Sense # 10: 10 Sixth Sense,LOTR,Galdiator,Green Mile ```
394
[serial](https://electronics.stackexchange.com/questions/tagged/serial "show questions tagged 'serial'") is fairly broad (what isn't serial nowadays...), and most of the current tags are really referring to UARTs ([uart](https://electronics.stackexchange.com/questions/tagged/uart "show questions tagged 'uart'")), but a (scant) few questions are using it more generally. Cleanup from that rename would be pretty easy, but probably more annoying would be the maintenance burden it places on the site, as naive most Arduino users will just tag [serial](https://electronics.stackexchange.com/questions/tagged/serial "show questions tagged 'serial'") and probably not know what a UART is, so it will need to be fixed again, and again, and again... Or we could leave it as is...but that hurts me inside.
2011/02/05
[ "https://electronics.meta.stackexchange.com/questions/394", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/1407/" ]
I think the problem is more complicated than that. For example, you can have: * Asynchronous Serial + logic level + RS232 + RS485 - CAN bus * Synchronous Serial + SPI + I2C * High-speed Serial + USB + Digital Video And this is not a complete list. I don't like the idea of using UART as a tag for all traditional asynchronous serial topics. To extend your perl analogy, it would be like tagging all perl questions [perl.exe] instead of [perl]. Most people, when they say they are using a serial connection, are using a logic level (0-3.3/5V) asynchronous serial protocol: 8 data bits, no parity, and one stop bit (8N1). I think a better retagging target would be [asynchronous-serial], but that's still a bit amorphous and vague. The other problem is that manufacturers start adding additional letters to the "UART", twisting the meaning of the tag. I've seen things like USARTs and EUSARTs, which have replaced the simple traditional UART. Manufacturers like these extended functionality ports because they support so many protocols - extending way beyond the original connotation of UART.
For me as a beginner serial is very common but uart is not.
69,962,211
I want to get data in parallel. I found an example to call API in parallel but I want to store `async let variables` with loop. Async let example. However, this example doesn't use a loop. ```swift async let firstPhoto = downloadPhoto(named: photoNames[0]) async let secondPhoto = downloadPhoto(named: photoNames[1]) async let thirdPhoto = downloadPhoto(named: photoNames[2]) let photos = await [firstPhoto, secondPhoto, thirdPhoto] show(photos) ``` I want to do something like the following. ```swift let items = photoNames.map({ photo in async let item = downloadPhoto(named: photo) return item }) let photos = await items show(photos) ```
2021/11/14
[ "https://Stackoverflow.com/questions/69962211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7359831/" ]
You can use a task group. See [Tasks and Task Groups](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID642) section of the *The Swift Programming Language: Concurrency* (which would appear to be where you got your example). One can use [`withTaskGroup(of:returning:body:)`](https://developer.apple.com/documentation/swift/3814991-withtaskgroup/) to create a task group to run tasks in parallel, but then collate all the results together at the end. E.g. here is an example that creates child tasks that return a tuple of “name” and ”image”, and the group returns a combined dictionary of those name strings with their associated image values: ``` func downloadImages(names: [String]) async -> [String: UIImage] { await withTaskGroup( of: (String, UIImage).self, returning: [String: UIImage].self ) { [self] group in for name in names { group.addTask { await (name, downloadPhoto(named: name)) } } var images: [String: UIImage] = [:] for await result in group { images[result.0] = result.1 } return images } } ``` Or, more concisely: ```swift func downloadImages(names: [String]) async -> [String: UIImage] { await withTaskGroup(of: (String, UIImage).self) { [self] group in for name in names { group.addTask { await (name, downloadPhoto(named: name)) } } return await group.reduce(into: [:]) { $0[$1.0] = $1.1 } } } ``` They run in parallel: [![enter image description here](https://i.stack.imgur.com/sBBVi.png)](https://i.stack.imgur.com/sBBVi.png) But you can extract them from the dictionary of results: ```swift let stooges = ["moe", "larry", "curly"] let images = await downloadImages(names: stooges) imageView1.image = images["moe"] imageView2.image = images["larry"] imageView3.image = images["curly"] ``` --- Or if you want an array sorted in the original order, just build an array from the dictionary: ```swift func downloadImages(names: [String]) async -> [UIImage] { await withTaskGroup(of: (String, UIImage).self) { [self] group in for name in names { group.addTask { await (name, downloadPhoto(named: name)) } } let dictionary = await group.reduce(into: [:]) { $0[$1.0] = $1.1 } return names.compactMap { dictionary[$0] } } } ```
If the order of result doesn't matter here, use a `TaskGroup` instead.
91,082
Two weeks ago I've started taking singing lessons to learn the proper technique and improve the extension. The teacher gave me 2-3 exercises to do at home that are involved with correct breathing (like standing in front of a mirror, inhale profoundly, feel the ribs/stomach widen and then exhale producing a constant "S" sounds, or also saying number for as long I have breath). Other than this, we started to study a song this way: she made me mark on the lyrics where the singer takes a breath so that I have visual assistance to do the same, and sing the song in pieces by taking a deep breath with my mouth every time the singer does that, so that I can learn step by step how to breath correctly during a song. So the problem is that after studying I always feel a little itchy in the throat, nothing really painful, but it's bothering because it's clear that I'm doing something wrong and I don't want to ruin my voice. I'm gonna see the teacher again only next month due to work stuff, but until then I want to keep practicing but I'm scared how to handle this. I can tell I'm breathing correctly at least for the inhaling part, feeling the stomach and ribs opening; I've seen few videos explaining how to breath and I've seen I was breathing correctly, so I'm afraid there's something wrong in the way I exhale, could it be? That maybe I still push somehow with my throat and not just let the air flow out? Maybe not pushing with the lungs/diaphragm? How can I prevent this from happening?
2019/10/22
[ "https://music.stackexchange.com/questions/91082", "https://music.stackexchange.com", "https://music.stackexchange.com/users/63963/" ]
I've determined the actual notes: [![Key of d minor](https://i.stack.imgur.com/FOIWf.png)](https://i.stack.imgur.com/FOIWf.png) The middle voice is the main melody. I'm not aware of any formal name for this kind of harmony, but it is certainly dissonant. I agree with PeterJ in that the harmonies are likely a result of lucky accidents. Regardless, each voice moves in a descending manner. Edit: As Rose F pointed out, the two Gs on “your re-“ are actually G#/Ab
I'm not at an instrument now to check, but it sounds like harmony in thirds going down chromatically. It also sounds like an electronic effect. It sounds artificial and that gives it a sort of weirdness. At least for me. Harmonizer effects put me off. They don't have the warmth of real harmonizing. A kind of [uncanniness](https://en.wikipedia.org/wiki/Uncanny_valley). This may account for the 'out of tune' sense you get.
529,088
Notice the following code. The offending line has been commented out. ``` interface I<R> { } class C : I<int> { } class Program { private static void function<T, R>(T t) where T : class, I<R> { } static void Main(string[] args) { // function(new C()); // wont compile function<C, int>(new C()); } } ``` I believe type inference should figure out the type because the argument `T` provides the first type, while `I<R>` provides the second type. Is there a way to redesign the function so that the callers may not have to specify the types?
2009/02/09
[ "https://Stackoverflow.com/questions/529088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9178/" ]
``` class D : I<int>, I<string> { } // function<D, int>(new D()); function<D, string>(new D()); //is R int or string? function(new D()); ```
C# does not support this kind of type inference. Consider this case which adds a bit of ambiguity to the problem. ``` class Other : I<int>, I<Student>{ ... } void Example(){ function(new D()); } ``` In this case there is an ambiguity as to which I should be chosen. If you look forward to C# 4.0 the problem only increases with the new variance features they are adding.
50,327
I am creating an animated logo for my web site. It is a simple 2 frame gif. The only difference between the 2 frames is that the first one has a glowing object and the second one doesn't. Here's [the first frame](https://imgur.com/g5Xu2Gr). Now, after hitting save for web, I choose not to use matte because the background color I am using on the website is a gradient. And that creates [this ugly thing](https://imgur.com/KTdxhx7). As I said before, I can't just use matte because my website's background color is a grey and black gradient. Is there anything I can do? I need this logo to be clean without lines and it needs to fit the gradient on my website.
2015/03/28
[ "https://graphicdesign.stackexchange.com/questions/50327", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/41479/" ]
`.gif` does not support alpha transparency, that is the reason for the “line” around your logo. The easiest way would be to include the gradient in the background. The only problem would be a dynamicly changing background. To get alpha transparency on the web is using a `.png`, which does not support animations. But since you only have two frames, you can simulate the animation with a simple CSS or JS Animation.
As Afterlame suggests, the best solution to your problem is either: 1. Include the gradient in your image so that it can render the half opacity drop shadow that you're looking for. OR 2. Simulate your animation through CSS or JS. This is the vastly superior option, as it gives you complete control over your situation. You won't have to edit a gif, or any difficult, framed resource like that. You can simply create two static images and toggle them back and forth, even apply nifty animations and transitions. This is definitely the way to go in this case. An example would be to have a DIV with a background of your first picture, and then put the second frame as an IMG inside of it. Using css/js, simply fade the enclosed IMG in and out to achieve the effect you're looking for.
330
I am running a forum with a very young user group (primarily 9-17 years old) and there are some users that are simply overusing my community: Some of them are online all day, every day. While I appreciate their interest in my community and know that they found friends in there I am concerned about their real life. Staying online all day cannot be good for their real life, health and school grades. Note that the community is located in Europe, I am not affected by COPPA and the parents do not necessarily know about their membership. Should I do something against this or is this none of my business and their parents should keep an eye on them?
2014/07/30
[ "https://moderators.stackexchange.com/questions/330", "https://moderators.stackexchange.com", "https://moderators.stackexchange.com/users/15/" ]
I don't think it's something you should have to, or even want to, worry about. You are only responsible for your forum, why would you want the added responsibility of trying to raise someone else's kids? Most likely any restrictions you place will have adverse effects. I see one of two things happening: 1. They'll start to lie about their ages to get around the rules. 2. They'll start to leave in favor of a forum that doesn't restrict their use. It's also important to remember that in today's age, everyone has multiple devices that allow them to stay connected no matter where they are. Smartphones especially, allow people to stay connected to their favorite sites and forums no matter where they are. Sometimes I'll still appear to be connected just because I've left my computer open when I left the house. It's possible that they always seem online because they're connected through a phone or tablet, and they aren't actually devoting their entire time to the forum.
I would say that you won't have to concern your self with this, as these people may have a good reason to be online all day * Either they are doing what is known as homeschooling, and hence have more time being online (not that homeschooling gives a person such time) * They may have some break from school Other then this, this should be the parents responsibility to deal with them, that is assuming the person isn't old enough to be responsible themselves. but if you are truly concerned about this, then you can always specify from which hour to which hour your forum is open, since your user base is young, you most likely control the content (no adult content), so like that I suggest you somehow control the time the forum is open.
11,641,224
I'm working with MVC 3 and have an issue. Instead of giving mydomain/mydirectory/item like I expected I get this: mydomain/mydirectory/list?animal=quack. Here's the route in the global ``` //Default route mapping routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new { controller = @"[^\.]*", action = @"[^\.]*" } ); ``` Code showing how I'm building the link: > > > ``` > <div id="main-content" title="AnimalBox" style="float:none;"> > <% Html.DataList(Model.PriceListAnimals).Columns(7).Item(item => > { > item.Template(galleryImage => > {%> > <div style="margin-left:20px; line-height:150%;"> > <span><%= Html.ActionLink(galleryImage.AnimalName,"List",new { @animal = galleryImage.AnimalName }) %></span> > </div> > <% }); > }).Render(); %> > </div> > > ``` > > Any ideas?
2012/07/25
[ "https://Stackoverflow.com/questions/11641224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88230/" ]
It's the close the definition of the anonymous implementation of `View.OnClickListener` and then to close the method call `setOnClickListener()`. To make it more clear, the code is equivalent to: ``` View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) { if (((CheckBox)v).isChecked()) DisplayToast("CheckBox is checked"); else DisplayToast("CheckBox is unchecked"); } }; checkBox.setOnClickListener(listener); ```
It closes the setOnClickListener . TIP if you are using eclipse set your cursor to the right of the closed bracket.The open bracket will than be highlighted so you can see what's what.
659,650
I need to get a stack trace for a JVM process running on a client machine that uses windows. The client has the JRE installed but not the JDK. I want to use JStack but it is not installed and we can't install a JDK on the client's machine. I also tried using AdaptJ stack trace product from a Java Webstart Session but that didn't work because we remote in and get an error about not being the session that started the application at a specified PID. Essentially I want a way to install JStack without installing the JDK.
2009/03/18
[ "https://Stackoverflow.com/questions/659650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47508/" ]
The JDK and associated tools work fine whether "installed" or not, if you just zip up and extract it to a temporary directory, you should be able to run jstack. (No PATH or JAVA\_HOME modifications necessary). Just make sure you use the same version that corresponds to the JRE your client has the application running with. At least in the case of JConsole, it seems to fuss if the versions are different. I'm not sure if jstack behaves the same way. I'm not saying this is the ideal solution, just that it would work. I think jdigital and Eddie's suggestions are better first bets, and even though this shouldn't interfere with an existing java installation the same way running the installer would, the customer may disagree regardless.
To get a thread dump with only a JRE you need tools.jar and attach.dll from the JDK of the same Java version. Install this somewhere and copy these into the jre. Must be identical version! If you need a dump of a process running under the system account you can use the Windows sysinternals psexec.exe to gain access to the process. Copy this into the JRE bin or somewhere in the path. This batch file writes the stack dump to a file with a datetime filename so multiple traces can be taken and compared easily. Threads.bat ``` :: Creates a thread dump for the tomcat6.exe process :: saved in a timestamped filename and views it! :: Jim Birch 20111128 rev 2015-10-12 ::Required the following files to be placed in the jre/bin folder: :: attach.dll - From the Java JDK (must be the same version) :: tools.jar - ditto :: psexec.exe - from Windows sysinternals ::cd to jre/bin d: cd \application\jre\bin ::build datetime filename rem datetime from wmi.exe for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set dt0=%%I rem datetime string as YYYY-MM-DD-hhmmss set dt=%dt0:~0,4%-%dt0:~4,2%-%dt0:~6,2%-%dt0:~8,6% set ff=td-%dt%.txt echo filename: %ff% ::PID of the process by named exe, eg, tomcat6 for /F "tokens=2" %%I in ('TASKLIST /NH /FI "IMAGENAME eq tomcat6.exe"' ) DO SET PID=%%I echo pid: %PID% ::combine above with jstack command psexec -s jstack.exe -l %PID% >> %ff% :: view result start %ff% ::insert pause to debug or timer to review script operation ::ping localhost -n 20 >nul ::pause ```
2,265,912
I need help figuring out my mistake. Proof. Proving by contradiction that $\sqrt{\frac{1}{2}}$ is irrational. Suppose $\sqrt{\frac{1}{2}}$ is rational so: $\sqrt{\frac{1}{2}}=\frac{m}{n}$. Where $m/n$ are in lowest terms. Squaring both sides and solving for $n$ we have $n^{2}=2m^{2}$. So $n^2$ is even therefore $n$ is also even therefore $n=2k$ and $n^{2}=4k^{2}$. Now, replacing $n^2$ in $n^{2}=2m^{2}$, we have $4k^{2}=2m^{2}$. Which means $m$ is also even. So we are left with an even numerator and an even denominator which contradicts the initial assumption that m/n are in lowest terms. Therefore $\sqrt{\frac{1}{2}}$ is irrational. (which we know is wrong)
2017/05/04
[ "https://math.stackexchange.com/questions/2265912", "https://math.stackexchange.com", "https://math.stackexchange.com/users/368481/" ]
$$\sqrt { \frac 12 }=\frac{1}{\sqrt2}=\frac{1}{\sqrt2} \times \frac{\sqrt2}{\sqrt2}=\frac{\color{red}{ \sqrt{2}} ~(\text{Irrational)}}{2~(\text{Rational)}} :=~~~\text{Is Irrational}$$
Your proof is actually correct. We know$\sqrt{\frac12} = \frac{1}{\sqrt{2}}$. So, if we prove $\frac{1}{\sqrt{2}}$ is irrational, then so is $\sqrt{\frac12}$ since they are equal. Let $\sqrt{2} = \frac{m}{n}$. So that means $\frac{1}{\sqrt{2}} = \frac{n}{m}$. However, we know that $\sqrt{2}$ is irrational thus there is no $m,n$ such that $\sqrt{2} = \frac{m}{n}$. Since there is no such $m,n$, that means there are no solutions to $\frac{1}{\sqrt{2}} = \frac{n}{m}$, either. Thus, $\frac{1}{\sqrt{2}}$ is irrational, so your proof is actually fine, since there was no error in your logic and conclusion was correct.
1,842,681
I'm looking for a regular expression to remove a single parameter from a query string, and I want to do it in a single regular expression if possible. Say I want to remove the `foo` parameter. Right now I use this: ``` /&?foo\=[^&]+/ ``` That works as long as `foo` is not the first parameter in the query string. If it is, then my new query string starts with an ampersand. (For example, "`foo=123&bar=456`" gives a result of "`&bar=456`".) Right now, I'm just checking after the regex if the query string starts with ampersand, and chopping it off if it does. Example edge cases: ``` Input | Expected Output -------------------------+-------------------- foo=123 | (empty string) foo=123&bar=456 | bar=456 bar=456&foo=123 | bar=456 abc=789&foo=123&bar=456 | abc=789&bar=456 ``` --- ### Edit OK as pointed out in comments there are there are way more edge cases than I originally considered. I got the following regex to work with all of them: ``` /&foo(\=[^&]*)?(?=&|$)|^foo(\=[^&]*)?(&|$)/ ``` This is modified from [Mark Byers's answer](https://stackoverflow.com/questions/1842681/regular-expression-to-remove-one-parameter-from-query-string/1842787#1842787), which is why I'm accepting that one, but Roger Pate's input helped a lot too. Here is the full suite of test cases I'm using, and a Javascript snippet which tests them: ```js $(function() { var regex = /&foo(\=[^&]*)?(?=&|$)|^foo(\=[^&]*)?(&|$)/; var escapeHtml = function (str) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return str.replace(/[&<>"']/g, function(m) { return map[m]; }); }; //test cases var tests = [ 'foo' , 'foo&bar=456' , 'bar=456&foo' , 'abc=789&foo&bar=456' ,'foo=' , 'foo=&bar=456' , 'bar=456&foo=' , 'abc=789&foo=&bar=456' ,'foo=123' , 'foo=123&bar=456' , 'bar=456&foo=123' , 'abc=789&foo=123&bar=456' ,'xfoo' , 'xfoo&bar=456' , 'bar=456&xfoo' , 'abc=789&xfoo&bar=456' ,'xfoo=' , 'xfoo=&bar=456' , 'bar=456&xfoo=' , 'abc=789&xfoo=&bar=456' ,'xfoo=123', 'xfoo=123&bar=456', 'bar=456&xfoo=123', 'abc=789&xfoo=123&bar=456' ,'foox' , 'foox&bar=456' , 'bar=456&foox' , 'abc=789&foox&bar=456' ,'foox=' , 'foox=&bar=456' , 'bar=456&foox=' , 'abc=789&foox=&bar=456' ,'foox=123', 'foox=123&bar=456', 'bar=456&foox=123', 'abc=789&foox=123&bar=456' ]; //expected results var expected = [ '' , 'bar=456' , 'bar=456' , 'abc=789&bar=456' ,'' , 'bar=456' , 'bar=456' , 'abc=789&bar=456' ,'' , 'bar=456' , 'bar=456' , 'abc=789&bar=456' ,'xfoo' , 'xfoo&bar=456' , 'bar=456&xfoo' , 'abc=789&xfoo&bar=456' ,'xfoo=' , 'xfoo=&bar=456' , 'bar=456&xfoo=' , 'abc=789&xfoo=&bar=456' ,'xfoo=123', 'xfoo=123&bar=456', 'bar=456&xfoo=123', 'abc=789&xfoo=123&bar=456' ,'foox' , 'foox&bar=456' , 'bar=456&foox' , 'abc=789&foox&bar=456' ,'foox=' , 'foox=&bar=456' , 'bar=456&foox=' , 'abc=789&foox=&bar=456' ,'foox=123', 'foox=123&bar=456', 'bar=456&foox=123', 'abc=789&foox=123&bar=456' ]; for(var i = 0; i < tests.length; i++) { var output = tests[i].replace(regex, ''); var success = (output == expected[i]); $('#output').append( '<tr class="' + (success ? 'passed' : 'failed') + '">' + '<td>' + (success ? 'PASS' : 'FAIL') + '</td>' + '<td>' + escapeHtml(tests[i]) + '</td>' + '<td>' + escapeHtml(output) + '</td>' + '<td>' + escapeHtml(expected[i]) + '</td>' + '</tr>' ); } }); ``` ```css #output { border-collapse: collapse; } #output tr.passed { background-color: #af8; } #output tr.failed { background-color: #fc8; } #output td, #output th { border: 1px solid black; padding: 2px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="output"> <tr> <th>Succ?</th> <th>Input</th> <th>Output</th> <th>Expected</th> </tr> </table> ```
2009/12/03
[ "https://Stackoverflow.com/questions/1842681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
Having a query string that starts with `&` is harmless--why not leave it that way? In any case, I suggest that you search for the trailing ampersand and use `\b` to match the beginning of foo w/o taking in a previous character: ``` /\bfoo\=[^&]+&?/ ```
It's a bit silly but I started trying to solve this with a regexp and wanted to finally get it working :) ``` $str[] = 'foo=123'; $str[] = 'foo=123&bar=456'; $str[] = 'bar=456&foo=123'; $str[] = 'abc=789&foo=123&bar=456'; foreach ($str as $string) { echo preg_replace('#(?:^|\b)(&?)foo=[^&]+(&?)#e', "'$1'=='&' && '$2'=='&' ? '&' : ''", $string), "\n"; } ``` the replace part is messed up because apparently it gets confused if the captured characters are `'&'`s Also, it **doesn't** match `afoo` and the like.
27,195
I just seeded a pomegranate, and instead of red / deep pink seeds, the seeds are pale pink / white. What does this mean? Are they ok to eat?
2012/09/16
[ "https://cooking.stackexchange.com/questions/27195", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/4853/" ]
Got pomegranate with pale pink/white seed. I was surprised when i first opened it because i have been always getting the dark red seed varity. I thought i got a bad fruit. After I taste it, those pale pink/white seed taste sweeter and it is less tart than the drak red varity. It is also more juicy. I LOVED it!!
it depends on how much the field is riched by minerals such as Iron. you know as the Iron amount increase in field you have a more red element object you have and the pomegrenate's fruit is not an exception
13,640,594
I have a certain scenario where I am trying to accomplish more generic approach of using delegate and calling a selector based on what selector is being set. For example below is the code: ``` @protocol HttpRequestDelegate @optional - (void)testDrive:(NSData*)dataembedd; @end - (id)init { self = [super init]; if (self) { //Initialize it here. self.HttpRequestdelegate = self; } return self; } HttpRequest *apiCaller = [[HttpRequest alloc] init]; NSLog(@"%@",apiCaller.HttpRequestdelegate); [WLCC_ApiCaller executeAsync:apiCaller.HttpRequestdelegate :@selector(testDrive:) :[NSURL URLWithString:updateUrl] :wlcc_Get]; ``` However at executeAsync call I am trying to call the selector which is test drive like: ``` [delegate performSelector:@selector(selector) withObject:responseData]; ``` but it gives me an error of unknown selector, however when I notice the reference of the delegate its the same when initialized. I am trying to utilize delegate perform selector in different class, is there anything else besides that I need to do here? Thanks.
2012/11/30
[ "https://Stackoverflow.com/questions/13640594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618658/" ]
I don't know of any libraries, but here is my XE2 helper class unit with the SelectNode(s) function that I use to 'do' XPath. The RemoveNameSpaces and XMLToTree functions do not apply, but who knows when they might come in handy ;-) ``` unit uXMLHelper; interface Uses System.SysUtils, System.Classes, System.TypInfo, Vcl.ComCtrls, XML.XMLDoc, XMLDom, XML.XMLIntf; type TXMLHelper = class public class function SelectNode(StartNode: IXmlNode; const NodeXPath: WideString): IXmlNode; class function SelectNodes(StartNode: IXmlNode; const NodeXPath: WideString): IXMLNodeList; class function RemoveNameSpaces(XMLString: String): String; class procedure XMLToTree(XmlDoc: IXMLDocument; TV: TTreeView); end; function ConcatNodeNames(NodeNames: Array of String): String; // Concatenates the strings in NodeNames to /name1/name2/.../namex implementation Uses MSXML2_TLB; // IXMLDOMdocument class function TXMLHelper.RemoveNameSpaces(XMLString: String): String; const // An XSLT script for removing the namespaces from any document. It will remove the prefix as well. // From http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl cRemoveNSTransform = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">' + '<xsl:output method="xml" indent="no"/>' + '<xsl:template match="/|comment()|processing-instruction()">' + ' <xsl:copy>' + ' <xsl:apply-templates/>' + ' </xsl:copy>' + '</xsl:template>' + '<xsl:template match="*">' + ' <xsl:element name="{local-name()}">' + ' <xsl:apply-templates select="@*|node()"/>' + ' </xsl:element>' + '</xsl:template>' + '<xsl:template match="@*">' + ' <xsl:attribute name="{local-name()}">' + ' <xsl:value-of select="."/>' + ' </xsl:attribute>' + '</xsl:template>' + '</xsl:stylesheet>'; var Doc, XSL: IXMLDOMdocument2; Res : string; p : Integer; begin Doc := ComsDOMDocument.Create; Doc.ASync := false; XSL := ComsDOMDocument.Create; XSL.ASync := false; try Doc.loadXML(XMLString); XSL.loadXML(cRemoveNSTransform); Res := Doc.TransFormNode(XSL); // This now contains the original text with a <?xml version="1.0" encoding="UTF-16"?> prepended; remove it: p := Pos('?>',Res); result := Copy(Res,P+2); except on E:Exception do Result := E.Message; end; end; { RemoveNameSpaces } class function TXMLHelper.SelectNode(StartNode: IXmlNode; const NodeXPath: WideString): IXmlNode; // Geeft de node in path NodeXPath onder StartNode // http://delphi.about.com/od/delphi-tips-2011/qt/select-single-node-ixmlnode-txmlnode-xpath-delphi-xmldom.htm var intfSelect : IDomNodeSelect; dnResult : IDomNode; intfDocAccess : IXmlDocumentAccess; XMLDoc : TXmlDocument; begin Result := nil; if not Assigned(StartNode) or not Supports(StartNode.DOMNode, IDomNodeSelect, intfSelect) then Exit; dnResult := intfSelect.selectNode(NodeXPath); if Assigned(dnResult) then begin if Supports(StartNode.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then XMLDoc := intfDocAccess.DocumentObject else XMLDoc := nil; Result := TXmlNode.Create(dnResult, nil, XMLDoc); end; end; { SelectNode } class function TXMLHelper.SelectNodes(StartNode: IXmlNode; const NodeXPath: WideString): IXMLNodeList; (* Returns a list of all nodes in path NodeXPath below StartNode. * NodeXPath is relative; e.g. with: * * <Envelope> <= DocumentElement root * <Body> * <FindItemResponse> * <ResponseMessages> * <FindItemResponseMessage> * <RootFolder> <= IRootNode * <Items> * <CalendarItem> * * these are identical: * SelectNodes(DocumentElement,'Envelope/Body/FindItemResponse/ResponseMessages/FindItemResponseMessage/RootFolder/Items/CalendarItem') * SelectNodes(DocumentElement,'/Envelope/Body/FindItemResponse/ResponseMessages/FindItemResponseMessage/RootFolder/Items/CalendarItem') * SelectNodes(IRootNode,'Items/CalendarItem') * * http://delphi.about.com/od/vclusing/qt/delphi-select-xml-nodes-ixmlnodelist-selectnodes-xpath-xmldom.htm *) var intfSelect : IDomNodeSelect; intfAccess : IXmlNodeAccess; dnlResult : IDomNodeList; intfDocAccess : IXmlDocumentAccess; XMLDoc : TXmlDocument; i : Integer; dn : IDomNode; begin Result := nil; if not Assigned(StartNode) or not Supports(StartNode, IXmlNodeAccess, intfAccess) or not Supports(StartNode.DOMNode, IDomNodeSelect, intfSelect) then Exit; dnlResult := intfSelect.selectNodes(NodeXPath); if Assigned(dnlResult) then begin // Since the XPath implementation of SelectNodes returns an IDomNodeList and we need an IXMLNodeList // we need to "wrap" a call to IDomNodeSelect.selectNodes into a function that will result in IXMLNodeList. Result := TXmlNodeList.Create(intfAccess.GetNodeObject, '', nil); if Supports(StartNode.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then XMLDoc := intfDocAccess.DocumentObject else XMLDoc := nil; for i := 0 to dnlResult.length - 1 do begin dn := dnlResult.item[i]; Result.Add(TXmlNode.Create(dn, nil, XMLDoc)); end; end; end; { SelectNodes } procedure DomToTree(XmlNode: IXMLNode; TV: TTreeView; TreeNode: TTreeNode); var I: Integer; NewTreeNode: TTreeNode; NodeText: string; AttrNode: IXMLNode; begin // Skip text nodes and other special cases if XmlNode.NodeType <> ntElement then Exit; try // Add the node itself NodeText := XmlNode.NodeName; if XmlNode.IsTextElement then NodeText := NodeText + ' = ' + XmlNode.NodeValue; NewTreeNode := TV.Items.AddChild(TreeNode, NodeText); // Add attributes for I := 0 to xmlNode.AttributeNodes.Count - 1 do begin AttrNode := xmlNode.AttributeNodes.Nodes[I]; TV.Items.AddChild(NewTreeNode, '[' + AttrNode.NodeName + ' = "' + AttrNode.Text + '"]'); end; // add each child node if XmlNode.HasChildNodes then for I := 0 to xmlNode.ChildNodes.Count - 1 do DomToTree (xmlNode.ChildNodes.Nodes [I], TV, NewTreeNode); except on E:Exception do TV.Items.AddChild(TreeNode, E.Message); end; end; { DomToTree } class procedure TXMLHelper.XMLToTree(XmlDoc: IXMLDocument; TV: TTreeView); begin XMlDoc.Active := true; TV.Items.Clear; DomToTree(XMLDoc.DocumentElement,TV,nil); end; { XMLToTree } function ConcatNodeNames(NodeNames: Array of String): String; var Res,Nam : String; begin for Nam in NodeNames do Res := Res + '/' + Nam; Result := Res; end; end. ```
May be [OmniXML](http://code.google.com/p/omnixml/) will be useful (see XPath demo). And [another](http://www.benibela.de/sources_en.html#internettools) library for HTML parsing include XPath 2 support;
36,896,539
I've a Nodejs app and I use Passeport to let my users connect throught Facebook or Google via Oauth. I'm storing basic data after connection such as : uid, firstname etc. How can I be assured that the uid I'm receiving will be always unique for a given user ? I mean, data is coming either from Facebook or Google, so why couldn't I face a nasty duplicate uid for different users someday ?
2016/04/27
[ "https://Stackoverflow.com/questions/36896539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3903595/" ]
The UID is unique only within the scope of that single provider’s list of users. [This article](http://www.sitepoint.com/rails-authentication-oauth-2-0-omniauth/) suggests you combine the provider’s name plus the UID to get a unique value. > > Combination of provider’s name and uID will uniquely identify user inside our app. > > > I would use the provider’s domain name such as “google.com” or “com.google”.
The id you are getting via OAuth is unique when you are using either Facebook or Google. But if you want to use both then I would suggest make your **dbSchema** (if you are using mongoose) like this - ``` var userSchema = new mongoose.Schema({ local: { username: String, password: String }, facebook: { id: String, token: String, email: String, name: String }, google: { id: String, token: String, email: String, name: String } }); ```
12,880,539
I know that coding in native JavaScript means that your code will execute faster than if you were to code it in jQuery, but how much faster? In particular, I want to know if the speed increase would make it worth while spending the longer time coding in native JavaScript than jQuery if it was for a very large webapp? Or is the difference in speed not that great at all? For instance, to setup an AJAX request in jQuery all you have to do is call `$.ajax` or `$.post` and pass a few parameters, but with native JavaScript you have to create `XMLHttpRequest` or `ActiveXObject` objects depending on the users browser etc etc.
2012/10/14
[ "https://Stackoverflow.com/questions/12880539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320129/" ]
Test it. Pick a part of your web app and write it in JavaScript and then do the equivalent using jQuery. Test the performance. Developing JavaScript that outperforms jQuery is dependent on your, or the team's skill. jQuery is battle hardened code that abstracts lots of browser quirks for you. It does add some overhead to cater for lots of development use cases but that is a price that many developers are willing to pay. It takes skill and knowledge to to re-create the same functionality in JavaScript while eliminating the overhead that is not needed for your web app. I recommend you use jQuery. However, once jQuery is part of your web app it becomes your code so you must make efforts to understand what it is doing and why.
On the app I'm building we are using a combination of JQuery with our own prototypes. The time difference from a user's perspective is negligible from using just straight JS. Plus the CBS(cross browser support) is super important.
461,165
For the undermentioned tikz picture, I am not able to place it in centre. May kindly help. ``` \tikzstyle{startstop} = [rectangle, rounded corners, minimum width=3cm, minimum height=1cm,text centered, draw=black, fill=black!10] \tikzstyle{arrow} = [thick,->,>=stealth] \begin{tikzpicture}[node distance=2cm, auto] \node (start) [startstop] {Preparation of Tensile Specimen}; \node (in1) [startstop] [below of=start, xshift=0cm] {Tensile Testing}; \node (in2) [startstop] [below of=in1, xshift=0cm] {Analysis of Tensile Test Data for Sy}; \node (in3) [startstop] [below of=in2, xshift=0cm] {Preparation of High Cycle Fatigue Specimen}; \node (in4) [startstop] [below of=in3, xshift=0cm] {High Cycle Fatigue Testing}; \node (stop) [startstop] [below of=in4, xshift=0cm] {Analysis of Test Data}; \draw [arrow] (start) -- (in1); \draw [arrow] (in1) -- (in2); \draw [arrow] (in2) -- (in3); \draw [arrow] (in3) -- (in4); \draw [arrow] (in4) -- (stop); \end{tikzpicture} ```
2018/11/21
[ "https://tex.stackexchange.com/questions/461165", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/132410/" ]
The `tkz-euclide` package has a macro to do this. The manual is written in French. 1. First, we define the circle with the macro `\tkzDefCircle`. 2. This macro returns two values that are the center recovered with the macro `\tkzGetPoint{O}` 3. and the radius that is recovered with the macro `\tkzGetLength{rayon}`. Once this is done, we draw the circle with the macro `\tkzDrawCircle[R](O,\rayon pt)` [![cercle circonscrit](https://i.stack.imgur.com/iv6Au.png)](https://i.stack.imgur.com/iv6Au.png) ``` \documentclass[tikz,border=5mm]{standalone} %\usepackage{tikz} \usepackage{tkz-euclide} \usetikzlibrary{calc,through} \begin{document} \begin{tikzpicture} \coordinate (A) at (1,1); \coordinate (B) at (2,2); \coordinate (C) at (3,1.5); % \node[draw,line width=2pt] [circle through={(A)(B)(C)}] {}; \tkzDefCircle[circum](A,B,C) \tkzGetPoint{O} \tkzGetLength{rayon} \tkzDrawCircle[R](O,\rayon pt) \foreach \i in {A,B,C} { \node[circle,minimum size=1pt,fill=red] at(\i) {}; } \end{tikzpicture} \end{document} ```
A new node style, based on the derivation below plus the information that one can use `intersection of \p1--\p3 and \p2--\p4`, which I learned from [AndréC's nice answer](https://tex.stackexchange.com/a/461194/121799) ``` \documentclass[tikz,border=5mm]{standalone} \usetikzlibrary{calc,through} \tikzset{circle through 3 points/.style n args={3}{% insert path={let \p1=($(#1)!0.5!(#2)$), \p2=($(#1)!0.5!(#3)$), \p3=($(#1)!0.5!(#2)!1!-90:(#2)$), \p4=($(#1)!0.5!(#3)!1!90:(#3)$), \p5=(intersection of \p1--\p3 and \p2--\p4) in }, at={(\p5)}, circle through= {(#1)} }} \begin{document} \begin{tikzpicture} \coordinate (A) at (1,1); \coordinate (B) at (2,2); \coordinate (C) at (3,1.5); \node[circle through 3 points={A}{B}{C},draw=blue]{}; \foreach \i in {A,B,C} { \node[circle,minimum size=1pt,fill=red] at(\i) {}; } \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/KXnlh.png)](https://i.stack.imgur.com/KXnlh.png) Just for fun: an analytic solution based on `calc` only. (My personal opinion, though, is that this method is more "Ti*k*Zy", i.e. closer to how the standard Ti*k*Z styles work, than the tkz-euclide macros, which are more like pstricks, which I have left behind. However, this is just a personal opinion, and might not be shared by others.) ``` \documentclass{standalone} \usepackage{tikz} \usetikzlibrary{calc} \tikzset{circle through 3 points/.style n args={3}{% insert path={let \p1=($(#1)-(#2)$),\p2=($(#1)!0.5!(#2)$), \p3=($(#1)-(#3)$),\p4=($(#1)!0.5!(#3)$),\p5=(#1),\n1={(-(\x2*\x3) + \x3*\x4 + \y3*(-\y2 + \y4))/(\x3*\y1 - \x1*\y3)},\n2={veclen(\x5-\x2-\n1*\y1,\y5-\y2+\n1*\x1)} in ({\x2+\n1*\y1},{\y2-\n1*\x1}) circle (\n2)} }} \begin{document} \begin{tikzpicture} \coordinate (A) at (1,1); \coordinate (B) at (2,2); \coordinate (C) at (3,1.5); \draw[circle through 3 points={A}{B}{C}]; \foreach \i in {A,B,C} { \node[circle,minimum size=1pt,fill=red] at(\i) {}; } \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/9OEiq.png)](https://i.stack.imgur.com/9OEiq.png) (Note that `\n1` is a fraction, and could in principle not be well defined. If you ever encounter this case, just change the ordering, e.g. do `\draw[circle through 3 points={B}{C}{A}];` or something along those lines.) **ADDENDUM**: Explanation of the analytic formula. ``` \documentclass[tikz,border=3.14mm]{standalone} \usepackage{tikz} \usetikzlibrary{calc} \tikzset{circle through 3 points/.style n args={3}{% insert path={let \p1=($(#1)-(#2)$),\p2=($(#1)!0.5!(#2)$), \p3=($(#1)-(#3)$),\p4=($(#1)!0.5!(#3)$),\p5=(#1),\n1={(-(\x2*\x3) + \x3*\x4 + \y3*(-\y2 + \y4))/(\x3*\y1 - \x1*\y3)},\n2={veclen(\x5-\x2-\n1*\y1,\y5-\y2+\n1*\x1)} in ({\x2+\n1*\y1},{\y2-\n1*\x1}) circle (\n2)} }} \begin{document} \foreach \X in {1,...,5} {\begin{tikzpicture}[font=\sffamily] \path[use as bounding box] (-1,-4) rectangle (6,4); \coordinate (A) at (1,1); \coordinate (B) at (2,2); \coordinate (C) at (3,1.5); \foreach \i in {A,B,C} { \node[circle,minimum size=1pt,fill=red] at(\i) {}; } \ifnum\X=1 \node[anchor=north,text width=7cm] (start) at (2.5,0){Starting point: 3 points.}; \foreach \Y in {A,B,C} {\draw[-latex] (start) to[out=90,in=-90] (\Y) node[above=2pt]{\Y}; } \fi \ifnum\X=2 \coordinate (auxAB) at ($ (A)!.5!(B) $); \coordinate (auxBC) at ($ (B)!.5!(C) $); \draw (A) -- (B) -- (C); \draw ($ (auxAB)!1.2cm!90:(B) $) -- ($ (auxAB)!1.2cm!-90:(B) $) coordinate(aux1); \draw ($ (auxBC)!1.2cm!90:(B) $) coordinate(aux2) -- ($ (auxBC)!1.2cm!-90:(B) $); \node[anchor=north,text width=7cm] (int) at (2.5,0){The center of the circle is where the lines that run through and are orthogonal to the edges intersect.}; \draw[-latex] (int) to[out=45,in=-90] (aux1); \draw[-latex] (int) to[out=135,in=-90] (aux2); \fi \ifnum\X=3 \coordinate[label=below:$P_2$] (auxAB) at ($ (A)!.5!(B) $); \coordinate[label=below:$P_4$] (auxBC) at ($ (B)!.5!(C) $); \foreach \Y in {auxAB,auxBC} {\fill (\Y) circle (1pt);} \draw (A) -- (B) -- (C); \draw ($ (auxAB)!1.2cm!90:(B) $) -- ($ (auxAB)!1.2cm!-90:(B) $); \draw ($ (auxBC)!1.2cm!90:(B) $) -- ($ (auxBC)!1.2cm!-90:(B) $); \node[anchor=north,text width=7cm] (int) at (2.5,0){Call the points in the middle $P_2$ and $P_4$, and the differences $P_1=A-B$ and $P_3=B-C$. Then the orthogonal lines will fulfill \[\gamma_1(\alpha)~=~\left(\begin{array}{c} x_2+\alpha\,y_1\\ y_2-\alpha\,x_1\\ \end{array}\right) \] and \[\gamma_2(\beta)~=~\left(\begin{array}{c} x_4+\beta\,y_3\\ y_4-\beta\,x_3\\ \end{array}\right)\;. \] }; \fi \ifnum\X=4 \coordinate[label=below:$P_2$] (auxAB) at ($ (A)!.5!(B) $); \coordinate[label=below:$P_4$] (auxBC) at ($ (B)!.5!(C) $); \foreach \Y in {auxAB,auxBC} {\fill (\Y) circle (1pt);} \draw (A) -- (B) -- (C); \draw ($ (auxAB)!1.2cm!90:(B) $) -- ($ (auxAB)!1.2cm!-90:(B) $); \draw ($ (auxBC)!1.2cm!90:(B) $) -- ($ (auxBC)!1.2cm!-90:(B) $); \node[anchor=north,text width=7cm] (int) at (2.5,0){The center of the circle is then simply determined by \[\gamma_1(\alpha)~=~\gamma_2(\beta)\;, \] which has the solution \[ \alpha~=~\frac{-(x_2\cdot x_3) + x_3\cdot x_4 + y_3\cdot (y_4-y_2 )}{x_3\cdot y_1 - x_1\cdot y_3}\;. \] This is \texttt{\textbackslash n1} in the Ti\emph{k}Z style \texttt{circle through 3 points}. }; \fi \ifnum\X=5 \draw[circle through 3 points={A}{B}{C}]; \node[anchor=north,text width=7cm] (int) at (2.5,-0.1){Once we have the center, determining the radius (\texttt{\textbackslash n2}) is trivial, and we can draw the circle with a simple \texttt{insert path}.}; \fi \end{tikzpicture}} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/AAbaC.gif)](https://i.stack.imgur.com/AAbaC.gif)
67,373,803
If a user inputs a string like "y=3x+2", how do I change the "x" in the user's input to a SymPy Symbol named `x`? I have tried: ``` e1 = 'y = 3x+2' y = parse_expr(e1, evaluate=True) ``` but an error is raised when I try to parse `e1`. I don't want to use a regex or split the values into separate variables because there could be completely different formats of formulas.
2021/05/03
[ "https://Stackoverflow.com/questions/67373803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14862417/" ]
After parsing the user string (after taking care of the `=`) you no longer have a string, you have a python expression in which are SymPy objects. The `x` will now be a generic Symbol, just like the one you assigned to the variable `x`. Here I just split on the `=` and feed the left and right hand sides into an `Equality` expression: ``` >>> from sympy import * >>> x = Symbol('x') >>> user = 'y=3*x+2' >>> y = parse_expr('Eq(%s,%s)' % tuple(user.split('='))) >>> y Eq(y, 3*x + 2) >>> y.subs(x,3) Eq(y, 11) ``` You will *not* need to replace the `x` with anything before using `solve` to solve the equation(s): ``` >>> solve(y, x) [y/3 - 2/3] ``` You can read the `solve` docstring to see how to solve more than one equation. You will need to read about how to get `parse_expr` to recognize implied multiplication -- note that in my example I used a proper python expression on both sides of the `=`.
not sure if you want this is what you are asking for modify the equation: ``` 3x-y=-2 4x-y=2 import numpy as np a = np.array([[3, -1], [4,-1]]) b= np.array([-2,2]) z=np.linalg.solve(a,b) ``` Answer z = ``` array([ 4., 14.]) ```
23,444,320
SO i have active relation like: ``` [[id:1, post_id: 10, user_id:2][id:2, post_id:11, user_id:2]] ``` When i say `relation.uniq`, it doesn't return one value, because id's of objects are different(which is obvious behavior). How do i get only unique object, but not by full fields, but only by some specific field, for example `(:user_id)` I've tried to use distinct, but that returns me only array of fields, instead of active relation or objects As result, i'd want to get an active relation where, field user\_id would be unique Though i'm not sure if this is good idea, maybe i should use some other methodics to get what i want, because i'm starting to understand, that this is not the best idea
2014/05/03
[ "https://Stackoverflow.com/questions/23444320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411047/" ]
Right so it took me a while to figure it out myself but I finally managed to do this by writing the following function: ``` // @param int $post_id - The id of the post that you are setting the attributes for // @param array[] $attributes - This needs to be an array containing ALL your attributes so it can insert them in one go function wcproduct_set_attributes($post_id, $attributes) { $i = 0; // Loop through the attributes array foreach ($attributes as $name => $value) { $product_attributes[$i] = array ( 'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name 'value' => $value, // set attribute value 'position' => 1, 'is_visible' => 1, 'is_variation' => 1, 'is_taxonomy' => 0 ); $i++; } // Now update the post with its new attributes update_post_meta($post_id, '_product_attributes', $product_attributes); } // Example on using this function // The attribute parameter that you pass along must contain all attributes for your product in one go // so that the wcproduct_set_attributes function can insert them into the correct meta field. $my_product_attributes = array('hdd_size' => $product->hdd_size, 'ram_size' => $product->ram_size); // After inserting post wcproduct_set_attributes($post_id, $my_product_attributes); // Woohay done! ``` I hope this function will help other people if they need to import multiple attributes pro-grammatically in WooCommerce!
I tried Daniel's answer, and it didn't work for me. It might be that the Wordpress/Woocommerce code has changed since, or perhaps I didn't quite understand how to do it, but either way that code did nothing for me. After a lot of work using it as a base, however, I came up with this snippet of code and put it on my theme's `functions.php`: ``` function wcproduct_set_attributes($id) { $material = get_the_terms( $id, 'pa_material'); $material = $material[0]->name; // Now update the post with its new attributes update_post_meta($id, '_material', $material); } // After inserting post add_action( 'save_post_product', 'wcproduct_set_attributes', 10); ``` With this, I can take what I set as "material" on my WooCommerce install as a custom attribute and add it to the formal meta as \_material. This in turn allows me to use another snippet of code so the WooCommerce search function extends to meta fields, meaning I can search for a material in the WooCommerce search field and have all items with that material appear. I hope this is useful to somebody.
480,755
I am using a Dell n5050 laptop, recently I noticed that I have a problem with my laptop. Namely, the power LED always stays on after shutting down the laptop. I've found two options: 1. long press of the power switch will turn the LED off 2. remove the battery will also turn it off How can I resolve this issue?
2012/09/28
[ "https://superuser.com/questions/480755", "https://superuser.com", "https://superuser.com/users/161936/" ]
This LED reflects the fact that your laptop is plugged into the power network. Unplug it and the LED will be switched off. The battery charge continues after you shut down your laptop. The long press on the power button stops this charging
You can do few troubleshooting steps: 1. Click on Start → right-click Computer → Device Manager 2. In Device Manager click the `+` sign before "Network adapters" 3. Under "Network adapters" right-click "Wireless adapter n1030", select Properties and go to the Power Management tab. Uncheck "Allow the computer to turn off this device to save power". 4. Under "Network adapters" right-click "RTL8111E Fast Ethernet controller", select Properties and go to the Power Management tab. Uncheck "Allow the computer to turn off this device to save power". 5. Go to Start menu → Control Panel 6. In Control Panel, go to "Hardware and Sound" → "Power Options" 7. Under Power Options click "Choose what the power buttons do" 8. Select the option that says "Shut down" 9. Also select "Choose what closing the lid does" and select "Shut down"
65,519,159
After upgrading my application from rails 5.2 to rails 6 and I am getting this issue **This model adapter does not support fetching records from the database.** ``` class PlayerArtController < ApplicationController load_and_authorize_resource only: [:index, :create] def index end def create end end ``` Version: rails (6.0.3.4) cancancan (2.3.0) ruby 2.7.2
2020/12/31
[ "https://Stackoverflow.com/questions/65519159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5787849/" ]
As suggested by @Eyeslandic I ended up updating cancancan from 2.3 to 3.0
``` CanCan::NotImplemented (This model adapter does not support fetching records from the database.): ``` Records were not fecthed from database, after updating the gem resolved the issue: ``` # gem 'cancancan', '2.3.0' ## update version to new version gem 'cancancan', '~> 3.3.0' ```
200,082
I'm new in Blender and I'm making a jar bottle to start and want to close the top wraping with paper like these ones: [![enter image description here](https://i.stack.imgur.com/Ws3Da.png)](https://i.stack.imgur.com/Ws3Da.png) I tried using cloth modifier with a colision object + pressure but I can't find a way to make those folds in the paper like you can see in the picture. I already checked a lot of tutorials and questions but didn't find anything useful to get those folds. That's the best I get out of it: [![enter image description here](https://i.stack.imgur.com/h8Msq.png)](https://i.stack.imgur.com/h8Msq.png) **Q:** Any other idea how to achieve that kind of folds as realistic as possible?
2020/10/27
[ "https://blender.stackexchange.com/questions/200082", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/109883/" ]
Cloth Sim --------- * Add Circle 16 sides, Extrude, Scale, Grid Fill * Extrude, Scale outer loop, select vertices for each side and Scale on (X/Y) to zero to get square shape, add extra loops `Ctrl`+`R`+`3` [![enter image description here](https://i.stack.imgur.com/jkTS7.png)](https://i.stack.imgur.com/jkTS7.png) * Add cloth simulation (physics) * Add ShrinkWrap modifier, select one vertex loop next to perfect circles and assign vertex group to these, and use this group for modifier * The illusion that brings cloth more to paper feeling is under *Data Properties > Normal >* **Auto Smooth** [![enter image description here](https://i.stack.imgur.com/LDU8b.gif)](https://i.stack.imgur.com/LDU8b.gif) * To add detail to the lowpoly simulated mesh just add a **Normal Map** texture of smashed paper [![enter image description here](https://i.stack.imgur.com/Lf23W.gif)](https://i.stack.imgur.com/Lf23W.gif) [![enter image description here](https://i.stack.imgur.com/0LZK7.jpg)](https://i.stack.imgur.com/0LZK7.jpg) [![](https://blend-exchange.giantcowfilms.com/embedImage.png?bid=5R5gN3Yq)](https://blend-exchange.giantcowfilms.com/b/5R5gN3Yq/) **Notes:** * Select outer loop and with *Proportional editing* (O) rotate (R) a bit, twisted topology results in nicer sim * With a few extra loops close to existing folding is a bit closer to your reference. [![enter image description here](https://i.stack.imgur.com/Ycs2J.png)](https://i.stack.imgur.com/Ycs2J.png) * To let border of paper stick closer to glass you can create another vertex group and use second Shrink-wrap modifier with a subtle Ofset value. [![enter image description here](https://i.stack.imgur.com/oJ85V.jpg)](https://i.stack.imgur.com/oJ85V.jpg) [![](https://blend-exchange.giantcowfilms.com/embedImage.png?bid=K0qQLoYp)](https://blend-exchange.giantcowfilms.com/b/K0qQLoYp/)
This example you posted I believe is likely done by sculpting but simulation may be faster here (for multiple good looking results with low experience. *There were many major advances in the last year(s) of Blender development that are worth checking out if you aim for speed.* Sculpting method ---------------- The steps you take and the ways you sculpt is completely up to you here. In *Blender 2.80+* you... 1. Select the cloth (In object mode (switch with `TAB` or dropdown menu in the upper left corner of 3D viewport) 2. Go to "Sculpting" workspace (at the top of the UI) 3. Sculpt the surface to your liking. (with tools on the left - toggle by `T`, (`NUM /` to isolate selected object) For older versions refer to Blender Wiki (Docs) [here](https://docs.blender.org/manual/en/2.79/). For basic and traditional sculpting I'd recommend starting with official Blender guide [here](https://www.youtube.com/watch?v=TAGWu08oWAM) and seeing sculpting walkthroughs in Blender and other software too (you can very well refer in this topic). For cloth tool sculpting (new, faster) [this](https://www.youtube.com/watch?v=FjPbZBAApUI) might help you start. Simulation method ----------------- By creating **any shape(s) (mesh)** for the cloth to collide against (e.g. during a fall) without making the collision shape(s) visible, you can create many seemingly random and beautiful folds and wrinkles. I recommend seeing [this](https://www.youtube.com/watch?v=j5GFtJPvQXo) short video for guidance (different scenario, same base method)
123,612
I am a second year PhD student in math. I recently feel miserable working with my current advisor so I am considering switching advisor or adding a second advisor. A few problems I can think of at this moment which make me want another advisor include: * He constantly forgets meeting. For example, I schedule it with him on Wednesday. He would probably forget it on Friday. Of course this is minor if I send out a reminder in the morning on the day... * I feel he is not able to suggest me good references or offer help. I am surely not an independent enough student that can work on my own yet. I kept desperately seeking answers online, asking everywhere, and probably spamming the authors who wrote the papers... This is probably the right way of doing research, but I doubt whether I could speed up my progress a bit if I could get more help from my advisor. * I guess one reason also for the last paragraph is he is giving me something that he is not very familiar with. I believe this is probably the case with most advisors. But once I tried to search for a long time and just could not find an object in the problem that he suggested me, and it turned out he remembered it wrong... I just wish he could be less careless. I actually kind of transferred following my advisor to this university, so I tried to work with him since I came here, though I actually did not really start working with him in my previous school and came here as a first year student. I always thought seeking for another advisor would again take effort, and the miseries come and go, so I just did not do anything with it. What I am thinking now is, if everything like the above is normal for a math advisor, then I would like to convince myself and go along with it. My miseries are probably just what I need to bare to do math, but If it is not, I really hope to get more help and support from my advisor for my next a few years in grad school. I guess one direct reason why I am posting this is I have not made any progress reading one paper (not even doing a problem) since 3 or 4 months ago. I could not answer my advisor's questions about the paper perfectly as he wants and he would not let me move on. I do not really see the meaning of doing it and he could not give any suggestions, and I started to hate the math and lost motivations, so I think I definitely want some adjustment, either real or mental. Thanks in advance for any advice.
2019/01/23
[ "https://academia.stackexchange.com/questions/123612", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/101905/" ]
As suggested in other answers here, none of the things you describe are necessarily deal breakers. But you don't give any positive aspects of the relationship. A lot of relatively small negatives can add up. I'm going to guess that you've made up your mind already, even if you haven't noticed it, and simply want confirmation that it is ok to go. Yes, it is ok to go. There is little worse in a doctoral program than having an advisor who isn't right for you. If you don't have some big positive sense that makes the negatives less important, then you should start looking for a different advisor. You don't have to break ties before you start to search, of course. But explore the options, at least.
1. The meeting forgetting is minor. There can be way worse aspects of an advisor (competition, power struggles, etc.) 2. Giving good references: in an ideal world, "apprenticeship" would be more normal. However the reality is that many grad students forge their own path and are even expected to do so. Definitely this is the case in experimental sciences with large groups and advisors who have teaching responsibilities and spend a lot of time grubbing for money, etc. Perhaps this is a bit different in math because the groups are smaller and the work is harder. But still, perhaps it is somewhat the case in math also. I would lean to assuming you need to do your own work. 3. Project selection: this is a big issue. It's probably the most important part of a Ph.D. to pick a problem that is tractable. Advisors are not the ones doing the work. It is easy for them to assign "nice to know" projects that are too difficult or have low likelihood of success. And then the risk/reward is dramatically different and the pain of failure much harder on you. --- Based on what you say so far, I would try to pivot to some easier project that is more tractable. Probably with a different advisor, perhaps with yours. Would be open to some field of math that is not as challenging as what you are in (stats or OR versus Andrew Wiles stuff) if such a change is still feasible. You seem to need something easier. Note, I'm not sure if the issue is you were given an unreasonable problem or if you don't have the traits to deal with what was assigned. But it sort of doesn't matter. Find a better match. You've been doing this a little while and some parts of your question text make me think it unlikely you will succeed with challenging material. (It's OK. Michael Jordan was bad at baseball.
18,620
I want to insert a record in the database. If it meets certain criteria, it should be inserted in lead, if not, it should be added in contacts. I'm not able to achieve this. Its a before insert trigger on lead object. If the trigger completes properly, it gets updated in leads irrespective of its insertion in contacts. Please help..
2013/10/23
[ "https://salesforce.stackexchange.com/questions/18620", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/4135/" ]
You could do something like this in an after trigger. It has the downside of burning up an Id on Lead as each Lead needs to be inserted into the Database first ``` if (trigger.isInsert) { List<Lead> leadsToConvertToContacts = new List<Lead>(); for(Lead l : Trigger.new) { if (l.SomeCriteria__c == 'Blah') { leadsToConvertToContacts.add(eDel); } } List<Contact> newContacts = new List<Contact>(); for (Lead l : leadsToConvertToContacts) { // Create Contact from Lead DeleteLeadsClass dlc=new DeleteLeadClass(); dlc.deleteLead(l.id); } // delete leadsToConvertToContacts; insert newContacts; // Or use upsert } ``` And so i added an apex class called DeleteLeadsClass as follows: global class DeleteLeadsClass{ ``` public void deleteLead(String IDs){ Lead lead1=[Select id from lead where id=:IDs]; delete lead1; ``` } } This works perfectly fine. :)
What you can do is..create after insert trigger.. check for condition if its true --> insert contact record and delete this instance from Lead.
21,883,458
I have the following ENUM: ``` [Flags] public enum DataFiat { [Description("Público")] Public = 1, [Description("Filiado")] Listed = 2, [Description("Cliente")] Client = 4 } // DataFiat ``` And I created an extension to get an Enum attribute: ``` public static T GetAttribute<T>(this Enum value) where T : Attribute { T attribute; MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault(); if (info != null) { attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault(); return attribute; } return null; } ``` This works for non Flags Enums ... But when I have: ``` var x = DataFiat.Public | DataFiat.Listed; var y = x.GetAttribute<Description>(); ``` The value of y is null ... I would like to get "Público, Filiado, Cliente" ... Just as ToString() works. How can I change my extension to make this work? Thank You
2014/02/19
[ "https://Stackoverflow.com/questions/21883458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577805/" ]
You can use [this](https://stackoverflow.com/questions/4171140/iterate-over-values-in-flags-enum): ``` var values = x.ToString() .Split(new[] { ", " }, StringSplitOptions.None) .Select(v => (DataFiat)Enum.Parse(typeof(DataFiat), v)); ``` To get the individual values. Then get the attribute values of them. Something like this: ``` var y2 = values.GetAttributes<DescriptionAttribute, DataFiat>(); public static T[] GetAttributes<T, T2>(this IEnumerable<T2> values) where T : Attribute { List<T> ts =new List<T>(); foreach (T2 value in values) { T attribute; MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault(); if (info != null) { attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault(); ts.Add(attribute); } } return ts.ToArray(); } ```
in .NET CORE without any additional libraries you can do: ``` public enum Divisions { [Display(Name = "My Title 1")] None, [Display(Name = "My Title 2")] First, } ``` and to get the title: ``` using System.ComponentModel.DataAnnotations using System.Reflection string title = enumValue.GetType()?.GetMember(enumValue.ToString())?[0]?.GetCustomAttribute<DisplayAttribute>()?.Name; ```
17,446,109
This is my 1st post in StackOver flow and my English is not good. I am a beginner in iOS, so i am slow little bit. Actually i want to parse 5 of my data (including Image) from URL. I use custom tableView cell for it. My plain text are showing in custom cell (in lable) clearly but images are not. That's why i use "dispatch\_queue\_t" for loading the image in a particular ImageView. When i run the simulator the images showing up (Logo & BackGround) one after another row perfectly, but the problem happen when i reset the simulator. After reset it, one image (the last one in queue) load in every cell (total 5). I call my "parsingLoad" method in "viewDidLoad", so that it only load, once at the time of loading viewController. Can any one told me what did i wrong? Here is my code : ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"FairListCustomCell"; FairListCustomCell *cell = (FairListCustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *topLabelObject = [[NSBundle mainBundle] loadNibNamed:@"FairListCustomCell" owner:self options:nil]; for (id currentObject in topLabelObject) { if ([currentObject isKindOfClass:[UITableViewCell class]]) { cell = (FairListCustomCell*) currentObject; break; } } } cell.selectionStyle = UITableViewCellSelectionStyleNone; currentFair = [fairs objectAtIndex:indexPath.row]; cell.fairNameLabel.text =currentFair.FairName; cell.fairLocationLabel.text =currentFair.FairLocation; cell.bookmarkImageView.image=[UIImage imageNamed:@"Favorite.png"]; cell.bookmarkImageView.tag=indexPath.row; dispatch_queue_t imageQueueFairLogo = dispatch_queue_create("com.queue", NULL); dispatch_async(imageQueueFairLogo, ^ { dispatch_retain(imageQueueFairLogo); UIImage *imageFairLogo = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentFair FairLogo]]]]; dispatch_async(dispatch_get_main_queue(), ^ { cell.fairLogoImageView.image = imageFairLogo; #if NEEDS_DISPATCH_RETAIN_RELEASE dispatch_release(imageQueueFairLogo); #endif }); }); dispatch_queue_t imageQueueFairCellBackGround = dispatch_queue_create("com.queue", NULL); dispatch_async(imageQueueFairCellBackGround, ^ { dispatch_retain(imageQueueFairCellBackGround); UIImage *imageFairCellBackGround = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentFair FairCellBackGround]]]]; dispatch_async(dispatch_get_main_queue(), ^ { cell.fairCellBackGround.image = imageFairCellBackGround; #if NEEDS_DISPATCH_RETAIN_RELEASE dispatch_release(imageQueueFairCellBackGround); #endif }); }); return cell; ``` } I also try with another tow ways. 1st :- using "global\_queue" for both of Images (here as a sample just put one), like this : ``` imageQueueFairCellBackGround = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(imageQueueFairCellBackGround, ^ { dispatch_retain(imageQueueFairCellBackGround); UIImage *imageFairCellBackGround = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentFair FairCellBackGround]]]]; dispatch_async(dispatch_get_main_queue(), ^ { cell.fairCellBackGround.image = imageFairCellBackGround; #if NEEDS_DISPATCH_RETAIN_RELEASE dispatch_release(imageQueueFairCellBackGround); #endif }); }); return cell; ``` 2nd :- Like this: ``` dispatch_queue_t fairCellBackGroundcallerQueue = dispatch_get_current_queue(); dispatch_queue_t fairCellBackGrounddownloadQueue = dispatch_queue_create("Thumb downloader", NULL); dispatch_async(fairCellBackGrounddownloadQueue, ^ { UIImage *imageFairCellBackGround = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentFair FairCellBackGround]]]]; dispatch_async(fairCellBackGroundcallerQueue, ^ { cell.fairCellBackGround.image = imageFairCellBackGround; }); }); dispatch_release(fairCellBackGrounddownloadQueue); ``` But still it isn't solved. Please if any one have any solution, share with me. Thanks a lot, in advanced.
2013/07/03
[ "https://Stackoverflow.com/questions/17446109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2435154/" ]
I found the solution of this particular problem. Here it is: ``` imageQueueFairLogo = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(imageQueueFairLogo, ^ { UIImage *imageFairLogo = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[currentFair FairLogo]]]]; dispatch_async(dispatch_get_main_queue(), ^ { //[imageCache setObject:imageLogoCache forKey:currentFair.FairLogo]; cell.fairLogoImageView.image = imageFairLogo; [cell setNeedsLayout]; }); }); ``` And of course "**Declare**" & "**@synthesize**" the corresponding dispatch queue in your "MyClass.h" & "MyClass.m" file like this : ``` @property(nonatomic) dispatch_queue_t imageQueueFairLogo; @synthesize imageQueueFairLogo; ``` Do the same thing for "imageQueueFairCellBackGround" Thanks. :)
try like this ``` if (postAndCheckInDetails.postImageURL.length != 0) { if (!uploadImage) uploadImage = (UIImageView*)[cell viewWithTag:4]; dispatch_queue_t checkInQueueForPostImage = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(checkInQueueForPostImage, ^{ UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:postAndCheckInDetails.postImageURL]]]; dispatch_sync(dispatch_get_main_queue(), ^{ if (image!=nil) { [uploadImage setImage:image]; [uploadImage setFrame:CGRectMake(80, checkInDateAndTime.frame.origin.y+40, 160, 120)]; } [cell setNeedsLayout]; }); }); } ```
119,050
Challenge ========= Given a the ID for a PPCG user who has existed for at least a month, output the average amount of reputation they gain per month. You can do this by dividing their reputation by the time since their account was created (which you can find on the profile). This should be returned floored; that is, truncate all of the decimals. (We don't care about the small stuff). Input ===== A single integer, which is the user's ID Output ====== A single integer, representing the floored rep change per month. Test Cases ========== ``` input -> output 42649 -> 127 (me) 12012 -> 3475 (Dennis) 8478 -> 3015 (Martin Ender) ```
2017/05/05
[ "https://codegolf.stackexchange.com/questions/119050", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/68942/" ]
JS, ES6 ~~243~~ ~~235~~ ~~168~~ ~~166~~ ~~165~~ 164 bytes ========================================================= ``` i=>fetch(`//api.stackexchange.com/users/${i}?site=codegolf`).then(x=>x.json()).then(x=>alert(~~((y=x.items[0]).reputation/((new Date/1e3-y.creation_date)/2592e3)))) ``` Based on [the Python answer](https://codegolf.stackexchange.com/a/121370/58826). Run this in the console: ``` (i=>fetch(`//api.stackexchange.com/users/${i}?site=codegolf`).then(x=>x.json()).then(x=>alert(~~((y=x.items[0]).reputation/((new Date/1e3-y.creation_date)/2592e3)))))(+prompt("Enter a userId")) ``` -4 thanks to [@insert\_name\_here](https://codegolf.stackexchange.com/users/59682/insert-name-here) ### Old answer: ``` z=>fetch("//codegolf.stackexchange.com/u/"+z).then(x=>x.text()).then(x=>alert((/([\d,]+) <span class="label-uppercase">repu/.exec(x)[1].replace(/,/g,"")/(((y=/Member for <.+>((\d+) years?, )?(\d+) month/.exec(x))[2]||0)*12+ +y[3]||0)))) ``` Improvements welcome! Just fetches the profile page and parses it with regular expressions! Won't work as a stack snippet, but you can paste this in your console: ``` (z=>fetch("//codegolf.stackexchange.com/u/"+z).then(x=>x.text()).then(x=>alert(Math.floor(/([\d,]+) <span class="label-uppercase">repu/.exec(x)[1].replace(/,/g,"")/(((y=/Member for <.+>((\d+) years?, )?(\d+) month/.exec(x))[2]||0)*12+ +y[3]||0)))))(+prompt("Enter a userId")) ```
Python ~~3~~ 2, ~~206~~ ~~219~~ ~~201~~ 193 bytes ------------------------------------------------- ``` import requests,time a=requests.get('http://api.stackexchange.com/users/'+str(input())+'?site=codegolf').json()['items'][0] print a['reputation']/((int(time.time())-a['creation_date'])/2592000) ``` I am estimating the months as the OP suggested, but actually `print(int(b/((d-c)/2592000)))` is a more accurate solution than `print(int(b/int((d-c)/2592000)))` and also saves a few bytes.
3,421
I've read a few other questions/answers on smart contract consensus by nodes in the network, but I still don't understand the steps. Here's how I picture it: 1. Two parties might agree upon a smart contract, sign with their private keys 2. Nodes validate that those parties are who they say they are 3. Smart contract is appended to the blockchain Let's say that the contract was a simple payout from Adam to Bob depending on the day of the week (Monday = 1 bubblecoin, Tuesday = 2 bubblecoins, etc.) Part of the code might look something like this: ``` If Monday, send 1 from Adam to Bob, else If Tuesday, send 2 from Adam to Bob, else If Wednesday, send 3 from Adam to Bob.... ``` My question is, if we ran the code on Wednesday, what do those nodes do? Do they check to make sure the code within the contract is the same as what every other node sees? Or do they actually run the code, get the output (here it would be 3 from Adam to Bob), and compare that OUTPUT with others in the system? If they compare output, what if the output is different between nodes? I'm hoping that providing an example contract will help me visualize what is actually being agreed upon by the nodes.
2016/04/27
[ "https://ethereum.stackexchange.com/questions/3421", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/1768/" ]
> > what is actually being agreed upon by the nodes > > > Many details, but at a high level 2 main ones are: * the **state** of the blockchain, including the exact contract code * the behavior and results of that code when it is executed (technical term is the **state transition function**) More granular details include where the code is on the blockchain, who put it on the blockchain, how much "coins" an account has, etc. > > Do they check to make sure the code within the contract is the same as what every other node sees? > > > An Ethereum node follows the rules defined by the [Ethereum protocol](https://github.com/ethereum/yellowpaper). If something doesn't follow the rules, the node effectively ignores it. A node gets data from other nodes, but processes the data according to the protocol. **A node is more concerned about following the Ethereum protocol, rather than if other nodes are following the protocol.** But it is important for a node to have connections to other nodes that are following the protocol, otherwise the node doesn't have the data to join and be part of the Ethereum network. > > ...what if the output is different between nodes? > > > Nodes that follow the Ethereum protocol should always be in **agreement because the protocol is [deterministic](https://ethereum.stackexchange.com/a/334/42) and [carefully defined](https://github.com/ethereum/yellowpaper)**. Basically, if one node is following the protocol, and another node produces a different output, only the first node is part of the network: the latter node is ignored. When a definition is missing in the Ethereum protocol, nodes can disagree, and to resolve the disagreement, the protocol is updated, and nodes are upgraded to obtain the new rules and form consensus again.
**TL;DR** Date is always based on the time and date when the block was mined. --- **Longer answer.** Ethereum smart contracts use a deterministic code. Solidity is one of the deterministic languages that makes you able to generate Ethereum EVM deterministic code. Deterministic code means that if you call a function using some parameters, you will always get the same result. Parameters are defined by the transaction used to call that contract function. Deterministic code thus can't provide expressions that wouldn't give the same result each time you execute it with the same parameters. Deterministic code will not contain things like random functions. The example in your question is `If Monday, send 1 from Adam to Bob, else` this can be better translated to `If it was monday at the moment the transaction was included in the mined block, send 1 from Adam to Bob, else`. This is fully deterministic and every time you will replay the function it will give the same result as the date the block was mined never changes.
58,485,673
I have an ASP.NET Core Project with Angular App inside it. After updating the project to .NET Core 3.0 release, I've got a problem. During ASP.NET Core Project build, I see 2 errors in the output: ``` 1>------ Build started: Project: Portal, Configuration: Debug Any CPU ------ 1>C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.6\lib.es2015.iterable.d.ts(41,6): error TS2300: Build:Duplicate identifier 'IteratorResult'. 1>D:\Solution\MyProject\ClientApp\node_modules\@types\node\index.d.ts(73,11): error TS2300: Build:Duplicate identifier 'IteratorResult'. 1>MyProject -> D:\Solution\MyProject\bin\Debug\netcoreapp3.0\Portal.dll 1>Done building project "Portal.csproj". ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== ``` package.json: ``` { "name": "client-app", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "build-dev": "ng build --configuration=development" }, "private": true, "dependencies": { "@angular/animations": "^8.2.2", "@angular/cdk": "~8.1.3", "@angular/common": "~8.2.0-next.1", "@angular/compiler": "~8.2.0-next.1", "@angular/core": "~8.2.0-next.1", "@angular/forms": "~8.2.0-next.1", "@angular/platform-browser": "~8.2.0-next.1", "@angular/platform-browser-dynamic": "~8.2.0-next.1", "@angular/router": "~8.2.0-next.1", "core-js": "^2.5.4", "primeflex": "^1.0.0-rc.1", "primeicons": "^1.0.0", "primeng": "^8.0.1", "rxjs": "~6.5.2", "tslib": "^1.9.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.801.1", "@angular/cli": "~8.1.1", "@angular/compiler-cli": "~8.2.0-next.1", "@angular/language-service": "~8.2.0-next.1", "@types/node": "~8.9.4", "@types/jasmine": "~2.8.8", "@types/jasminewd2": "~2.0.3", "codelyzer": "^5.0.1", "jasmine-core": "~2.99.1", "jasmine-spec-reporter": "~4.2.1", "karma": "~4.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.1", "karma-jasmine": "~1.1.2", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.4.0", "ts-node": "~7.0.0", "tslint": "~5.11.0", "typescript": "3.4.5" } } ``` tsconfig.json: ``` { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "downlevelIteration": true, "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "module": "esnext", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] } } ``` What I tried: * update @type/node through npm; * delete @type/node from package.json; * change typescript (bottom of package.json) version to 3.6.4.
2019/10/21
[ "https://Stackoverflow.com/questions/58485673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/776539/" ]
I also got similar issue, but after installing Typescript on local machine from below link, <http://www.typescriptlang.org/#download-links> I rebuild solution, it worked. Note : Choose your appropriate VisualStudio version or any IDE you are using from download link!
I guess it is showing the error because somewhere you try to reinitialize the same property twice or more times. For Example: ``` let name = "John"; let person = { name, name: "Jane" } ``` As in the above code, * we first assigned the person's property(name) to John. * but then we reassigned the person's property(name) to Jane. This will make the first initialization redundant. Result : person = {name: "Jane"}
16,713,914
I am not sure if this is a **bug** with the **new Android GeoFence sample code** or my understanding of what it is supposed to do is wrong. The sample app creates geofences but does not alert when geofence is breached. If anyone would like to give this a try and confirm, you can download the sample code from here : <https://developer.android.com/training/location/geofencing.html> This is what I was expecting the sample app to do : * Setup 2 different geofences. In my case, I picked 2 points a mile apart by entering their respective lat/long. I also set the radius to 250m . * I drove to each of those 2 locations one after another and I assumed a notification would popup indicating that the geofence has been breached. In this case, **no notifications nor any log messages were registered** which means that "ReceiveTransitionsIntentService" never got called. One observation is that **when I drive to the first location and then add a new geofence right at that location**, the notification gets **fired immediately**, but any other location (geofence) I set and drive to, nothing happens. **Any idea why? Is my understanding correct about the sample app's functionality?** Do I need to do anything in addition to what is in the sample code to receive an alert when I breach the geofence while driving? **Is geofence monitoring separate from creating geofences, what am I missing here?** Highly appreciate any input, We are very eager to use this in our app but right now we are stuck. Thanks, Torri.
2013/05/23
[ "https://Stackoverflow.com/questions/16713914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720954/" ]
First of all, your understanding of the app's functionality is correct. Whenever you enter/leave one of your geofences it shows you that in a notification (it's always updating the same notification btw, so keep an eye out for it or you might miss one of the events). Second, be careful because Geofence 1, by default, is only triggering **ENTER** events. So if you leave that geofence area after being inside it you won't get a notification for that! You can change this behavior in the creation of the mUIGeofence1 object on MainActivity.java. Lastly, as with all things related to location, this API isn't perfect.. From my tests so far I have never seen it start up the GPS, so when outside it pretty much seems to rely on network locations which can easily not fall under a 500m radius geofence even if you're standing right in the middle of it. During one of the presentations at IO, Reto Meier mentioned that the API would be clever enough to handle battery drain the best way possible, so it would only turn on GPS when the user starts getting close to a geofence - which makes sense - but this never seems to happen unfortunately.
I tried the GeofenceDetection sample code and it is working. I am using only Wifi and GPS, and set my radius to be 15 meters. When i walked to the region, it is not immediately show the notification. After a few seconds, i got "enter" notification. Also, even if i am standing still in the region, sometimes i got notified that i am exiting the region. It makes the app feels like it's jumping around in and out of a region.
68,622,755
I want to scrape web and the structure looks like: ``` <iframe> #document <html> ...... </html> </iframe> ``` I need to step into "html" and click the button but I can't find a way to go inside. Is there any method to click button inside the "#tag\_name"?
2021/08/02
[ "https://Stackoverflow.com/questions/68622755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9540366/" ]
[adam-smooch](https://stackoverflow.com/users/10761353/adam-smooch) he was right I think ``` sub_lists=[(1,None,None,12,None,None,None),(2,67,None,None,None,None,None),(2,None,None,83,None,None,None)] def my_combine(l1, l2): l1 = list(l1) l2 = list(l2) for i in range(len(l1)): if l1[i] is None: l1[i] = l2[i] return l1 results = dict() for sl in sub_lists: if sl[0] not in results: results[sl[0]] = sl[1:] else: results[sl[0]] = my_combine(results[sl[0]], sl[1:]) print(results) # desired outcome. # sub_lists=[(1,None,None,12,None,None,None),(2,67,None,83,None,None,None)] ``` I think @Adam Smooch was right I am modified it a bit
since sub-lists' first numbers will be unique at the end, you could use a dictionary. so do something like: ``` def my_combine(l1, l2): l1 = list(l1) for i in range(len(l1)): if l1[i] is None: l1[i] = l2[i] return tuple(l1) results = dict() for sl in sub_lists: if sl[0] not in results: results[sl[0]] = sl[1:] else: results[sl[0]] = my_combine(results[sl[0]], sl[1:]) ```
40,164,782
The question posed was: Given an integer 0 < N < 1000000000000 return the highest number of consecutive digits in the number. For example in the number 9934445666644 the answer would be 4 because there are: ``` 2x 9 1x 3 3x 4 1x 5 4x 6 2x 4 ``` In the number provided. I know I can solve the problem with some counters and loops but thought it would be best to use regex to solve this. And if the question was extended to highest number of consecutive characters in any string (not limited to digits) how would I do it?
2016/10/20
[ "https://Stackoverflow.com/questions/40164782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983926/" ]
You may extract all chunks of consecutive identical characters (here, we may just match digits) and then find the longest match. The regex looks rather basic: ``` /(\d)\1*/g ``` It will match and capture into Group 1 a digit (see `(\d)`) and then zero or more (due to `*` quantifier) values captured in Group 1. That means it will match chunks consisting of one digit that will be helpful if there are no repeated digits in the string. The code will look like ``` console.log((Math.max.apply(Math, "9934445666644".match(/(\d)\1*/g))+"").length); ```
You can use a `for` loop, set property name of an array to number, increment property value if object property name is matched at nested `for` loop which iterates from current index + 1 until end of input. Return array having first element set to index of beginning of the greatest sequence of matching characters at original string, second element set to end of sequence length of greatest sequence of matching characters. `.slice()` or `for` loop can be utilized to retrieve the characters of the greatest matching sequence; ```js let values = ["9934445666644" , Array.from("993444564666644") , "aaBBBCCCdd333*******11111"]; // `input`: string, array function greatestSequence(input) { for (var i = 0, res = []; i < input.length; i++) { var curr = input[i]; res[i] = 1; for (var j = i + 1; j < input.length; j++) { if (curr == input[j]) { res[j] = ++res[i]; } else { break } } } var g = res.reduce(function(a, b) { return a < b ? b : a }); var index = res.indexOf(g); return [index, index + g]; } let g0 = greatestSequence(values[0]); console.log("value[0] indexes:", g0, "values:", values[0].slice(g0[0], g0[1])); let g1 = greatestSequence(values[1]); for (var i = g1[0], garr = []; i < g1[1]; garr.push(values[1][i]), i++); console.log("value[1] indexes:", g1, "values:", garr.join("")); let g2 = greatestSequence(values[2]); console.log("value[2] indexes:", g2, "values:", values[2].slice(g2[0], g2[1])); ```