text
stringlengths
64
89.7k
meta
dict
Q: Powershell input validition I am trying to only allow a user to enter 2 letters when they rename a file if its exists. It is not working as I wanted it. I am allowed to enter numbers. if ($RenameLargeFiles.Length -gt '2') { Write-Host " You may only enter 2 letters." Pause Clear-Host Rename-LargeFiles } else { Rename-Item -Path $LargeFiles $RenameLargeFiles".txt" $LargeFiles = $RenameLargeFiles Set-Content -Value $Files -Path $LargeFiles } } Set-StrictMode –Version Latest $LargeFiles = "C:\PSScripts\LargeFiles.txt" $PSScripts = "C:\PSScripts" $TestPSScripts = Test-Path "C:\PSScripts" switch ($TestPSScripts) { 'False' { New-Item -Type directory -Path $PSScripts } } function Test-Files { $Files8 = "" $Files8 = Read-Host " Please Enter the Complete Path. " $TFiles8 = Test-Path $files8 if ($TFiles8 -eq 'True') { Write-Host $Files8 "LOCATED." } else { Write-Host $Files8 "NOT FOUND" Pause Clear-Host Test-Files } } function Test-LargeFiles { $LargeFiles = "C:\PSScripts\LargeFiles.txt" $TestLargeFiles = Test-Path $LargeFiles if ($TestLargeFiles -eq 'True') { Write-Host $LargeFiles "already present" Rename-LargeFiles } else { Write-Host $LargeFiles "NOT FOUND." Write-Host $LargeFiles "created" } } function Rename-LargeFiles { $LargeFiles = "C:\PSScripts\LargeFiles.txt" [string] $RenameLargeFiles = Read-Host " Please Enter 2 letters to rename" $LargeFiles if ($RenameLargeFiles.Length -gt '2') { Write-Host " You may only enter 2 letters." Pause Clear-Host Rename-LargeFiles } else { Rename-Item -Path $LargeFiles $RenameLargeFiles".txt" $LargeFiles = $RenameLargeFiles Set-Content -Value $Files -Path $LargeFiles } } Test-Files $Files = Get-ChildItem -Recurse $Files8 | Sort-Object -Descending -Property Length | Select-Object -First 10 Test-LargeFiles Add-Content -Value $Files -Path $LargeFiles pause A: Use a regex like so: if ($RenameLargeFiles -notmatch '[aA-zZ]{2}') { ... display error message }
{ "pile_set_name": "StackExchange" }
Q: Is my proof that πe is transcendental correct? I've been trying to prove that πe (the product of π and e) is transcendental. e can be defined as the infinite sum of reversed values of factorials (1/0!+1/1!+1/2!+1/3!+...). Hence, πe = π(1/0!+1/1!+1/2!+1/3!+...) = π/0!+π/1!+π/2!+π/3!+... Each number in this infinite series (π/0!, π/1! etc.) is transcendental (it's always π divided by an integer so it is transcendental because π is), so the sum of the infinite series (which equals πe) must be transcendental as well. Can anyone check my proof and say whether it is correct or not? A: No, that argument is not correct. Being transcendental is not preserved under sums: e.g. $\pi+(-\pi)$ certainly isn't transcendental! Infinite sums only ever make things worse, not better, so the fact that a finite sum of transcendentals isn't necessarily transcendental should convince you that your argument is incorrect; but just to drive the point home, here's an example of a sequence all of whose terms are transcendental (indeed, all of whose partial sums are transendental) whose sum is $1$: $$(1-\pi)+(\pi-{\pi\over 2})+({\pi\over 2}-{\pi\over 3})+({\pi\over 3}-{\pi\over 4})+...$$ In general, negative properties like irrationality, transcendentality, etc. aren't preserved under sums - positive ones, like rationality, algebraicity, etc. tend to be.
{ "pile_set_name": "StackExchange" }
Q: Trying to create a field in gravity Forms that hides the information as it types, similar to when inputting a password I am creating an application and need the potential hirees to put in their SSN. I am having some trouble creating a Line Text Field that as the hiree types will hide the numbers, similar to when you're putting in your password. Anyone know how to do this? I've already edited the functions.php in an attempt to add 'encrypt' to the advanced settings but that only encrypts the data once its submitted, not immediately turning it into dots as the enter it. A: On Single Line Text fields, you can select the Enable Password Input option to mask the text like a password input.
{ "pile_set_name": "StackExchange" }
Q: Converting cell array of string arrays to a double array I have a 55X1 cell array. Each cell contains a 1X178 string array of numbers. I would like to convert all the cells to a double array, but in such a way that it forms a 55X178 double array. Take, for example, the 55X1 cell array dataCellOut = {each cell has a 1X178 string}. I can use: na=str2num(dataCellOut{1}) and this will output a 1X178 double array. I have tried using: na=cellfun(@str2num, dataCellOut, 'UniformOutput', false) and this does not work (error: "input must be a character vector or string scalar"). I have worked on this for awhile to no avail. I hope this makes sense and if there is anything else that I can offer please don't hesitate to let me know. Thank you in advance! A: According to the documentation to str2num: The str2num function does not convert cell arrays or nonscalar string arrays, and is sensitive to spacing around + and - operators. In addition, str2num uses the eval function, which can cause unintended side effects when the input includes a function name. To avoid these issues, use str2double. str2double, however, does just as you want: X = str2double(str) converts the text in str to double precision values. [...] str can be a character vector, a cell array of character vectors, or a string array. [...] If str is [...] a string array, then X is a numeric array that is the same size as str. Thus, this should work: na = cellfun(@str2double, dataCellOut, 'UniformOutput', false); na = cat(1,na{:});
{ "pile_set_name": "StackExchange" }
Q: Cannot load Android Emulator on Ubuntu 10.04 When I trying run Android Emulation, i Have error message: $ tools/emulator -avd Default -verbose -debug-all emulator: found SDK root at /opt/android-sdk-linux_86 emulator: /home/jupeter/.android/avd/Default.ini: parsing as .ini file emulator: 1: KEY='target' VALUE='android-8' emulator: 2: KEY='path' VALUE='/home/jupeter/.android/avd/Default.avd' emulator: /home/jupeter/.android/avd/Default.ini: parsing finished emulator: root virtual device file at /home/jupeter/.android/avd/Default.ini emulator: virtual device content at /home/jupeter/.android/avd/Default.avd emulator: /home/jupeter/.android/avd/Default.avd/config.ini: parsing as .ini file emulator: 1: KEY='hw.lcd.density' VALUE='160' emulator: 2: KEY='sdcard.size' VALUE='200M' emulator: 3: KEY='skin.name' VALUE='HVGA' emulator: 4: KEY='skin.path' VALUE='platforms/android-8/skins/HVGA' emulator: 5: KEY='image.sysdir.1' VALUE='platforms/android-8/images/' emulator: /home/jupeter/.android/avd/Default.avd/config.ini: parsing finished emulator: virtual device config file: /home/jupeter/.android/avd/Default.avd/config.ini emulator: found image search path: platforms/android-8/images/ emulator: found a total of 1 search paths for this AVD emulator: no kernel-qemu in content directory emulator: found kernel-qemu in search dir: /opt/android-sdk-linux_86/platforms/android-8/images/ emulator: no ramdisk.img in content directory emulator: found ramdisk.img in search dir: /opt/android-sdk-linux_86/platforms/android-8/images/ emulator: no system.img in content directory emulator: found system.img in search dir: /opt/android-sdk-linux_86/platforms/android-8/images/ emulator: found userdata-qemu.img in content directory emulator: locking user data image at /home/jupeter/.android/avd/Default.avd/userdata-qemu.img emulator: found cache.img in content directory emulator: locking cache image at /home/jupeter/.android/avd/Default.avd/cache.img emulator: found sdcard.img in content directory emulator: locking SD Card image at /home/jupeter/.android/avd/Default.avd/sdcard.img emulator: found skin 'HVGA' in directory: platforms/android-8/skins emulator: autoconfig: -skin HVGA emulator: autoconfig: -skindir platforms/android-8/skins emulator: adding binding BUTTON_CALL to F3 emulator: adding binding BUTTON_HANGUP to F4 emulator: adding binding BUTTON_HOME to HOME emulator: adding binding BUTTON_BACK to ESCAPE emulator: adding binding BUTTON_MENU to F2 emulator: adding binding BUTTON_MENU to PAGEUP emulator: adding binding BUTTON_STAR to Shift-F2 emulator: adding binding BUTTON_STAR to PAGEDOWN emulator: adding binding BUTTON_POWER to F7 emulator: adding binding BUTTON_SEARCH to F5 emulator: adding binding BUTTON_CAMERA to Ctrl-KEYPAD_5 emulator: adding binding BUTTON_CAMERA to Ctrl-F3 emulator: adding binding BUTTON_VOLUME_UP to KEYPAD_PLUS emulator: adding binding BUTTON_VOLUME_UP to Ctrl-F5 emulator: adding binding BUTTON_VOLUME_DOWN to KEYPAD_MINUS emulator: adding binding BUTTON_VOLUME_DOWN to Ctrl-F6 emulator: adding binding TOGGLE_NETWORK to F8 emulator: adding binding TOGGLE_TRACING to F9 emulator: adding binding TOGGLE_FULLSCREEN to Alt-ENTER emulator: adding binding BUTTON_DPAD_CENTER to KEYPAD_5 emulator: adding binding BUTTON_DPAD_UP to KEYPAD_8 emulator: adding binding BUTTON_DPAD_LEFT to KEYPAD_4 emulator: adding binding BUTTON_DPAD_RIGHT to KEYPAD_6 emulator: adding binding BUTTON_DPAD_DOWN to KEYPAD_2 emulator: adding binding TOGGLE_TRACKBALL to F6 emulator: adding binding SHOW_TRACKBALL to DELETE emulator: adding binding CHANGE_LAYOUT_PREV to KEYPAD_7 emulator: adding binding CHANGE_LAYOUT_PREV to Ctrl-F11 emulator: adding binding CHANGE_LAYOUT_NEXT to KEYPAD_9 emulator: adding binding CHANGE_LAYOUT_NEXT to Ctrl-F12 emulator: adding binding ONION_ALPHA_UP to KEYPAD_MULTIPLY emulator: adding binding ONION_ALPHA_DOWN to KEYPAD_DIVIDE emulator: keyset loaded from: /home/jupeter/.android/default.keyset emulator: trying to load skin file 'platforms/android-8/skins/HVGA/layout' emulator: skin network speed: 'full' emulator: skin network delay: 'none' emulator: IP address of your DNS(s): 192.168.1.1 emulator: registered 'boot-properties' qemud service emulator: registered 'boot-properties' qemud service emulator: Adding boot property: 'qemu.sf.lcd_density' = '160' emulator: Adding boot property: 'dalvik.vm.heapsize' = '16m' emulator: argv[00] = "tools/emulator" emulator: argv[01] = "-kernel" emulator: argv[02] = "/opt/android-sdk-linux_86/platforms/android-8/images//kernel-qemu" emulator: argv[03] = "-initrd" emulator: argv[04] = "/opt/android-sdk-linux_86/platforms/android-8/images//ramdisk.img" emulator: argv[05] = "-nand" emulator: argv[06] = "system,size=0x4e00000,initfile=/opt/android-sdk-linux_86/platforms/android-8/images//system.img" emulator: argv[07] = "-nand" emulator: argv[08] = "userdata,size=0x4200000,file=/home/jupeter/.android/avd/Default.avd/userdata-qemu.img" emulator: argv[09] = "-nand" emulator: argv[10] = "cache,size=0x4200000,file=/home/jupeter/.android/avd/Default.avd/cache.img" emulator: argv[11] = "-hda" emulator: argv[12] = "/home/jupeter/.android/avd/Default.avd/sdcard.img" emulator: argv[13] = "-serial" emulator: argv[14] = "android-kmsg" emulator: argv[15] = "-serial" emulator: argv[16] = "android-qemud" emulator: argv[17] = "-append" emulator: argv[18] = "qemu=1 console=ttyS0 android.checkjni=1 android.qemud=ttyS1 android.ndns=1" emulator: argv[19] = "-m" emulator: argv[20] = "96" emulator: argv[21] = "-clock" emulator: argv[22] = "unix" emulator: mapping 'system' NAND image to /tmp/android/emulator-0Waqxc emulator: rounding devsize up to a full eraseunit, now 4e1e000 emulator: qesd_audio_init: entering emulator: could not find libesd on this system audio: Could not init `esd' audio driver emulator: using 'alsa' audio input backend emulator: qesd_audio_init: entering emulator: could not find libesd on this system audio: Could not init `esd' audio driver emulator: using 'alsa' audio output backend Inconsistency detected by ld.so: dl-version.c: 230: _dl_check_map_versions: Assertion `needed != ((void *)0)' failed! The problem is on last line: Inconsistency detected by ld.so: dl-version.c: 230: _dl_check_map_versions: Assertion `needed != ((void *)0)' failed! Any idea how to fix it? A: I found where was problem ... and i find out that it's not related with android application, but my one library. I have corrupted "/lib32/libdbus-1.so.3.4.0" file. I figured out, when I compare md5sum from my computer and new instalation of Ubuntu on VirtualBox. I this case probably couse of the problem was with my disk. Wrong md5sum: @/lib32# md5sum libdbus-1.so.3.4.0 a1ce67fa4e733bf94939e9a699d3a9ff libdbus-1.so.3.4.0 Correct md5sum: @:/lib32/# md5sum libc-2.11.1.so dba5fd388fe58c0865829192c0112ad1 libdbus-1.so.3.4.0
{ "pile_set_name": "StackExchange" }
Q: What breaks a working $_SESSION on another page? I have a weird problem. Which, I was using $_SESSION to show login errors to user. It was working with no problem. Few days ago, I have changed my host from a Plesk host to a cPanel host that runs safe_mod off. Somehow my $_SESSIONs at login page doesn't work. I test $_SESSION on index page and it works OK and it show nothing wrong with working of $_SESSION function. Both page included same session starter page. Also nothing works on login page when my functions file included. (sessions, post items, classes, functions etc. nothing.) But everything works on index page even if functions file included. What's happening here? What can be the reason? PS: I am using UserCake for members system. My server doesn't allow me to turn PHP errors at htaccess level and nothing seems with error_reporting(E_ALL); ini_set('display_errors', '1'); Also nothing seems relevant at my error logs. Edit: We succeeded to show errors using ini_set('error_reporting', 8191); ini_set('display_startup_errors', 1); ini_set('display_errors', 1); thanks to @J A but no errors seems. A: Either one of the following solutions. Put session_start(); on top of the pages you are accessing $_SESSION from. Check your php.ini, you can set session autostart to 1 if you don't want to follow the other solution.
{ "pile_set_name": "StackExchange" }
Q: Add on a MediaWiki geshi syntax highlight extension I use mediawiki to take note about the procedure that I follow, the source codes I write in mediawiki are highlighted with the expansion Genshi Syntax HighLight. I want to modify this expansion in mediawiki so it could be created a box above the source code in which it is written the programming language I used. I tried to see expansion sources in my mediawiki but I didn't find the segment in which is "sketch" the <div>. I also saw material about the creation of new expansion in mediawiki to understand how it runs, but I don't understand where the box is created. I use syntax hightligher like this some_code and this is the result in html code generate from mediawiki <div class="mw-geshi mw-code mw-content-ltr" dir="ltr"> <div class="bash source-bash"> <pre class="de1"> some_code </pre> </div> </div> I want to prepen the div to first div, like this <div class='gsh-lang-label'>Language bash</div> <div class="mw-geshi mw-code mw-content-ltr" dir="ltr"> <div class="bash source-bash"> <pre class="de1"> some_code </pre> </div> </div> Can you explain me if it is possible to do it and how can I face the problem? A: I think ordinary jQuery will solve this problem. Something like: $(".mw-geshi").each(function(){ $(this).before("<div class='gsh-lang-label'>" + $(this).children().first().attr("class").split(' ')[0] + "</div>") }) Put this in [[MediaWiki:Common.js]], so this script will be run for every user.
{ "pile_set_name": "StackExchange" }
Q: How do I say "no" to an ill friend who wants to leave hospital? A friend of mine (20-30) was recently admitted into hospital for minor surgery. When we visited him a few days later he was certainly better, but then the next day he told me that he was in pain and begged me to take him home. When I arrived, he was experiencing recurring headaches and occasional vomiting. I stayed throughout the day and heard him screaming and crying every time a headache struck. Eventually, the pain seemed to subside, so I decided not to stay the night and to visit him the next morning. In the morning, he asked to be discharged from hospital, despite not completing the therapy and still suffering from headaches and bouts of vomiting. His wanting to leave was against common sense: He should've waited until the treatment was ended and the symptoms were gone. But he begged me in a very "painful voice". He kept saying please. As a result, I found myself giving in to his request and helped him pack his things. Let's say the journey home was not enjoyable... Usually common sense tells me what to do. But in this case, I couldn't help but think of relieving my best friend from pain (although I believe it won't help him) by granting his request. I believe that he should have stayed at hospital. But next time, when a friend begs me to help him leave hospital How to effectively say no to his request, especially since he was unable to take a better judgment due to his pain? Logic seems out of option - he seemed to be in great pain, and it clouded his better judgment. Inquiry about his pain cannot produce a meaningful result due to unclear response and very soft voice. The symptoms actually are very confusing, because it happened suddenly and seemed to be unrelated to the surgery (knee vs head). The doctors could not give a satisfying answer and seemed to be only guessing, so it might add to his rage quitting the hospital. Update: The doctor dismissed the symptoms as post-surgery effect. However, they were puzzled by their appearance because of the unrelated location. I also find it hard to believe. I believe the symptoms will subside and disappear after several days, and he's not in any danger of dying, but I'm concerned about how he'll cope alone because no one is able to take care of him on weekdays. He's technically living "alone" with no next of kin nearby, and friends are unavailable during the day because of work. A: Consider the possibility that their main motivation was an addiction to either alcohol or a specific med, which they can pick up in their house but not in the hospital; and much of this is withdrawal symptoms/cold turkey. [Or combination of addiction like pills and caffein, giving an unusual combination of symptoms; tho I'm sure the doctors considered this.] This is unlikely, but very possible. (USA: over 7million battle drug addiction, out of 21.5million battling addictions.) A: If him staying in the hospital is beneficial to his health, I would not support his decision to leave. The question is whether the doctors have done every test possible and decided that his headaches and pain is merely a symptom of his surgery recovery and not an indication of something worse. For the first case, I would try to be strong for him, and help him understand that despite the doctors not having a solution to the immediate problem, staying and continuing the tests is beneficial. Hospital stay for many is insufferable but for me I've found that with the proper support, either you being there playing board games or him having a laptop to play / watch movies on, staying in the hospital can be seen as a vacation from the worries of the daily routine. If the case is the second case, that the pain is just a symptom and will go away on it's own, I would support his decision to go home. Pain is temporary and you forget that you had it once it goes away, the best way to alleviate it is to ignore it by having fun and distracting yourself. That's a lot easier to accomplish at home. As for your friendship, in both cases I believe a true friend would want the best medical result, even if it means losing the friendship. But that's not really a risk because as it may be hard now to explain to your friend why you're making this decision which he hates, he isn't thinking clearly because of pain and worries. Once he will recover he will be able to listen to your logic and understand that all you wanted was for his best, and hopefully he will understand. I know that if I was him, I would much prefer a friend who works against me in my favor than one who enables me in my own destruction. I've had many complex surgeries with weeks of pain and recovery, and for the most part, I handle it alone and don't ask (or even tell) my friends about what's going on. The fact that he has confided in you in this time means that the friendship is strong and he does want your help coping with the situation. Sometimes when in extreme pain we revert to a more primitive state, (I've seen this in cognitive elders who cry out for their mothers despite knowing that they are long gone). If you do think staying in the hospital is the right choice, being strong and assertive, without bargaining or discussing the option of going home, can be a good method of passing the message. A: Try to find out what the reason is your friend wants to leave the hospital so badly. The fact that this friend is so insistent about going home suggests that there is a strong reason they want to leave. Without knowing the reason, you can't make an informed decision, nor can anyone on this site give you good advice. For example, the reason might be that a case of an addiction and withdrawal from that addiction as user3445853 suggests. Alternatively, the reason may be that the setting of the hospital room is causing mental distress. As you may be able to see, the whole discussion on whether or not you should take him home changes completely. It's also quite likely you may have a better grasp on what to do yourself.
{ "pile_set_name": "StackExchange" }
Q: Lower bound on a minimum of maximum of a sequence of standard normal random variables Let $X = (x_{ij}) \in \mathbb{R}^{n \times p}$ be a matrix with independent $N(0,1)$ entries. We know that $\max_j x_{ij} < \sqrt{2\log(p/\delta)}$ with probability at least $1-\delta$. I would like to obtain a lower bound for $\min_i (\max_j x_{ij})$ that holds with probability at least $1-\delta$. Could somebody point to a relevant reference please? A: You know that $$\Pr(\max_j x_{ij} \le k) = \Phi(k)^p$$ so $$\Pr(\max_j x_{ij} \gt k) = 1 - \Phi(k)^p$$ so $$\Pr(\min_i (\max_j x_{ij}) \gt k) = \left(1 - \Phi(k)^p\right)^n $$ so $$\Pr(\min_i (\max_j x_{ij}) \le k) = 1- \left(1 - \Phi(k)^p\right)^n $$ and if this is is equal to $1-\delta$ then $$k = \Phi^{-1}\left( (1- \delta^{\frac{1}{n}})^{\frac{1}{p}} \right)$$
{ "pile_set_name": "StackExchange" }
Q: MySQL Error : #1005 - Can't create table (errno: 150) When I try create more than 1 FK I have this table: CREATE TABLE IF NOT EXISTS `produtos` ( `id` int(11) NOT NULL auto_increment, `idcatprodutos` int(11) NOT NULL, `idcategoria` int(11) NOT NULL, `idmarca` int(11) NOT NULL, `nome` varchar(100) NOT NULL, PRIMARY KEY (`id`), KEY `FK_produtos_2` (`idcatprodutos`), KEY `FK_produtos_3` (`idmarca`), KEY `FK_produtos_4` (`idcategoria`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC AUTO_INCREMENT=39 ; and this table: CREATE TABLE IF NOT EXISTS `sugestoes` ( `id` int(11) NOT NULL auto_increment, `idproduto` int(11) NOT NULL, `idsugestao1` int(11) NOT NULL, `idsugestao2` int(11) NOT NULL, `idsugestao3` int(11) NOT NULL, `idsugestao4` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `FK_sugestoes_prod` (`idproduto`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED AUTO_INCREMENT=9 ; I already have created a fk sugestoes.idproduto -> produtos.id working, but I want each of the other fields also refer to the produtos.id through new FK. Run this command below that return MySQL Error : #1005 - Can't create table (errno: 150): ALTER TABLE `infantile`.`sugestoes` ADD CONSTRAINT `FK_sugestoes_2` FOREIGN KEY `FK_sugestoes_2` (`idsugestao1`) REFERENCES `produtos` (`id`) ON DELETE SET NULL ON UPDATE CASCADE , ROW_FORMAT = FIXED; Does anyone have any idea what's going on? A: Try this, it works: ALTER TABLE `sugestoes` ADD CONSTRAINT `FK_idproduto_produtos_1` FOREIGN KEY (`idproduto`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_2` FOREIGN KEY (`idsugestao1`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_3` FOREIGN KEY (`idsugestao2`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_4` FOREIGN KEY (`idsugestao3`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_5` FOREIGN KEY (`idsugestao4`) REFERENCES `produtos` (`id`) UPDATE: You can not specify ON DELETE SET NULL Because of this: You have defined a SET NULL condition though some of the columns are defined as NOT NULL You can see exact error when you run SHOW ENGINE INNODB STATUS;
{ "pile_set_name": "StackExchange" }
Q: Django: multiple models with one-to-many relation on admin page TabularInline I have multiple models in an existing database that all have a many-to-one relation to another model. For example: class Collection(models.Model): start = models.DateTimeField() end = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'Program' class ItemA(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'ItemA' class ItemB(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'ItemB' What I want to do, is show these models in a single TabularInline on the admin page of the Collection model. I also want to be able to filter the models. Is this possible without inheritance in the database? (I don't want to add a general item table). In the documentation, I can only find how you can use TabularInline for a single model. So my question is basically: What would be the best approach to solve this? Is it maybe possible to define some kind of view model dat is not in the database, but that can be used to display all the items in a TabularInline? A: I ended up using a view in my database, meaning that I did not need to add a table. In Django, I created a model to handle the view: class Item(models.Model): collection = models.ForeignKey( 'Collection', models.CASCADE, db_column='Collection_id') ... class Meta: managed = False db_table = 'Item' # This is not a table, but a view I defined the View by using multiple SELECT statements and UNION: CREATE OR REPLACE VIEW `Item` AS SELECT CONCAT('itemA_',id) as id, name, ... FROM ItemA UNION SELECT CONCAT('itemB_',id) as id, name, ... FROM ItemB ...
{ "pile_set_name": "StackExchange" }
Q: Calculating $d(xdx + z^2dy + xydz)$ Inspired by this answer, I am trying to learn about differential forms. I am going through these notes were (on page 3) $d(xdx + z^2dy + xydz)$. I believe that the formula that I should use is $$ df = \frac{\partial f}{\partial x}dx + \frac{\partial f}{\partial y}dy + \frac{\partial f}{\partial z}dz. $$ So for example I get $$ d(xy) = ydx + xdy. $$ The notes seem to say that $d(xy) = dx + dy$ so I am a bit confused. What am I doing wrong? A: It is a typo. It is indeed true that $d(xy)=ydx+xdy$. In short, to calculate with differential forms you take total derivatives paired with the wedge product. The wedge product has $dx_i \wedge dx_j= -dx_j\wedge dx_i $ hence $dx_i \wedge dx_i=0$ for all $i$. Then, you extend that rule naturally. In the same way, we could say complex numbers are just real numbers paired with some new element $i$ such that $i^2=-1$ then multiplication and addition proceeds as usual.
{ "pile_set_name": "StackExchange" }
Q: Subversion branching when trunk/branches buried in subtree I've been tasked with work on an SVN repository organized as follows: REPO_ROOT |-AAA |-BBB |-DDD |-D1 |-D2 |-software |-branches |-tags |-trunk |-YYY |-ZZZ I'm working mostly on ^/DDD/software/trunk. Now I'd like to create a branch to do some error fixing at ^/DDD/software/branches/error-fixing. First I created and committed the ^/DDD/software/branches/error-fixing directory which did not exist. Then I created a branch of trunk using the command: $ svn copy svn+ssh://[email protected]/REPO_ROOT/DDD/software/trunk svn+ssh://[email protected]/REPO_ROOT/DDD/software/branches/error-fixing -m "Branching from trunk to error-fixing". Now I need to switch to the correct branch. I'm inside trunk and using the command $ svn switch "^/DDD/software/branches/error-fixing" . but this fails with svn: E195012: Path '.' does not share common version control ancestry with the requested switch location. How can I switch to the branch? (First time I'm doing this so I may have done something wrong.) A: The problem comes from the way the branch was created. I first created the error directory and then did the svn copy. This causes the trunk directory to be copied into error-fixing instead of just its contents resulting in ^/DDD/software/branches/error-fixing/trunk/<files> instead of ^/DDD/software/branches/error-fixing/<files>. Found out about the subtle difference here. That's why trunk and error-fixing did not share a common ancestry, the contents were different. Once I svn-removed error-fixing and did the svn copy without previously creating error-fixing, the svn switch worked fine.
{ "pile_set_name": "StackExchange" }
Q: Map a column to be IDENTITY in db Although I have marked my ID column with .Identity(), the generated database schema doesn't have IDENTITY set to true, which gives me problems when I'm adding records. If I manually edit the database schema (in SQL Management Studio) to have the Id column marked IDENTITY, everything works as I want it - I just can't make EF do that by itself. This is my complete mapping: public class EntryConfiguration : EntityConfiguration<Entry> { public EntryConfiguration() { Property(e => e.Id).IsIdentity(); Property(e => e.Amount); Property(e => e.Description).IsRequired(); Property(e => e.TransactionDate); Relationship(e => (ICollection<Tag>)e.Tags).FromProperty(t => t.Entries); } } As I'm using EF to build and re-build the database for integration testing, I really need this to be done automatically... EDIT: Hm... In a comment I was requested to give enough code to execute this, so I cut-and-pasted my code into a console app (so you wouldn't need all my classes...) and suddenly it just worked. I guess I was forgetting some method call somewhere, although I haven't been able to figure out where. I'll post the working solution code in an answer to this post, in case someone else comes looking for it. A: Running this code solves the problem. I guess I must have forgot a step somewhere, so if you have the same problem, make sure you do all these things: var connection = GetUnOpenedSqlConnection(); // Any connection that inherits // from DbConnection is fine. var builder = new ContextBuilder<ObjectContext>(); // I actually had my own class // that inherits from // ObjectContext, but that was // not the issue (I checked). builder.Configurations.Add(EntryConfiguration); // EntryConfiguration is the // class in the question var context = builder.Create(connection); if (context.DatabaseExists()) { context.DeleteDatabase(); } context.CreateDatabase();
{ "pile_set_name": "StackExchange" }
Q: Restart script instead of turning it off when error happens in python selenium I have this python selenium script that after few minutes always throws some kind of error. Usually because chrome runs out of memory or there is some problem with proxy, but other errors also so its hard to catch them all. More simple for me would be solution, that the script would just restart itself every time there is an error. I know how to restart script, I just don't know how to tell python to do it when ANY error happens. Another solution would be something like "error ignore" because my script is already set to restart itself every x loops, but I cannot find anything like that for python. A: You could catch every kind of error by just using a try/except around your whole code, and then restart the function in your except statement when any kind of error occurs. Here is a snippet of pseudo code: def myfunc(): try: do_something except: # or catch one specific error with 'except AttributeError:' myfunc()
{ "pile_set_name": "StackExchange" }
Q: Formal regular expression for a language over a,b,c such that a is never adjacent to b I am trying to write a regex query for a language with letters a,b,c such that a is never adjacent to b. Can it be done by using only the alternation (plus), concatenation and repetition (multiplication) operators? L = w belongs to {a,b,c}* such that a is never adjacent to b A: (Lets see if I recall enough formal language theory.) Such a regular expression could be built with help of a DFA like this: A = aA + cC + F // only a or c can follow a B = bB + cC + F // only b or c can follow b C = cC + aA + bB + F // any char can follow c Where A, B and C are states representing the state when a, b and c respectively was the previous character. Since any character can follow c we can make C our start state. F being the final end state (end of string). This DFA can be converted to a regular expression like this: A = a*(cC+F) // eliminate recursion B = b*(cC+F) // eliminate recursion C = cC + aA + bB + F = cC + aa*(cC+F) + bb*(cC+F) + F // substitute A and B = (c + aa*c + bb*c)C + aa*F + bb*F + F // regroup = (c + aa*c + bb*c)*(aa*F + bb*F + F) // eliminate recursion = (c + aa*c + bb*c)*(aa* + bb* + e)F // regroup So the expression would be: (c + aa*c + bb*c)*(aa* + bb* + e) // e being the empty/null string Or in informal regex format: (c|a+c|b+c)*(a+|b+)? Which can be shortened to: (a+c|b*c)*(a*|b*)
{ "pile_set_name": "StackExchange" }
Q: Which gem is breaking Rails application.css.scss wrong number of arguments 3 for 2 Okay. This is a new problem caused by a gem update. Calling bundle update breaks my rails application. Here are the gems that changed: # Gemfile.lock - compass (0.12.7) + compass (0.12.2) - sass (~> 3.2.19) + sass (~> 3.1) - country_select (2.0.1) # Not likely this + country_select (2.1.0) # Not likely this - devise (3.3.0) + devise (3.4.0) + responders - excon (0.39.6) - execjs (2.2.1) + excon (0.40.0) + execjs (2.2.2) - jbuilder (2.1.3) + jbuilder (2.2.2) - jquery-ui-rails (5.0.0) + jquery-ui-rails (5.0.1) - mime-types (2.3) + mime-types (2.4.2) - netrc (0.7.7) + netrc (0.8.0) - omniauth-twitter (1.0.1) # Not likely this + omniauth-twitter (1.1.0) # Not likely this - railroady (1.1.2) # Not likely this + railroady (1.2.0) # Not likely this - rails_12factor (0.0.2) + rails_12factor (0.0.3) - rails_layout (1.0.22) + rails_layout (1.0.23) - sass (3.2.19) + sass (3.2.0) - sprockets-rails (2.1.4) + sprockets-rails (2.2.0) - sprockets (~> 2.8) + sprockets (>= 2.8, < 4.0) - turbolinks (2.3.0) + turbolinks (2.4.0) - twilio-ruby (3.13.0) # Not likely this + twilio-ruby (3.13.1) # Not likely this The error I get is: wrong number of arguments (3 for 2) (in /app/assets/stylesheets/application.css.scss) And better errors shows it happening at this line: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> If you can tell me which gem is responsible for the error I can version out the new one in my Gemfile. It does the same thing on my local machine and Heroku. I'm maintaining the older Gemfile.lock for now. For the record I tried installing each gem individually. Afterwards I had no problem on the local machine, but Heroku failed with the same error and would not build. Following Paul Richter's tip it's either compass, sprockets, or sass sass-rails (4.0.3) lib/sass/rails/importer.rb:80:in `engine_from_path' sass-rails (4.0.3) lib/sass/rails/importer.rb:27:in `find_relative' sass (3.2.0) lib/sass/tree/import_node.rb:45:in `import' sass (3.2.0) lib/sass/tree/import_node.rb:25:in `imported_file' sass (3.2.0) lib/sass/tree/import_node.rb:34:in `css_import?' sass (3.2.0) lib/sass/tree/visitors/perform.rb:214:in `visit_import' sass (3.2.0) lib/sass/tree/visitors/base.rb:37:in `visit' sass (3.2.0) lib/sass/tree/visitors/perform.rb:97:in `visit' sass (3.2.0) lib/sass/tree/visitors/base.rb:53:in `block in visit_children' sass (3.2.0) lib/sass/tree/visitors/base.rb:53:in `visit_children' sass (3.2.0) lib/sass/tree/visitors/perform.rb:106:in `block in visit_children' sass (3.2.0) lib/sass/tree/visitors/perform.rb:118:in `with_environment' sass (3.2.0) lib/sass/tree/visitors/perform.rb:105:in `visit_children' sass (3.2.0) lib/sass/tree/visitors/base.rb:37:in `block in visit' sass (3.2.0) lib/sass/tree/visitors/perform.rb:125:in `visit_root' sass (3.2.0) lib/sass/tree/visitors/base.rb:37:in `visit' sass (3.2.0) lib/sass/tree/visitors/perform.rb:97:in `visit' sass (3.2.0) lib/sass/tree/visitors/perform.rb:7:in `visit' sass (3.2.0) lib/sass/tree/root_node.rb:20:in `render' sass (3.2.0) lib/sass/engine.rb:315:in `_render' sass (3.2.0) lib/sass/engine.rb:262:in `render' compass-rails (2.0.0) lib/compass-rails/patches/sass_importer.rb:29:in `evaluate' tilt (1.4.1) lib/tilt/template.rb:103:in `render' sprockets (2.11.0) lib/sprockets/context.rb:197:in `block in evaluate' sprockets (2.11.0) lib/sprockets/context.rb:194:in `evaluate' sprockets (2.11.0) lib/sprockets/processed_asset.rb:12:in `initialize' sprockets (2.11.0) lib/sprockets/base.rb:374:in `block in build_asset' sprockets (2.11.0) lib/sprockets/base.rb:395:in `circular_call_protection' sprockets (2.11.0) lib/sprockets/base.rb:373:in `build_asset' sprockets (2.11.0) lib/sprockets/index.rb:94:in `block in build_asset' sprockets (2.11.0) lib/sprockets/caching.rb:58:in `cache_asset' sprockets (2.11.0) lib/sprockets/index.rb:93:in `build_asset' sprockets (2.11.0) lib/sprockets/base.rb:287:in `find_asset' sprockets (2.11.0) lib/sprockets/index.rb:61:in `find_asset' sprockets (2.11.0) lib/sprockets/bundled_asset.rb:16:in `initialize' sprockets (2.11.0) lib/sprockets/base.rb:377:in `build_asset' sprockets (2.11.0) lib/sprockets/index.rb:94:in `block in build_asset' sprockets (2.11.0) lib/sprockets/caching.rb:58:in `cache_asset' sprockets (2.11.0) lib/sprockets/index.rb:93:in `build_asset' sprockets (2.11.0) lib/sprockets/base.rb:287:in `find_asset' sprockets (2.11.0) lib/sprockets/index.rb:61:in `find_asset' sprockets (2.11.0) lib/sprockets/environment.rb:75:in `find_asset' sprockets (2.11.0) lib/sprockets/base.rb:295:in `[]' sprockets-rails (2.2.0) lib/sprockets/rails/helper.rb:230:in `lookup_asset_for_path' sprockets-rails (2.2.0) lib/sprockets/rails/helper.rb:190:in `check_errors_for' sprockets-rails (2.2.0) lib/sprockets/rails/helper.rb:159:in `block in stylesheet_link_tag' sprockets-rails (2.2.0) lib/sprockets/rails/helper.rb:158:in `stylesheet_link_tag' A: The problem is with sass. Here's a link to the the official issue. Locking sass-rails to version 4.0.3 has worked for me on rails-4.0.x through rails-4.1.x. In your Gemfile: gem 'sass-rails', '4.0.3' UPDATE A better solution I have found is to use the 4-0-stable branch: gem 'sass-rails', github: 'rails/sass-rails', branch: '4-0-stable' A: I believe this is actually a problem with sass and compass dependencies. I had the same issue in Rails 4.1.5. The default Gemfile includes: gem 'sass-rails', '~> 4.0.3' But a simple bundle update within the last month (Oct/Nov 2014) breaks the application. I was able to fix it by adding the following lines to my Gemfile to preserve the dependencies between compass and sass: gem 'sass', '~> 3.2.19' gem 'compass', '~> 0.12.7' gem 'compass-rails', '~> 2.0.0' Update Dec 2014: I ran into this same issue again after trying to upgrade to Zurb Foundation 5.5. It seems like the main culprit is the compass-rails gem. Even after I pulled out the gem, I found that a different gem I was using (chosen-rails) was pulling it back in. After getting rid of all the sass and compass lines (and chosen-rails), the following works for me: gem 'sass-rails', '~> 5.0.0' gem 'foundation-rails', '~> 5.5' A: bundle update sass did the trick.
{ "pile_set_name": "StackExchange" }
Q: Hadoop MapReduce sort reduce output using the key down below there is a map-reduce program counting words of several text files. My aim is to have the result in a descending order regarding the amount of appearences. Unfortunately the program sorts the output lexicographically by the key. I want a natural order of the integer value. So I added a custom comparator with job.setSortComparatorClass(IntComparator.class). But this doesn't work as expected. I'm getting the following exception: java.lang.Exception: java.nio.BufferUnderflowException at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:404) Caused by: java.nio.BufferUnderflowException at java.nio.Buffer.nextGetIndex(Buffer.java:498) at java.nio.HeapByteBuffer.getInt(HeapByteBuffer.java:355) at WordCount$IntComparator.compare(WordCount.java:128) at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.compare(MapTask.java:987) at org.apache.hadoop.util.QuickSort.sortInternal(QuickSort.java:100) at org.apache.hadoop.util.QuickSort.sort(QuickSort.java:64) at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.sortAndSpill(MapTask.java:1277) at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.flush(MapTask.java:1174) at org.apache.hadoop.mapred.MapTask$NewOutputCollector.close(MapTask.java:609) at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:675) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:330) at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:266) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) Any help would be appreciated! :) I've listed the whole program below as there may be a reason for the exception which I obviously don't know. As you can see I am using the new mapreduce api (org.apache.hadoop.mapreduce.*). import java.io.IOException; import java.nio.ByteBuffer; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; /** * Counts the words in several text files. */ public class WordCount { /** * Maps lines of text to (word, amount) pairs. */ public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> { private Text word = new Text(); private IntWritable amount = new IntWritable(1); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String textLine = value.toString(); StringTokenizer tokenizer = new StringTokenizer(textLine); while (tokenizer.hasMoreElements()) { word.set((String) tokenizer.nextElement()); context.write(word, amount); } } } /** * Reduces (word, amount) pairs to (amount, word) list. */ public static class Reduce extends Reducer<Text, IntWritable, IntWritable, Text> { private IntWritable amount = new IntWritable(); private int sum; @Override protected void reduce(Text key, Iterable<IntWritable> valueList, Context context) throws IOException, InterruptedException { sum = 0; for (IntWritable value : valueList) { sum += value.get(); } amount.set(sum); context.write(amount, key); } } public static class IntComparator extends WritableComparator { public IntComparator() { super(IntWritable.class); } private Integer int1; private Integer int2; @Override public int compare(byte[] raw1, int offset1, int length1, byte[] raw2, int offset2, int length2) { int1 = ByteBuffer.wrap(raw1, offset1, length1).getInt(); int2 = ByteBuffer.wrap(raw2, offset2, length2).getInt(); return int2.compareTo(int1); } } /** * Job configuration. * * @param args * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Path inputPath = new Path(args[0]); Path outputPath = new Path(args[1]); Configuration configuration = new Configuration(); configuration.addResource(new Path("/etc/hadoop/conf/core-site.xml")); Job job = new Job(configuration); job.setJobName("WordCount"); job.setJarByClass(WordCount.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); job.setSortComparatorClass(IntComparator.class); FileInputFormat.setInputPaths(job, inputPath); FileSystem.get(configuration).delete(outputPath, true); FileOutputFormat.setOutputPath(job, outputPath); job.waitForCompletion(true); } } A: The comparator step occurs between the Mapper and Reducer, which wont work for you as you swap the key and value around in the Reducer itself. The default WritableComparator would normally handle your numerical ordering if the key was IntWritable, except it's getting a Text key thus resulting in lexicographical ordering. As to why exactly the output at the end isn't sorted by your written out IntWritable key, I'm unsure. Perhaps it has something to do with the way TextOutputFormat works? You might have to dig deeper into TextOutputFormat source code for clues on that, but in short, setting the sort comparator probably won't help you here I'm afraid.
{ "pile_set_name": "StackExchange" }
Q: Basis for Solution Space of Differential Equation Quick question for my differential equations and linear algebra homework. Say we have a differential equation that has the general solution $$ y = c_1e^{-2x} + c_2e^{-2x} $$ where $c1$, $c2$ are arbitrary constants. I need to find the basis for this. If the exponents had opposite signs, the basis would just be: $$ \{e^{-2x},\ e^{2x}\} $$ But since they are the same, and the exponent has an algebraic multiplicity of $2$, I'm not quite sure of the proper way to state the basis. I could see the basis being $\{e^{-2x}\}$, or $\{e^{-2x},\ e^{-2x}\}$, or even $\{0,\ e^{-2x}\}$. Thanks in advance guys. A: HINT: Notice, if the roots are equal then the general solution of differential equation: $\frac{d^2y}{dx^2}+4x\frac{dy}{dx}+4x^2y=0$ is given as $$y=(c_1+xc_2)e^{-2x}$$ while the basis, $e^{-2x}$ & $e^{2x}$ shows that roots are distinct of differential equation $\frac{d^2y}{dx^2}-4x^2y=0$ whose general solution is given as $$y=c_1e^{2x}+c_2e^{-2x}$$
{ "pile_set_name": "StackExchange" }
Q: Using adply in data.table I have a big data.table that looks like: dt<-data.table(start=c("2012-07-13 23:45:00", "2012-07-14 15:30:00", "2012-07-14 23:57:00"), end=c("2012-07-14 00:02:00", "2012-07-14 15:35:00", "2012-07-15 00:05:00"), id=c(1,2,1),cat=c("a","b","a")) dt start end id cat 1: 2012-07-13 23:45:00 2012-07-14 00:02:00 1 a 2: 2012-07-14 15:30:00 2012-07-14 15:35:00 2 b 3: 2012-07-14 23:57:00 2012-07-15 00:05:00 1 a I need to get an output that shows total minutes of event on each calendar day by id and category. Using the example above the output should be: day id cat V1 1: 13.07.2012 1 a 15 2: 14.07.2012 1 a 5 3: 14.07.2012 2 b 5 4: 15.07.2012 1 a 5 I used adply function from plyr package to split duration in intervals by minute: fn<-function(x){ s<-seq(from = as.POSIXct(x$start), to = as.POSIXct(x$end)-1,by = "mins") # here s is a sequence of all minutes in the given interval df<-data.table(x$id,x$cat,s) # return new data.table that contains each calendar minute for each id # and categoryy of the original data df } # run the function above for each row in the data.table dd<-adply(dt,1,fn) # extract the date from calendar minutes dd[,day:=format(as.POSIXct(s,"%d.%m.%Y %H:%M%:%S"), "%d.%m.%Y")] #calculate sum of all minutes of event for each day, id and category dd[,.N,by=c("day","id","cat")][order(day,id,cat)] The solution above perfectly suits my needs except the time it takes for calculation. When adply is run in a very big data and several categories defined in fn function, it feels like CPU runs forever. I will highly appreciate any hint on how to use pure data.table functionality in this problem. A: I would suggest a few things Convert to as.POSIXct only once instead of per each row. instead of adply which creates a whole data.table in each iteration, just use by within the data.table scope. In order to do so, simple create an row index using .I Here's a quick attempt (I've used substr because it will be probably faster than as.Date or as.POSIXct. If you want it to be Date class again, use res[, Date := as.IDate(Date)] on the result istead of doing it by group). dt[, `:=`(start = as.POSIXct(start), end = as.POSIXct(end), indx = .I)] dt[, seq(start, end - 1L, by = "mins"), by = .(indx, id, cat) ][, .N, by = .(Date = substr(V1, 1L, 10L), id, cat)] # Date id cat N # 1: 2012-07-13 1 a 15 # 2: 2012-07-14 1 a 5 # 3: 2012-07-14 2 b 5 # 4: 2012-07-15 1 a 5
{ "pile_set_name": "StackExchange" }
Q: Assigning a value to specific product I was wondering if there is a way to assign a value to a specific problem. For example if I wanted $a\cdot a$ to equal $-1$. How would I go about doing that? A: If all you are looking for is a basic implementation of quaternions, then there is no need to implement them yourself, since they are already built-in: << Quaternions` Quaternion[0, 1, 0, 0] ** Quaternion[0, 1, 0, 0] producing Quaternion[-1, 0, 0, 0] as you asked for.
{ "pile_set_name": "StackExchange" }
Q: Pyspark error on creating dataframe: 'StructField' object has no attribute 'encode' I'm facing a little issue when creating a dataframe: from pyspark.sql import SparkSession, types spark = SparkSession.builder.appName('test').getOrCreate() df_test = spark.createDataFrame( ['a string', 1], schema = [ types.StructField('col1', types.StringType(), True), types.StructField('col2', types.IntegerType(), True) ] ) ## AttributeError: 'StructField' object has no attribute 'encode' I don't see anything wrong with my code (it's so simple I feel really dumb). But I can't get this to work. Can you point me in the right direction? A: You were most of the way there! When you call createDataFrame specifying a schema, the schema needs to be a StructType. An ordinary list isn't enough. Create an RDD of tuples or lists from the original RDD; Create the schema represented by a StructType matching the structure of tuples or lists in the RDD created in the step 1. Apply the schema to the RDD via createDataFrame method provided by SparkSession. Also, the first field in createDataFrame is a list of rows, not a list of values for one row. So a single one-dimensional list will cause errors. Wrapping it in a dict that explicitly identifies which columns hold which values is one solution, but there might be others. The result should look something like: df_test = spark.createDataFrame( [{'col1': 'a string', 'col2': 1}], schema = types.StructType([ types.StructField('col1', types.StringType(), True), types.StructField('col2', types.IntegerType(), True) ]) )
{ "pile_set_name": "StackExchange" }
Q: AUTOEXEC Configuration for DOSBOX doesn't work (Works on Windows) I'm trying to configure the Autoexec section of Dosbox. I downloaded DOSBOX for Windows and I added these lines : [autoexec] # Lines in this section will be run at startup. # You can put your MOUNT lines here. MOUNT C C:\DOSGAMES\ C: I saved and ran Dosbox.exe, it worked ! I'm doing the same thing for Dosbox in Fedora 30, configuring the file dosbox-0.74.conf located in /usr/share/dosbox/translations/fr. But when I run it, it doesn't work. Here is a screenshot : http://image.noelshack.com/fichiers/2019/30/2/1563874333-dosboxconf.jpg It worked for Windows... I tried to put these lines on each dosbox-0.74.conf located in each translation folder, but still not working. I think that the application doesn't run this configuration file, it seems to be another file, but which one? I've made a search of dosbox and these were the only files existing. A: The .dosbox folder was hidden by design. Each user have its own default config file in ~/.dosbox/dosbox.conf . For root, go in /root/ and do Ctrl+H , and hidden folders will appear. You can choose other config files with the corresponding flag, so make sure to configure the right dosbox.conf file.
{ "pile_set_name": "StackExchange" }
Q: Does proxy setting affect the working of Azure bot? Symbols for Microsoft.Recognizer.Text.* and Microsoft.Recognizer.Definitions, taking time to load after removal of proxy. I made a simple greeting bot using bot framework v4 using asp.net core. I'm working in an environment where proxy is set up. However, I've not connected it with Microsoft Azure yet. I'm just running it locally and testing it on emulator, so it has no internet requirements. Due to some other issue, I need to remove the proxy whenever I run the bot. But whenever I do so, symbols for Microsoft.Recognizer.Text.* and Microsoft.Recognizer.Definitions, take time to load, due to which there is a large time delay after every numeric, date, time input. I'm a beginner to bot framework so please help me resolve this issue. A: Microsoft.Recognizer.Text.*, et al., is a dependency of Microsoft.Bot.Builder.Dialogs. If you're having difficulty loading it, try updating your nuget packages, or even doing a standalone installation of Microsoft.Recognizers.Text
{ "pile_set_name": "StackExchange" }
Q: conditional date query in mysql I'm trying to structure a query which returns data which if priority = emergency is in the last 2 weeks, and if urgent is in the last month. WHERE ((priority = 'emergency' and date > DATE_SUB(NOW(), INTERVAL 14 DAY)) or priority = 'urgent' and date > DATE_SUB(NOW(), INTERVAL 30 DAY)) I know this isn't right, but I'm not sure how to do it. A: It just looks like your parentheses are in the wrong place: WHERE ( priority = 'emergency' and date > DATE_SUB(NOW(), INTERVAL 14 DAY) ) OR ( priority = 'urgent' and date > DATE_SUB(NOW(), INTERVAL 30 DAY) ) Since not all months are 30 days you might have to adjust the interval if you want strictly one month back.
{ "pile_set_name": "StackExchange" }
Q: Numpy fast check for complete array equality, like Matlabs isequal In Matlab, the builtin isequal does a check if two arrays are equal. If they are not equal, this might be very fast, as the implementation presumably stops checking as soon as there is a difference: >> A = zeros(1e9, 1, 'single'); >> B = A(:); >> B(1) = 1; >> tic; isequal(A, B); toc; Elapsed time is 0.000043 seconds. Is there any equavalent in Python/numpy? all(A==B) or all(equal(A, B)) is far slower, because it compares all elements, even if the initial one differs: In [13]: A = zeros(1e9, dtype='float32') In [14]: B = A.copy() In [15]: B[0] = 1 In [16]: %timeit all(A==B) 1 loops, best of 3: 612 ms per loop Is there any numpy equivalent? It should be very easy to implement in C, but slow to implement in Python because this is a case where we do not want to broadcast, so it would require an explicit loop. Edit: It appears array_equal does what I want. However, it is not faster than all(A==B), because it's not a built-in, but just a short Python function doing A==B. So it does not meet my need for a fast check. In [12]: %timeit array_equal(A, B) 1 loops, best of 3: 623 ms per loop A: First, it should be noted that in the OP's example the arrays have identical elements because B=A[:] is just a view onto the array, so: >>> print A[0], B[0] 1.0, 1.0 But, although the test isn't a fit one, the basic complaint is true: Numpy does not have a short-circuiting equivalency check. One can easily see from the source that all of allclose, array_equal, and array_equiv are just variations upon all(A==B) to match their respective details, and are not notable faster. An advantage of numpy though is that slices are just views, and are therefore very fast, so one could write their own short-circuiting comparison fairly easily (I'm not saying this is ideal, but it does work): from numpy import * A = zeros(1e8, dtype='float32') B = A[:] B[0] = 1 C = array(B) C[0] = 2 D = array(A) D[-1] = 2 def short_circuit_check(a, b, n): L = len(a)/n for i in range(n): j = i*L if not all(a[j:j+L]==b[j:j+L]): return False return True In [26]: %timeit short_circuit_check(A, C, 100) # 100x faster 1000 loops, best of 3: 1.49 ms per loop In [27]: %timeit all(A==C) 1 loops, best of 3: 158 ms per loop In [28]: %timeit short_circuit_check(A, D, 100) 10 loops, best of 3: 144 ms per loop In [29]: %timeit all(A==D) 10 loops, best of 3: 160 ms per loop
{ "pile_set_name": "StackExchange" }
Q: What is this Excel formula doing? Can someone please explain in English wtf this formula is doing? I'm looking at someone else's work and have no idea. =SUM(OFFSET(INDIRECT((ADDRESS(ROW(),21)),0,0,1)CurrentActualPeriod)) A: Agreeing with jeffreymb, you can also use the Evaluate Formula function in Excel to step through the nested functions one at a time (if you have Excel 2007). Here is documentation and a screenshot on how that works: http://office.microsoft.com/en-us/excel-help/evaluate-a-nested-formula-one-step-at-a-time-HP010066254.aspx
{ "pile_set_name": "StackExchange" }
Q: Read text last 7 days I am trying to read several text files which have text with date and success. The Idea is to read logs from the last 7 days which are continuously a success. Example of logs: 12/5/2018 3:40:08 AM: Something_secret.txt Successfully 6335 12/6/2018 3:40:06 AM: Something_secret.txt Successfully 6337 12/7/2018 3:40:10 AM: Something_secret.txt Successfully 6338 12/8/2018 3:40:09 AM: Something_secret.txt Successfully 6342 12/9/2018 3:40:09 AM: Something_secret.txt Successfully 6342 12/10/2018 3:40:11 AM: Something_secret.txt Successfully 6342 12/11/2018 3:40:07 AM: Something_secret.txt Successfully 6342 12/12/2018 3:40:10 AM: Something_secret.txt Successfully 6344 12/13/2018 3:40:10 AM: Something_secret.txt Successfully 6347 Log type 2: 12/6/2018 3:40:06 AM: Something_secret.txt Successfully 6337 12/7/2018 3:40:10 AM: Something_secret.txt Successfully 6338 12/8/2018 3:40:09 AM: Something_secret.txt Successfully 6342 12/9/2018 3:40:09 AM: Something_secret.txt Successfully 6342 12/10/2018 3:40:11 AM: Something_secret.txt file Not found 12/11/2018 3:40:07 AM: Something_secret.txt Successfully 6342 12/12/2018 3:40:10 AM: Something_secret.txt Successfully 6344 12/13/2018 3:40:10 AM: Something_secret.txt file Not found I have created this $files = gci C:\Users\Desktop\xx foreach ($file in $files) { $date = (Get-Date).AddDays(-7)-f 'MM/d/yyyy' $today = ((Get-Date -Format MM/d/yyyy)) gc $file.FullName | where { $_ -match $date -and $_ -match $today -match 'Successfully' } | select @{n='Pathoffile';e={$file.FullName}} } A: Following Ansgar's idea of the last seven entries all containing the string successfully but using the -Tail parameter of Get-Content. $files = gci .\*.log # C:\Users\Desktop\xx $CkeckSuccess7 = foreach ($file in $files) { if (7 -eq (gc $file.FullName -Tail 7 | where {$_ -match 'Successfully'}).Count){ $Result = $True } else { $Result = $False } [PSCustomObject]@{ Pathoffile=$file.FullName Success7=$Result } } $CkeckSuccess7 Pathoffile Success7 ---------- -------- Q:\Test\2018\12\13\fail.log False Q:\Test\2018\12\13\succes.log True
{ "pile_set_name": "StackExchange" }
Q: How to use momentjs to find number of days between ParseServer object updatedAt How to find the number of days difference between today and Parse Server Object column updatedAt using momentjs. Not sure whats the exact format of updatedAt column. A: If you have a JSON representation of your ParseObject, you can create a moment object from the "iso" property. const obj = yourParseObject.toJSON() const momentDate = moment(obj.updatedAt.iso).fromNow()
{ "pile_set_name": "StackExchange" }
Q: Hibernate message that table is not mapped though it is I have this table in mysql: CREATE TABLE IF NOT EXISTS `realEstate`.`USER` ( `userID` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(45) NULL, `password` VARCHAR(45) NULL, `registrationDate` VARCHAR(15) NULL, `name` VARCHAR(45) NULL, `surname` VARCHAR(45) NULL, `phone` VARCHAR(45) NULL, `email` VARCHAR(45) NULL, `registered` TINYINT(1) NULL, PRIMARY KEY (`userID`), UNIQUE INDEX `user_id_UNIQUE` (`userID` ASC)) ENGINE = InnoDB; and I try to get all its contents with hibernate. Althoug I implemented the .hbm file I get the error that the USER is not mapped[from USER]. Here how I make the question: List<Users> users = null; Session session = null; Transaction transaction = null; try { SessionFactory factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); transaction = session.beginTransaction(); Query query = session.createQuery("from USER"); users = query.list(); transaction.commit(); } catch (HibernateException ex) { System.out.println("Exception:"); System.out.println(ex.getMessage()); if (transaction != null) { transaction.rollback(); } } finally { /*for(Users user:users){ System.out.println(user.getName()); }*/ } System.out.println("Complete"); and here is the users.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Users" table="USER"> <id name="userID" type="int"> <column name="userID" /> <generator class="assigned" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="45"/> </property> <property name="password" type="java.lang.String"> <column name="password" length="45" /> </property> <property name="name" type="java.lang.String"> <column name="name" length="45"/> </property> <property name="date" type="java.lang.String"> <column name="registrationDate" length="45"/> </property> <property name="surname" type="java.lang.String"> <column name="surname" length="45"/> </property> <property name="phone" type="java.lang.String"> <column name="phone" length="45"/> </property> <property name="email" type="java.lang.String"> <column name="email" length="45"/> </property> <property name="registered" type="boolean"> <column name="registered" /> </property> </class> </hibernate-mapping> Eveyrything seems fine to me, but it doesn't work. Can you help me? Here's the class Users: public class Users { private int user_id; private String username; private String password; private String date; private String name; private String surname; private String phone; private String email; private boolean registered; public int getuserID() { return user_id; } public void setuserID(int user_id) { this.user_id = user_id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean getRegistered() { return registered; } public void setRegistered(boolean registered) { this.registered = registered; } } here's the hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="session1"> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/realestate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.timeout">300</property> <property name="hibernate.c3p0.max_statements">50</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <mapping resource="users.hbm.xml"/> <mapping resource="adminstrator.hbm.xml"/> </session-factory> </hibernate-configuration> and here's the directory A: In the HQL , you should use the java class name and property name of the mapped Entity instead of the actual table name and column name , so the HQL should be : Query query = session.createQuery("from USERS"); as provided by you in users.hbm.xml
{ "pile_set_name": "StackExchange" }
Q: Can $x$ be written as a $\mathbb{Q}[x,y]$-algebraic combination of $x+xy$, $y+xy$, $x^2$, and $y^2$? I was wondering how to write $x$ as an algebraic combination of $\{x+xy,y+xy,x^2,y^2\}$, with the coefficients $\in \mathbb Q[x,y]$. A: New problem: Take $(x+xy)-x(y+xy)+y(x^2)$. This simplifies to $x+xy-xy-x^2y+x^2y=x$. Old problem: This is not possible. To see why, examine $x= a(x+xy)+b(y+xy)+cx^2+dy^2$ with $a,b,c,d\in\mathbb{Q}$. We then have that $x= ax+by+(a+b)xy+cx^2+dy^2$. Equating coefficients, we see that $b$ must be 0 and $a$ must be 1. But then the coefficient of $xy$ is 1 on the RHS and 0 on the LHS, which is a contradiction.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET how to create container control which will have exactly two containers? How to create a web control which will contain exactly two containers in ASP.NET 3.5. Like always exactly two columns (divs). I know default way allows you to have ControlCollection by overriding CreateControlCollection() method, but whis allows you to have only one container (or variable number of containers). Is there a way to always have exactly two containers in web control? I want to archive something like this: <MyControl> <LeftContainer> ... </LeftContainer> <RightContainer> ... </RightContainer> </MyControl> A: There is no way to do it in ASP.NET 3.5
{ "pile_set_name": "StackExchange" }
Q: Unable to remove Office 365 Group Site Collection I'm unable to remove site collections that were provisioned alongside an Office 365 group. I tried two approaches. I deleted the O365 group in the O365 Admin Center. The group is gone but the opening the site collection produces a 403 forbidden error Used Remove-PnPUnifiedGroup to remove the O365 group. This was also successful. However, I'm unable to delete the SC getting the same error message. I can't even connect to the site collection in question with Connect-PnPOnline (403 forbidden) Using Remove-SPOSite gives a slightly different error message (Access to this Web site has been blocked). Any ideas how I can remove those leftover site Thanks in advance for your reply. A: The solution for the 403 error was to unlock the site collection. Set-SPOSite -Identity <URL> -LockState unlock After that the site collection could be removed with Remove-SPOSite
{ "pile_set_name": "StackExchange" }
Q: OO design - propagating attributes I'm an experienced C programmer dipping my toes in OO design (specifically C++). I have a particular piece of code I hate and would like to clean up using C++. The code implements a display tree for use in a 3d graphics app. It is a linked list of entries which have a type field specifying whether the entry is a window, geometry feature or light etc. In particular geometry features can either be a single piece of geometry of a collection of sub features, which is indicated by the presence of a separate structure. Being a linked list it is a flat structure but the order implies hierarchy. Also, each entry has an attribute structure which is able to be propagated down the list. A separate function allows this list to be traversed and a provided function pointer to be executed on traversal of the list. Each function used in this way must take proper care to maintain the attribute structure as it is propagated down the list and this is a frequent cause of rendering bugs (usually things not realising they should be redrawn because they are part of a group of entries, for example) While some aspects of OO design jump right out at me I am interested to hear: how i would best implement being able to pass a function pointer down a list (or vector - are STL vectors ok for lists like this?) whether i would be right to implement windows and geometry features as related (or even the same) classes how to best design a class that can have a collection of itself any suggestions regarding attribute transferral between objects (e.g color, scale). the desired behaviour is that modifying a feature will alter the attributes of that feature and any sub-features it contains, and modifying a sub-feature will only modify that feature. I realize this is a long and broad question, so appreciate your thoughts on any of the above queries. thanks! A: 1) Use boost::function and stl algorithms like for_each count_if 2) Divide model from the view. It will be ok. 3) GoF design pattern Composite 4) To implement reaction on changes take a look at GoF design pattern Observer
{ "pile_set_name": "StackExchange" }
Q: ICS calendar feed with Quarterly recurring events I am working on a ICS calendar feed that will be consumed by different calendar apps. I am using PHP iCal package to generate the feed : https://github.com/markuspoerschke/iCal The base system what provides me data for ics feed, has following types of recurring events: Daily, Weekly, Monthly, Quarterly, Yearly I was looking through RFC doc for this standard https://tools.ietf.org/html/rfc5545, and standard support only following repeat frequencies: freq = "SECONDLY" / "MINUTELY" / "HOURLY" / "DAILY" / "WEEKLY" / "MONTHLY" / "YEARLY" that means no standard way to have a quarterly recurring event. One solution that I have in mind is to add a new event after every 3 month. However, this will add 4 separate events in a year, and not 4 recurring instance of original event added. Is there a way to 'trick' ics to create quarterly 'recurring' events? A: If you explore the RFC5545 spec a bit further (next page in the RECUR rule https://tools.ietf.org/html/rfc5545#page-41) , you will find that you can do many things (no 'tricks' needed). For your example: RRULE:FREQ=MONTHLY;INTERVAL=3 as demonstrated here: http://test.icalevents.com/event/quarterly-test/. The INTERVAL rule part contains a positive integer representing at which intervals the recurrence rule repeats. The default value is "1", meaning every second for a SECONDLY rule, every minute for a MINUTELY rule, every hour for an HOURLY rule, every day for a DAILY rule, every week for a WEEKLY rule, every month for a MONTHLY rule, and every year for a YEARLY rule. For example, within a DAILY rule, a value of "8" means every eight days.
{ "pile_set_name": "StackExchange" }
Q: Saving Redis query output to file Using redis-cli I connected to specific server: redis-cli -h 10.1.xx.xx And select 1 Then just to get list of one key features: KEYS data_column* THis will print list of that column values on command line. However, there are like quite many values, I want to save query output to file. In general, using > file_name after the command works. But in this case, it does not work, as its on redis server, though from command line. How to save such query result? A: Simply use: ./redis-cli -h 10.1.xx.xx -n 1 keys 'data_column*' >file.txt A: echo "keys data_column*" | redis-cli -h 10.1.xx.xx -p xx > file.txt A: Following what hjiam2 said above but I cannot comment on their post. I misunderstood what they meant by "keys data_column*" and eventually achieved what I wanted with: echo 'GET key_name' | redis-cli -h localhost -p 6379 > key_value.txt I had a long value in a key that I wanted to view so needed to place it into a file where I can then do whatever I want with it. Using the above command achieved this. Obviously make sure the key_name is what you're looking for and make sure the host and port are correct too.
{ "pile_set_name": "StackExchange" }
Q: Question about "nari" 七三年にはテレビ番組になり、今も毎週続いています。 I understand the sentence to be: In '73 it became a television show, and today it continues every week. My question is about the form of the verb なる in the above sentence – why is it "なり" here? When is the stem form of the verb used in this way? A: 「七三年{ななじゅうさんねん}にはテレビ番組{ばんぐみ}になり、今{いま}も毎週続{まいしゅうつづ}いています。」 As you know, both verbs and adjectives conjugate in Japanese. 「なり」 is the 連用形{れんようけい} ("continuative form") of the verb 「なる」. This sentence talks about two events -- 1) "It became a TV program." + 2) "It has continued to today." 「なる」 is the terminal form; therefore, it cannot be used mid-sentence to connect itself to another verb phrase. Instead, you must use the continuative form 「なり」. Read here and see how 「だ」 becomes 「で」 mid-sentence: How to parse 中国人で日本語が話せる方は、お電話ください。
{ "pile_set_name": "StackExchange" }
Q: vector images in linux Gimp cannot create vector images, is there a good linux application for this? A: Inkscape is today the de facto standard. In earlier times, people used xfig and I still love it, however it isn't for the faint of heart as the user interface is disturbingly ugly and unusual (but highly efficient once you got to know it). Then there is also dia which is modeled a bit after xfig but with a normal Gtk GUI. A: How about Inkscape ?
{ "pile_set_name": "StackExchange" }
Q: Remove shadow on Highstock I'm using Highstock library, and I want to delete from my chart, does anyone know? Thanks. A: That line is the lineWidth of the axis (API). Set it to 0 (which is also the default): yAxis: [{ // ... lineWidth: 0 }] See this JSFiddle example of two y-axis, one with lineWidth set to 0 and one set to 2.
{ "pile_set_name": "StackExchange" }
Q: Create Intersection Type of Multiple Generic Types I've been doing a lot of reading into variadic types and some of the new tuple stuff in TypeScript but am having trouble determining if what I'm trying to accomplish is simply not possible given the language capabilities currently. The exact issue with the API currently can be seen here: export type Themed<T> = { theme: T }; export type ThemedStyleAugmentationFn<P, T> = ( allProps: Partial<P> & Themed<T> ) => string; export function augmentComponent< P, TA extends T, C extends keyof JSX.IntrinsicElements | React.ComponentType<any>, T extends object, O extends object = {}, A extends keyof any = never >( styledComponent: StyledComponent<C, T, O, A>, styleAugmentation: ThemedStyleAugmentationFn<P, TA> ): StyledComponent<C, T, O & Partial<P>, A> { const augmented = styled(styledComponent)` ${styleAugmentation} `; return augmented as StyledComponent<C, T, O & Partial<P>, A>; } export function multiAugment< P1 extends {}, TA1 extends T, P2 extends {}, TA2 extends T, C extends keyof JSX.IntrinsicElements | React.ComponentType<any>, T extends object, O extends object = {}, A extends keyof any = never >( styledComponent: StyledComponent<C, T, O, A>, styleAugmentations: [ThemedStyleAugmentationFn<P1, TA1>, ThemedStyleAugmentationFn<P2, TA2>] ): StyledComponent<C, T, O & Partial<P1 & P2>, A> { const augmented = styled(styledComponent)` ${styleAugmentations} `; return augmented as StyledComponent<C, T, O & Partial<P1 & P2>, A>; } In augmentComponent the important part of the signature is here: O & Partial<P>. In multiAugment which explicitly takes a tuple of two ThemeStyleAugmentationFun it's here: O & Partial<P1 & P2> I would like to be able to write a version of multiAugment that can take an arbitrary list of AugmentationFn and union them all together such that it would support any arity. Something that might return a version of O & Partial<P1 & P2 & P3 ... & P100> for example. I'd like to avoid if possible needing to have a massive number of function overloads in order to support this as I could continue writing Tupled versions of increasing length. A: I can't be sure because I don't have the libraries you're using installed, but perhaps you could do something like this: type PfromSA<SA extends Array<ThemedStyleAugmentationFn<any, any>>> = { [K in keyof SA]: SA[K] extends ThemedStyleAugmentationFn<infer P, any> ? (x: P) => void : never } extends { [k: number]: (x: infer P) => void } ? P : never; type SAExtendsTProperly<SA extends Array<ThemedStyleAugmentationFn<any, any>>, T> = { [K in keyof SA]: SA[K] extends ThemedStyleAugmentationFn<any, infer U> ? [U] extends [T] ? SA[K] : ThemedStyleAugmentationFn<any, T> : never } export function multiAugment< SA extends Array<ThemedStyleAugmentationFn<any, any>>, C extends keyof JSX.IntrinsicElements | React.ComponentType<any>, T extends object, O extends object = {}, A extends keyof any = never >( styledComponent: StyledComponent<C, T, O, A>, ...styleAugmentations: SA & SAExtendsTProperly<SA, T> ): StyledComponent<C, T, O & Partial<PfromSA<SA>>, A> { const augmented = styled(styledComponent)` ${styleAugmentations} `; return augmented as StyledComponent<C, T, O & Partial<PfromSA<SA>>, A>; } The idea is that you use a generic rest parameter for your styleAugmentations parameter (in the above example I made it a rest parameter instead of a tuple; TypeScript will not infer a tuple type from an array literal, but it will infer a tuple type from a rest parameter. If you need an array literal you will need to assert or otherwise coax the compiler into interpreting it as a tuple). This type parameter SA is an array of ThemedStyleAugmentationFn<any, any>. Then the type function PfromSA<SA> uses type inference in conditional types to calculate your desired intersection of P types from SA. And the type function SAExtendsTProperly<SA> does something similar to make sure that each element's ThemedStyleAugmentationFn<P, TA> has TA properly extending T (because ThemedStyleAugmentationFn<P, TA> might be invariant in TA, you can't just make sure SA extends ThemedStyleAugmentationFn<any, T>; you have to walk through the tuple and grab the TA for each element). This should work as you want, but again, I can't be sure without more self-contained code. Hope that helps you. Good luck.
{ "pile_set_name": "StackExchange" }
Q: Add date and time to footnote graph of ggplot I am running a loop all day and during its execution, it saves different graphs. I need to include or add the time in the graph bottom, footnote or even subtitle. I am Working with ggplot. Here is a basic example of how my code is structured: {p <- ggplot(subset(dm, freq>300),aes(word, freq)) } {p} {print(p)} {dev.off()} Thanks in advance. A: Feel free to use ggplot + labs(caption = "footnote"). See example below using mtcars. library(ggplot2) ggplot(mtcars,aes(x=cyl,y=mpg))+ geom_point() + labs(caption = paste(Sys.time()))
{ "pile_set_name": "StackExchange" }
Q: What is the Bash file extension? I have written a bash script in a text editor, what extension do I save my script as so it can run as a bash script? I've created a script that should in theory start an ssh server. I am wondering how to make the script execute once I click on it. I am running OS X 10.9.5. A: Disagreeing with the other answers, there's a common convention to use a .sh extension for shell scripts -- but it's not a useful convention. It's better not to use an extension at all. The advantage of being able tell that foo.sh is a shell script because of its name is minimal, and you pay for it with a loss of flexibility. To make a bash script executable, it needs to have a shebang line at the top: #!/bin/bash and use the chmod +x command so that the system recognizes it as an executable file. It then needs to be installed in one of the directories listed in your $PATH. If the script is called foo, you can then execute it from a shell prompt by typing foo. Or if it's in the current directory (common for temporary scripts), you can type ./foo. Neither the shell nor the operating system pays any attention to the extension part of the file name. It's just part of the name. And by not giving it a special extension, you ensure that anyone (either a user or another script) that uses it doesn't have to care how it was implemented, whether it's a shell script (sh, bash, csh, or whatever), a Perl, Python, or Awk script, or a binary executable. The system is specifically designed so that either an interpreted script or a binary executable can be invoked without knowing or caring how it's implemented. UNIX-like systems started out with a purely textual command-line interface. GUIs like KDE and Gnome were added later. In a GUI desktop system, you can typically run a program (again, whether it's a script or a binary executable) by, for example, double-clicking on an icon that refers to it. Typically this discards any output the program might print and doesn't let you pass command-line arguments; it's much less flexible than running it from a shell prompt. But for some programs (mostly GUI clients) it can be more convenient. Shell scripting is best learned from the command line, not from a GUI. (Some tools do pay attention to file extensions. For example, compilers typically use the extension to determine the language the code is written in: .c for C, .cpp for c++, etc. This convention doesn't apply to executable files.) Keep in mind that UNIX (and UNIX-like systems) are not Windows. MS Windows generally uses a file's extension to determine how to open/execute it. Binary executables need to have a .exe extension. If you have a UNIX-like shell installed under Windows, you can configure Windows to recognize a .sh extension as a shell script, and use the shell to open it; Windows doesn't have the #! convention. A: You don't need any extension (or you could choose an arbitrary one, but .sh is a useful convention). You should start your script with #!/bin/bash (that first line is understood by execve(2) syscall), and you should make your file executable by chmod u+x. so if your script is in some file $HOME/somedir/somescriptname.sh you need to type once chmod u+x $HOME/somedir/somescriptname.sh in a terminal. See chmod(1) for the command and chmod(2) for the syscall. Unless you are typing the whole file path, you should put that file in some directory mentioned in your PATH (see environ(7) & execvp(3)), which you might set permanently in your ~/.bashrc if your login shell is bash) BTW, you could write your script in some other language, e.g. in Python by starting it with #!/usr/bin/python, or in Ocaml by starting it with #!/usr/bin/ocaml... Executing your script by double-clicking (on what? you did not say!) is a desktop environment issue and could be desktop specific (might be different with Kde, Mate, Gnome, .... or IceWM or RatPoison). Perhaps reading EWMH spec might help you getting a better picture. Perhaps making your script executable with chmod might make it clickable on your desktop (apparently, Quartz on MacOSX). But then you probably should make it give some visual feedback. And several computers don't have any desktop, including your own when you access it remotely with ssh. I don't believe it is a good idea to run your shell script by clicking. You probably want to be able to give arguments to your shell script (and how would you do that by clicking?), and you should care about its output. If you are able to write a shell script, you are able to use an interactive shell in a terminal. That it the best and most natural way to use a script. Good interactive shells (e.g. zsh or fish or perhaps a recent bash) have delicious and configurable autocompletion facilities and you won't have to type a lot (learn to use the tab key of your keyboard). Also, scripts and programs are often parts of composite commands (pipelines, etc...). PS. I'm using Unix since 1986, and Linux since 1993. I never started my own programs or scripts by clicking. Why should I?
{ "pile_set_name": "StackExchange" }
Q: Printing the "\" key in Java using System.out.println I am trying to use the \ key in part of my output. Current searches via google are not proving to be successful, perhaps I'm calling it the wrong thing (back slash, escape character, etc.) I cannot find anywhere the code or how to make eclipse understand I want to actually print that character, and that I'm not attempting some sort of escape code. Is there a way to do this? A: You have to double-escape it, since it is the escape character: System.out.println("\\");
{ "pile_set_name": "StackExchange" }
Q: Draw Transparent Scaled PNG I have a large (300x300px) PNG image which I need to rescale. In an other SO question I read about StretchBlt and HALFTONE in order for better scaling. My problem is how do I draw the PNG image transparent, or at least paint the black corners white? As you can see on the attached image I get black corners. And here is the original image: Here is what I've tried so far. unit MainU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TFormMain = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.dfm} uses Pngimage; type TIRButton = class(TImage) protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; end; TGraphicControlAcess = class(TGraphicControl); TGraphicAcess = class(TGraphic); THalfTonePngImage = class(TPngImage) protected procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; end; { TIRButton } constructor TIRButton.Create(AOwner: TComponent); begin inherited; Center := True; Proportional := True; end; procedure TIRButton.Paint; var ParentCanvas: TCanvas; begin ParentCanvas := TGraphicControlAcess(Self).Canvas; TGraphicAcess(Picture.Graphic).Draw(ParentCanvas, DestRect); end; { THalfTonePngImage } procedure THalfTonePngImage.Draw(ACanvas: TCanvas; const Rect: TRect); var p: TPoint; dc: HDC; begin dc := ACanvas.Handle; GetBrushOrgEx(dc, p); SetStretchBltMode(dc, HALFTONE); SetBrushOrgEx(dc, p.X, p.Y, @p); ACanvas.Brush.Color := clWhite; ACanvas.FillRect(Classes.Rect(0, 0, Width, Height)); StretchBlt( dc, 0, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top, Canvas.Handle, 0, 0, Width, Height, ACanvas.CopyMode ); end; procedure TFormMain.FormCreate(Sender: TObject); var Image: THalfTonePngImage; begin Image := THalfTonePngImage.Create; Image.LoadFromFile('X200IR_11_EmgBrake.png'); with TIRButton.Create(Self) do begin Width := 100; Height := 100; Picture.Assign(Image); Parent := Self; Anchors := [akLeft, akTop, akRight, akBottom]; end; Image.Free; end; end. A: The corners of the source image are transparent. It's not visible in the correct image because the white background. StretchBlt doesn't support transparency. Since it doesn't, transparent pixels are indistinguishable from black. (If the ARGB color is FF 00 00 00 and we remove the alpha channel, we're left with 00 00 00) You need to use TransparentBlt. For reference this is the image when placed on a green background. It makes it easier to see the transparency.
{ "pile_set_name": "StackExchange" }
Q: how we find the nearest person in 100 meter area when using same app we design an android app in this app I want to get information of near by person using same app how can we do it ? I need to find closest person who using the same app in 100 meter range then how can I find him??? A: In android 4>0 you can use DirectWifi Take a look at this link too http://developer.android.com/training/connect-devices-wirelessly/ If the devices are too close (in a 10 meter range) , you can use bluetooth communication.
{ "pile_set_name": "StackExchange" }
Q: Draw centered text using core graphics (mobile device) I'm using this code: CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; NSString * text = @"text"; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:1 blue:1 alpha:RETICLE_ALPHA].CGColor); [text drawAtPoint:CGPointMake(screenWidth/2, screenHeight/2) withFont: [UIFont systemFontOfSize:22.0]]; to create a centered "text" for iOS. But I'm not sure how to edit the code above to really get the center alignment working, because till now the text is not really centered at all. Sorry, for the kind of stupid question but I didn't found an working example for the problem & I'm new in using Core Graphics. A: Your text is not centered because you have to subtract the text width from the screen size and then you have to divide by 2. Below I have tried to correct your code. CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; NSString * text = @"text"; CGFloat minHeight = 40; float widthIs = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, minHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:22.0] } context:nil].size.width; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:1 blue:1 alpha:1].CGColor); [text drawAtPoint:CGPointMake((screenWidth - widthIs)/2, (screenHeight - minHeight)/2) withFont: [UIFont systemFontOfSize:22.0]];
{ "pile_set_name": "StackExchange" }
Q: I need help with sql and data relation tables i building a mini forum site.. and i constructed a few tables. 1) Users 2) Threads 3) Comments 4) Topics i build a function that would insert a comment each time a user would submit a comment: string saveComment = "INSERT INTO Comments("; saveComment += " UsersID, ThreadsID, Date, Comments, CommentResponse"; saveComment += "Values('" + "','";// no idea what to insert in the UsersID saveComment += "" + "','";// no idea what to insert in the ThreadsID saveComment += DateTime.Now + "','"; saveComment += CommenttxtBox.Text + "','"; saveComment += commentResponseString + "')"; As you can see the fields have UsersID and ThreadID, both connected by a foreign key to the comments table. Now, each time the user submits a comment, i guess i need to insert also to the UsersID field (which is an int in the comments table, and that field increases incrementally by 1 in the Users table). How can i insert a comment, and notify the other table not to increase the UserID by 1. in fact i want it the UserID to stay the same for each user submitting a comment.. How do i do that? i need to insert to a few fields in one table (comments) but keep the other tables informed that it is actually the same user who submitted the comment . Note: i dont know any vb, only c#, and i use visual studio 2010. asp.net A: You are creating a very standard normalised structure. Your Users table will be responsible for controlling the UserID values that are generated. You have two situations to cope with when inserting new comments: The User exists and is logged in. The User does not exist and is anonymous. In the first situation, when you are inserting the comments you will not need to bother looking at the Users table. This assumes you have the UserID already loaded (as the user is logged in). In the second situation, you will first need to a new row to the Users table and return the UserID that the table generates (assuming you are using an identity column). You can then pass this value to the Comments table. The following script is an example of addressing the second situation: DECLARE @userId int INSERT INTO Users (Username, FirstName) VALUES ('adamh', 'Adam') SET @userId = SCOPE_IDENTITY() INSERT INTO Comments(UserId, ThreadId, Comment) VALUES (@userId, 1, 'My comment') If you want to continue with your current coding style, simply concatenate the values into the relevant parts of the string. However, with such as neatly defined structure as the one you have, I'd advise using something like Entity Framework 4.0, or LINQ to SQL, which cuts a lot of plumbing out once you have defined your structures.
{ "pile_set_name": "StackExchange" }
Q: @dbcolumn in session.evaluate in xpages I am trying to execute this code for a listbox but its not working, this gives me the error 500. If i directly write the @formula in listbox it works fine. return session.evaluate("@DbColumn(@DbName(), \"viewName\", 1)").elementAt(0) but if i write below code it works fine. return session.evaluate("@Unique").elementAt(0); I am working in xpages on Lotus Notes 8.5.3 A: You receive a 500er Error because the @DbColumn for SSJS has a parameter less than the "original" @DbColumn-Version which will be executed if you are using the evaluate method. For XPages, the option for caching and class got lost. This is the syntax for the evaluate statement: @DbColumn( class : cache ; server : database ; view ; columnNumber ) This is the XPages syntax: @DbColumn( server : database , view , columnNumber ); And you have to use the native Notes @Formula syntax, f.e. use semicolons instead commas.
{ "pile_set_name": "StackExchange" }
Q: L5.2 PHP Fatal error: Declaration of Illuminate\Auth\SessionGuard::basic I just pushed my L5.2 app to production server. I have made a few changes, but suddenly I get the following error: PHP Fatal error: Declaration of Illuminate\Auth\SessionGuard::basic($field = 'email') must be compatible with Illuminate\Contracts\Auth\SupportsBasicAuth::basic($field = 'email', $extraConditions = Array) in /home/forge/domain.com/bootstrap/cache/compiled.php on line 461 The app works fine locally and on the staging server. A: just remove the bootstrap/cache/compiled.php file rm bootstrap/cache/compiled.php then run composer dump-autoload and php artisan clear-compiled it should work
{ "pile_set_name": "StackExchange" }
Q: message digest hash MD5 I am trying to get MD5 hash for the string "password". When I am using MD5PasswordEncoder class from Spring framework I am getting this: 5f4dcc3b5aa765d61d8327deb882cf99 But when I am using Java's MessageDigest class with MD5 I am getting this: 9577-525990-89101-4229-12539-34-72-126-49-103 First one is Hex and other one is Decimal. Why is there a difference? Here is the code: public static void main(String[] args) { PasswordEncoder pEncoder = new Md5PasswordEncoder(); System.out.println(pEncoder.encodePassword("password", null)); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("password".getBytes("UTF-8")); byte [] digest = md.digest(); StringBuffer sb = new StringBuffer(); for (byte b : digest) { sb.append(b); } System.out.println(sb.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } A: The issue is your print function. The following code prints the same value as your Spring application: public static void main(String[] args) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("password".getBytes("UTF-8")); byte[] digest = md.digest(); System.out.println(DatatypeConverter.printHexBinary(digest)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Prints: 5F4DCC3B5AA765D61D8327DEB882CF99
{ "pile_set_name": "StackExchange" }
Q: Redirect on success and show error on failure I have implemented a controller to create new users. When it creates the user successfully it redirects to Index(). What I want is to get redirected when all is OK, but stay in the current page and see the error when something failed. I'm using jQuery ajax with MVC. My controller looks like this: [Authorize] public ActionResult CreateUser(string username) { try { //here the logic to create the user } catch (Exception ex) { string error = string.Format("Error creating user: {0}", ex.Message); Response.StatusCode = 500; Response.Write(error); } return RedirectToAction("Index"); } The form submit is intercepted with jQuery, and then the call is made with ajax: $("#new-user-form").submit(function() { var form = $(this); $.ajax({ type: "GET", url: form.attr('action'), data: form.serialize(), success: function(data, textStatus, xhr) { //At this point I would like to redirect }, error: function(xhr, textStatus, errorThrown) { $(".error-summary").html(xhr.responseText); } }); //cancel the event return false; }); It works fine when an error occurs, but I don't know how to implement the success case. I'm opened to other alternatives. A: If you are going to redirect in the success action why are you using AJAX? The purpose of AJAX is to refresh only parts of a site without reloading the whole page. If in the success action you are going to redirect that totally defeats all the purpose and benefits you get from AJAX. But because you asked here's what you could do: [Authorize] public ActionResult CreateUser(string username) { ... if (Request.IsAjaxRequest()) { return Json(new { redirectToUrl = Url.Action("Index") }); } return RedirectToAction("Index"); } And then: success: function(data, textStatus, xhr) { window.location.href = data.redirectToUrl; }, A: If you are going to redirect in the success action why are you using AJAX? The purpose of AJAX is to refresh only parts of a site without reloading the whole page. If in that any error or session expire you are going to redirect default login page.For that you have to override AuthorizeAttribute Filter so make class belew: public class CheckAuthorization : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (HttpContext.Current.Session["AFSUserId"] == null || !HttpContext.Current.Request.IsAuthenticated) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 302; //Found Redirection to another page. Here- login page. Check Layout ajaxError() script. filterContext.HttpContext.Response.End(); } else { filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?ReturnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl)); } } } After Making that CheckAuthorization Class you have just put whenever you call ajax Authorization like below: [CheckAuthorization] public class BuyerController : Controller { [HttpGet()] public ActionResult GetOrderlist() { return View(); } } now you have to handle ajax status 302 in view side on each Ajax call so put line of code in your layout page order by leadid desc any particular page so like below: $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) { if (jqXHR.status == 302) { window.location.href = '@Url.Action("Login", "Home")'; } }); Here you are redirect to login page if current session expire or Timeout.
{ "pile_set_name": "StackExchange" }
Q: Does MySQL not use LIMIT to optimize query select functions? I've got a complex query I have to run in an application that is giving me some performance trouble. I've simplified it here. The database is MySQL 5.6.35 on CentOS. SELECT a.`po_num`, Count(*) AS item_count, Sum(b.`quantity`) AS total_quantity, Group_concat(`web_sku` SEPARATOR ' ') AS web_skus FROM `order` a INNER JOIN `order_item` b ON a.`order_id` = b.`order_key` WHERE `store` LIKE '%foobar%' LIMIT 200 offset 0; The key part of this query is where I've placed "foobar" as a placeholder. If this value is something like big_store, the query takes much longer (roughly 0.4 seconds in the query provided here, much longer in the query I'm actually using) than if the value is small_store (roughly 0.1 seconds in the query provided). big_store would return significantly more results if there were not limit. But there is a limit and that's what surprises me. Both datasets have more than the LIMIT, which is only 200. It appears to me that MySQL performing the select functions COUNT, SUM, GROUP_CONCAT for all big_store/small_store rows and then applies the LIMIT retroactively. I would imagine that it'd be best to stop when you get to 200. Could it not do the select functions COUNT, SUM, GROUP_CONCAT actions after grabbing the 200 rows it will use, making my query much much quicker? This seems feasible to me except in cases where there's an ORDER BY on one of those rows. Does MySQL not use LIMIT to optimize a query select functions? If not, is there a good reason for that? If so, did I make a mistake in my thinking above? A: It can stop short due to the LIMIT, but that is not a reasonable query since there is no ORDER BY. Without ORDER BY, it will pick whatever 200 rows it feels like and stop short. With an ORDER BY, it will have to scan the entire table that contains store (please qualify columns with which table they come from!). This is because of the leading wildcard. Only then can it trim to 200 rows. Another problem -- Without a GROUP BY, aggregates (SUM, etc) are performed across the entire table (or at least those that remain after filtering). The LIMIT does not apply until after that. Perhaps what you are asking about is MariaDB 5.5.21's "LIMIT_ROWS_EXAMINED". Think of it this way ... All of the components of a SELECT are done in the order specified by the syntax. Since LIMIT is last, it does not apply until after the other stuff is performed. (There are a couple of exceptions: (1) SELECT col... must be done after FROM ..., since it would not know which table(s); (2) The optimizer readily reorders JOINed table and clauses in WHERE ... AND ....) More details on that query. The optimizer peeks ahead, and sees that the WHERE is filtering on order (that is where store is, yes?), so it decides to start with the table order. It fetches all rows from order that match %foobar%. For each such row, find the row(s) in order_item. Now it has some number of rows (possibly more than 200) with which to do the aggregates. Perform the aggregates - COUNT, SUM, GROUP_CONCAT. (Actually this will probably be done as it gathers the rows -- another optimization.) There is now 1 row (with an unpredictable value for a.po_num). Skip 0 rows for the OFFSET part of the LIMIT. (OK, another out-of-order thingie.) Deliver up to 200 rows. (There is only 1.) Add ORDER BY (but no GROUP BY) -- big deal, sort the 1 row. Add GROUP BY (but no ORDER BY) in, now you may have more than 200 rows coming out, and it can stop short. Add GROUP BY and ORDER BY and they are identical, then it may have to do a sort for the grouping, but not for the ordering, and it may stop at 200. Add GROUP BY and ORDER BY and they are not identical, then it may have to do a sort for the grouping, and will have to re-sort for the ordering, and cannot stop at 200 until after the ORDER BY. That is, virtually all the work is performed on all the data. Oh, and all of this gets worse if you don't have the optimal index. Oh, did I fail to insist on providing SHOW CREATE TABLE? I apologize for my tone. I have thrown quite a few tips in your direction; please learn from them.
{ "pile_set_name": "StackExchange" }
Q: model.save() not called when loading Django fixtures? I am overriding my Django model save() method, so I can do some extra sanity checking on the object. (Is save() the correct place to do this?) It doesn't appear that my fixtures/initial_fixtures.yaml objects have their save() method called. How can I sanity-check my fixtures? A: As of Django 1.5, save() is NOT called: When fixture files are processed, the data is saved to the database as is. Model defined save() methods are not called, and any pre_save or post_save signals will be called with raw=True since the instance only contains attributes that are local to the model. https://docs.djangoproject.com/en/1.9/ref/django-admin/
{ "pile_set_name": "StackExchange" }
Q: INSERT OVER statement? What the difference between INSERT INTO table VALUES (values) and INSERT OVER table VALUES (values) ? A: Of all reserved keywords, only INTO and OVER work. SQL:2003 mentions OVERRIDING keyword to override the identity (currently only supported by DB2) Probably, SQL Server parses it for now but does not actually implement. The plans generated are identical, and ParameterizedText is expanded into INSERT INTO. So as for 2008R2, the answer would be this: No difference, except that INSERT OVER has already wasted about 50 manhours of most curious developers to the moment and there is more to go A: People at Microsoft say: Thanks for reporting this issue. We keep recognizing the OVER keyword along with the INTO keyword (with the same meaning) in INSERT statements to provide backward compatibility with the previous versions of SQL Server. This should not present any problem for application development. Eugene Zabokritski, SQL Engine
{ "pile_set_name": "StackExchange" }
Q: Getting compile exception inside ActionFilter when accessing Request Object I have this little bit of code: using System; using System.Web.Mvc; public class SecureFilter : RequireHttpsAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (null == filterContext) { throw new ArgumentNullException("filterContext"); } if (null != filterContext.HttpContext && filterContext.HttpContext.Request.IsLocal) { return; } base.OnAuthorization(filterContext); } } Where I am trying to determine if the request is local or not is where I am getting the compile time exception. It gives me this error: 'System.Web.HttpContextBase' does not contain a definition for 'Request' and no extension method 'Request' accepting a first argument of type 'System.Web.HttpContextBase' could be found (are you missing a using directive or an assembly reference?) From what I understand the Request object actually belongs to the controller, but I am not quite sure how I am supposed to create this action filter if I am not able to gain access to the object. Any guidance here would be greatly appreciated! A: This was something quirky with the project it seems. I followed Nick Riggs advice and tried a test solution and it worked just fine. So I deleted the project from my current solution and created a new one and just copied the files into it. This got it working.
{ "pile_set_name": "StackExchange" }
Q: Unable to connect to data source using 'sa' user name Trying to debug an issue with a data source, I am currently getting this error: The error is occurring in my DataSet2, on this particular Dataset: Looking at the logs, I see this: Microsoft.ReportingServices.ReportProcessing.DataSetExecutionException: The execution failed for the shared data set 'DataSet2'. Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Query execution failed for dataset ''. System.Data.SqlClient.SqlException: Invalid object name 'facilities'.` My next step to figure this out is to open this DataSet and confirm the query. When I try to Edit in Report Builder and it prompts me for my credentials. In this case, I am trying to use the sa user, but it is telling me that my credentials are invalid. I've confirmed on the actual SQL Server that the credentials are correct. Any suggestions would be greatly appreciated. A: It doesn't look related to the username SA. The error suggests that the Dataset2 does not have the facilities table.
{ "pile_set_name": "StackExchange" }
Q: How to correctly configure symfony2 swiftmailer bundle to work with SMTP server with NTLM AUTH? # Swiftmailer Configuration swiftmailer: transport: smtp host: 10.8.100.1 port: 25 username: user password: pass auth_mode: ~ encryption: ~ spool: { type: memory } When I try to send a message via $this->get('mailer')->send($message); I am getting the following error: Fatal error: Uncaught exception 'Swift_TransportException' with message 'Failed to authenticate on SMTP server with username "user" using 0 possible authenticators' in /..path../vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php:184 Stack trace: #0 I've tried changeing the auth_mode setting to all possible values plain, login, cram-md5, or null - still the same error message. Then I wanted to telnet to SMTP server to manually check if i can auth (though, I am 100% sure the credentials are correct). telnet 10.8.100.1 25 Trying 10.8.100.1... Connected to 10.8.100.1. Escape character is '^]'. 220 EXC.acme.local Microsoft ESMTP MAIL Service ready at Wed, 19 Mar 2014 10:34:00 +0100 EHLO EXC.acme.local 250-EXC.acme.local Hello [10.8.100.1] 250-SIZE 250-PIPELINING 250-DSN 250-ENHANCEDSTATUSCODES 250-STARTTLS 250-X-ANONYMOUSTLS 250-AUTH NTLM 250-X-EXPS GSSAPI NTLM 250-8BITMIME 250-BINARYMIME 250-CHUNKING 250-XEXCH50 250 XRDST I'm no mail server expert, but I was expecting AUTH LOGIN there... seems like the server (over which I have no control) has a diffrent authentication method (which is not suppoerted by Swiftmailer bundle?) and that might be the cause of the problem... Are my suspictions correct? Or is there a way to configure Swiftmailer bundle to correctly auth with AUTH NTLM? A: So.. the problem wasn't with the symfony2 configuration. The problem was: the mailbox was configured to work inside VPN (from computers in the domain/group) I was trying to send a test mail from my development machine (while being connected to VPN... but my computer is not in the domain/group) This is also the reason why telnet EXC.acme.local 25 didn't work, but telnet 10.8.100.1 25 did work. So, when I tried to telnet, and then EHLO from my dev machine.. is got 250-AUTH NTLM, but when I SSH'ed to the prod machine (which is inside the domain/group) and telnet from there: telnet EXC.acme.local 25 did work EHLO EXC.acme.local returned AUTH LOGIN Once I discovered that, I just uploaded my changes to prod machine and started testing the config from there (with swiftmailer.transport: smtp) and it worked!
{ "pile_set_name": "StackExchange" }
Q: HTTPS urllib.request,read into JSON If I go for example from urlib2 import urllib.request response = urllib.request.urlopen('http://python.org/') html = response.read() then it works fine. I was suprised to see that my code req = urllib.request.Request('https://www.tehnomanija.rs/it-shop/laptop-racunari') response = urllib.request.urlopen(req) the_page = response.read() data = json.loads(the_page) print (data) produces error like this data = json.loads(the_page) File "/home/mm/anaconda3/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/home/mm/anaconda3/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/mm/anaconda3/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Except the other protocol I do not see why this would not work. A: json.load() is for loading from file. You need json.loads(): data = json.loads(the_page)
{ "pile_set_name": "StackExchange" }
Q: Can I disable journalling to improve performance We have a 16 shard MongoDB 2.4 installation running in AWS that is eating money. The data is volatile, it only gets used within 15 minutes of creation If the cluster goes down we wipe it out and restart ~ 30 seconds downtime I note that the majority of disk stress appears to be journalling Is there any reason I cannot disable journalling? A: It should be noted that on any MongoDB system with significant write volume, most of the continuous/ongoing disk usage will come from the journal - after all it syncs to disk every 100ms - so this observation is not unusual. If you truly can wipe out 16 shards and restore in 30 seconds (which is impressive), then you can eliminate the journal with minimal risk, yes, but you could also be less drastic. But, before you do, consider that getting rid of the journal means that a non-clean restart of a mongod leaves your data in an unknown state (it might be OK, it might not). You will want to be sure you have ways to detect any discrepancies (that might not present as an outage) if you run in this mode. It's also worth noting that this would essentially be an unsupported mode of operation for production, so getting any help with a problem will likely mean having to turn journaling back on. Finally, before you turn off the journal, consider these somewhat less drastic steps first: Move the journal to its own disk/volume - it's a standard write ahead journal meaning sequential writes - very different to the usual data writes, and so having it on its own disk/volume can be significantly more efficient, especially if your other IO is more randomly distributed (common with MongoDB). Finally, as of writing this, you should never have the journal on an NFS mount - it does not play well (may not apply here, but good advice in general). Change the commit interval of the journal - the default is 100ms, but you can increase to 300ms (see the docs here) - this is a minor tweak but may help Although it is not directly related to journaling, the other competing writes will come from the fsync process for data (every 60 seconds by default). If you alter this you may improve that performance also and remove stress from the disk also. Again, see the docs on syncdelay for details. Take a look at how you are writing data - sometimes large array updates, large or un-needed indexes etc. can translate into more writes than they should.
{ "pile_set_name": "StackExchange" }
Q: why Data.Set has no powerset function? I was looking at Data.Set, and I found out that it has no powerset function. Why? I can implement it like this: import Data.Set (Set, empty, fromList, toList, insert) powerset :: (Ord a) => Set a -> Set (Set a) powerset s = fromList $ map (fromList) (powerList $ toList s) powerList :: [a] -> [[a]] powerList [] = [[]] powerList (x:xs) = powerList xs ++ map (x:) (powerList xs) But this doesn't seem the most efficient way of doing it. OK, I can also write powerList :: [a] -> [[a]] powerList = filterM (const [True, False]) but still, I wonder why Data.Set has no powerset function. Also, what is the best way to write powerset :: (Ord a) => Set a -> Set (Set a)? A: Funny, I actually implemented powerset in Haskell the other day just for fun in a comment at /r/python. import Data.Set import Prelude hiding (map) powerset s | s == empty = singleton empty | otherwise = map (insert x) pxs `union` pxs where (x, xs) = deleteFindMin s pxs = powerset xs It is much as camccann described in his comment above. Set's fast union should give it a speed boost over the list version.
{ "pile_set_name": "StackExchange" }
Q: Disable all target="_blank" links on page I'm building content for a site that is displayed through an iframe in a PhoneGap mobile app. The content is pulled from a CMS that also serves the content for the main website so it has a mix of internal and target="_blank" links. Handling target="_blank" links is proving problematic in PhoneGap so I want to disable them in the app website without touching the content because it's also used on the main website. What I need is jQuery that runs on page load, finds all links with target="_blank" attribute and makes links normal text. Something like this (How to disable all links before load jQuery?) disables all links but I only want to disable links that have target="_blank" attribute, and I want to hide the fact that the words were links in the first place: var links = document.links; for (var i = 0, length = links.length; i < length; i++) { links[i].onclick = function(e) { e = e || window.event; e.preventDefault(); } } So I don't want to simply preventDefault() on link click but remove the links completely while keeping the link text, and I want to apply this to target="_blank" links only. A: $('a[target="_blank"]').each(function(){ $(this).removeAttr('href'); }); Or if you want to completely remove a tags $('a[target="_blank"]').each(function(){ $(this).replaceWith($(this).text()); }); http://jsfiddle.net/mohammadAdil/kZqFD/
{ "pile_set_name": "StackExchange" }
Q: Json empty array json_decode I have the following code that converts json into an array: $str = file_get_contents('http://localhost/data.json'); $decodedstr = html_entity_decode($str); $jarray = json_decode($decodedstr, true); echo "<pre>"; print_r($jarray); echo "</pre>"; but my $jarray keeps returning null... I dont know why this is happening.. i have already validated my json in this question: validated json question could anyone tell me what i am doing wrong? or what is happening. Thanks in advance. when i echo my $str i get the following: A: You are passing to json_decode a string that is not valid JSON, this is the reason NULL is returned. As I see from comments inspecting the error code generated gives 4 that corresponds to the constant JSON_ERROR_SYNTAX that just means the JSON string has a Syntax Error. (See http://php.net/manual/en/function.json-last-error.php) You should inspect (echo) what you get from $str = file_get_contents('http://localhost/data.json'); (You may edit your answer and post it - or a portion of it) For sure it is not valid JSON; the problem lies there: in data.json. Then as you fix things and get from data.json what is expected I would ensure you really need to use html_entity_decode on the fetched data. It would be "weird" to have html encoded JSON data. UPDATE Looking at what you get from data.json it seem the JSON data contains actually HTML entities (as I see the presence of &nbsp;s) This is actually weird, the right thing to do would be to fix how data.json is generated ensuring non-html-encoded JSON data is returned, charset is UTF-8 and the response content type is Content-Type: application/json. We can't deepen this here as I don't know where does data.json come from or the code that generates it. Eventually you may post another answer. So here is a quick fix provided that the right approach would be what I just suggested above. As you decode html entities, non breaking spaces &nbsp; turns into 2 byte UTF-8 characters (byte values 196, 160) that are not valid for JSON encoded data. The idea is to remove these characters; your code becomes: $str = file_get_contents('http://localhost/data.json'); $decodedstr = html_entity_decode($str); // the character sequence for decoded HTML &nbsp; $nbsp = html_entity_decode( "&nbsp;" ); // remove every occurrence of the character sequence $decodedstr = str_replace( $nbsp, "", $decodedstr ); $jarray = json_decode($decodedstr, true);
{ "pile_set_name": "StackExchange" }
Q: Processing Login with Sentry 2 I'm having trouble understanding Sentry 2 implementation for login. I mean in Sentry it was pretty strait forward. Provide username/email and password from Input to Sentry::login() method however they changed it now and it's really confusing. First of all they removed Username column which makes no sense. Second the login method now takes a User object that you need to retrieve using user's id which again makes no sense as you don't know the users id unless you make another query so they really complicated everything. My code: public function login() { // Deny access to already logged-in user if(!Sentry::check()) { $rules = array( 'username' => 'required|unique:users', 'password' => 'required' ); $validator = Validator::make(Input::all(), $rules); if($validator->fails()) { Session::flash('error', $validator->errors()); return Redirect::to('/'); } $fetch = User::where('username', '=', trim(Input::get('username'))); $user = Sentry::getUserProvider()->findById($fetch->id); if(!Sentry::login($user, false)) { Session::flash('error', 'Wrong Username or Password !'); } return Redirect::to('/'); } return Redirect::to('/'); } I tried using this approach but it throws an exception: that id is unknown despite id being part of the table and User model being nothing but a class declaration with a $table = 'users'; attribute. What am I doing wrong here or not understanding. A: Code below is my login method using Sentry 2. I'm basically letting Sentry do everything for me validation, find the user and, of course, login the user. Messages are in portuguese, but if you need me to translate just tell. public function login() { try { $credentials = array( 'email' => Input::has('email') ? Input::get('email') : null, 'password' => Input::has('password') ? Input::get('password') : null, ); // Log the user in $user = Sentry::authenticate($credentials, Input::has('remember_me') and Input::get('remember_me') == 'checked'); return View::make('site.common.message') ->with('title','Seja bem-vindo!') ->with('message','Você efetuou login com sucesso em nossa loja.'); } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { return View::make('site.common.message') ->with('title','Erro') ->with('message','O campo do e-mail é necessário.'); } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) { return View::make('site.common.message') ->with('title','Erro') ->with('message','O campo do senha é necessário.'); } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { $user = Sentry::getUserProvider()->findByLogin(Input::get('email')); Email::queue($user, 'site.users.emailActivation', 'Ativação da sua conta na Vevey'); return View::make('site.common.message') ->with('title','Usuário não ativado') ->with('message',"O seu usuário ainda não foi ativado na nossa loja. Um novo e-mail de ativação foi enviado para $user->email, por favor verifique a sua caixa postal e clique no link que enviamos na mensagem. Verifique também se os nossos e-mails não estão indo direto para a sua caixa de SPAM."); } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) { return View::make('site.common.message') ->with('title','Erro') ->with('message','A senha fornecida para este e-mail é inválida.'); } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { return View::make('site.common.message') ->with('title','Erro') ->with('message','Não existe usuário cadastrado com este e-mail em nossa loja.'); } // Following is only needed if throttle is enabled catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) { $time = $throttle->getSuspensionTime(); return View::make('site.common.message') ->with('title','Erro') ->with('message',"Este usário está suspenso por [$time] minutes. Aguarde e tente novamente mais tarde."); } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) { return View::make('site.common.message') ->with('title','Erro') ->with('message',"Este usário está banido do nossa loja."); } }
{ "pile_set_name": "StackExchange" }
Q: ZPOOL Mirror setup What is the best setup for an zpool intended for database big inserts or TCP/IP dumps (i mean sustained high write throughput using 4 disks ? I want buy 4 Wd RE4 2TB drives and get the more power i can ! i think of zpool create tank mirror disk1 disk2 disk3 disk4 OR zpool create tank mirror disk1 disk2 mirror disk3 disk4 OR zpool create tank disk1 disk2 disk3 disk4 i think the solution with two mirror in a pool is the best, but not sure. edit : ok so mirror IS RAID1. It is not possible to make this setup : RAID0 (RAID0, RAID0) A: The three commands and ZFS setups you've listed are vastly different configurations. zpool create tank mirror disk1 disk2 disk3 disk4 This creates a 4-way mirror with the capacity of ONE disk. Lots of protection, less space and less performance. I don't think you want that. zpool create tank mirror disk1 disk2 mirror disk3 disk4 This creates a stripe of two RAID 1 mirrors - RAID 1+0, with a capacity of TWO disks. This is a good balance. zpool create tank disk1 disk2 disk3 disk4 This creates a stripe of four disks - RAID 0, no protection against failure and a capacity of FOUR disks. This is fast, but only make sense if you don't care about your data's integrity. If a drive fails, you will lose all of your data
{ "pile_set_name": "StackExchange" }
Q: Custom TableViewCell with Core Data I have a Destination View Controller that allows you to edit information displayed in the TableViewController..I am attempting to set this up in a custom cell..I have my UITableViewCell file with the custom property class and I also have my Model Class for the Core Data with the attributes. I managed to get my root table view controller to show the custom label when I add a NEW player but once I click on the cell and edit it in the new view controller it goes back to the default on the table view. I believe it has something to do with this code but I can not figure it out. my NsManagedObject Subclass @property (nonatomic, retain) NSString *playerFirstName; I have a pointer to my Player Class of currentPlayer in my viewcontroller.h file and the firstnameTextfield is my UITextField -(IBAction)doneEditing:(id)sender { _currentPlayer.playerFirstName = firstnameTextField.text; AppDelegate *myApp = (AppDelegate *) [[UIApplication sharedApplication]delegate]' [myApp saveContext]; } Update I believe this is my line of code that is the problem after messing with it _currentPlayer.playerFirstName = firstnameTextField.text; how do I get the currentPlayer pointer to go to my playerNameCell property in my customcell class A: You should do something like: - (IBAction)newPlayer { _currentPlayer = (Player*) [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:_managedObjectContext]; } The _managedObjectContext should be passed to the view controller from the app delegate or some other view controller.
{ "pile_set_name": "StackExchange" }
Q: Is it a good way to realize a MVVM app in WPF? I am rather new to WPF. I'm trying to realize a chat app using Jabber.NET and I would like to follow a correct MVVM architecture. I have the following Models: BuddyListModel ChatSessionModel ChatMessageModel The following ViewModels: BuddyListViewModel ChatSessionsViewModel ChatMessagesViewModel Each of the VM contains ObservableCollection<> of corresponding Models. I instanciate Jabber in BuddyListViewModel (where I've put login handling) and all the Event handlers (presence, new message) are in that VM; the problem is that, doing in this way, I must call other VMs methods (AddNewChatSession when a new message arrives,....) from the BuddyListViewModel and I don't know if this is the right approach for MVVM. Another problem is that I'm handling ALL the messages in a single ViewModel and think to use filters (in linq, for example) to show the messages in the corresponding ChatSession. Is it a good thing? A: I'd create an ApplicationViewModel that holds the instance of of your main model (which may be the Jabber object), and pass the instance the other VMs it instantiates so that they can register to handle events that model raises. (I'm assuming, based on your description, that when Jabber receives a message it raises an event and passes the message in the EventArgs.) If you do this, then when a new message arrives, your ChatSessionsViewModel can check it to see if it's in a new session, and create a new ChatSessionViewModel if it is. Your ChatSessionViewModel can check the message to see if it belongs to the session, and add it to its collection of messages if it does. These two operations are completely independent of one another. I wouldn't put all the chat messages in a single collection and then have the session view models filter them - filtering items in a collection is an O(n) operation, and if you're building a chat client, n is going to get very big. It's much more logical to have the chat session examine the message as it comes in and capture it if it belongs to the session. But it really depends on the application. If you approach it this way, there's the possibility that a message will come in that nothing's handling, and it'll get discarded. Is that OK?
{ "pile_set_name": "StackExchange" }
Q: Do Hindus believe in Adam and Eve? If not, who is the first person (man or woman) in this world? Does any Hindu scripture mention anything about Adam and Eve? According to Hinduism, who is the first person (man or woman) in this world? A: No, Hindu scripture doesn't talks about Adam and Eve... However some people compare the story of Bhavisya Purana containing name Adam and Havyavati as Adam and Eve and their story sounds pretty much similar. But we can't be sure about stories of Bhavisya Purana because it is supposed that it suffered high interpolation. Even if we consider story of Bhavisya purana as genuine then still Adam and Eve[Havyavati] aren't progenitor of mankind.. They are just progenitor of mlechha dharma [Foreigner religion]. Still if you are interested in that story of Bhavisya Purana, the story goes like this: At that time the Kali purusha prayed to Lord Narayana along with his wife. After sometime the Lord apperared to him and said, "This age will be a good time for you. I will fulfil your desire having various kinds of forms. There is a couple named Adama and his wife Havyavati. They are born from Vishnu-kardama and will increase the generations of mlecchas. Saying this, the Lord disappeared. Having great joy the Kali purusha went to Nilacha Vyasa said: "Now you hear the future story narrated by Suta Goswami. This is the full story of of Kali-yuga, hearing this you will become satisfied." In the eastern side of Pradan city where there is a a big God-given forest, which is 16 square yojanas in size. The man named Adama was staying there under a Papa-Vriksha or a sinful tree and was eager to see his wife Havyavati. The Kali purusha quickly came there assuming the form of a serpent. He cheated them and they disobeyed Lord Vishnu. The husband ate the forbidden fruit of the sinful tree. They lived by eating air with the leaves called udumbara. After they had sons and all of them became mlecchas. Adama's duration of life was nine-hundred and thirty years. He offered oblations with fruits and went to heaven with his wife. His son was named Sveta-nama, and he lived nine-hundred and twelve years. Sveta-nama's son was Anuta, who ruled one-hundred years less than his father. His son Kinasa ruled as much as his grandfather. His son Malahalla ruled eight-hundred ninety five years. His son Virada ruled 160 years. His son Hamuka was devoted to Lord Vishnu, and offering oblations of fruits he achieved salvation. He ruled 365 years and went to heaven with the same body being engaged in mleccha-dharma. For more read here Coming to your second question: Who is the first man and women in the world? Practically it is impossible to find the first man and women in this world. You have to understand Hindu cosmology to understand this. _______________________________________ Literally Manu are the progenitors of Mankind hence humans are called Manushya. For eg. Present Manu is Vaivasvata Manu , son of sun God. But he is not the 1st Man of the world. He is the 7th Manu of this Kalpa [Shewta Varaha Kalpa]. 1st Manu of this Kalpa was Swayambhu Manu and his wife Shatrupa. But still they are not the first man and women of world. They are just first progenitor of man kind of this kalpa. Before this kalpa there was Pitri Kalpa and there were 14 Manus in that kalpa. Before that also there were 14 Manus in the before kalpa and so on goes... For scriptural reference see the answer here. How many Manus have been there? ________________________________________ Summarizing the cosmology in shortcut. Brahma lives for 100 years of Brahma loka. Each day of Brahma is equivalent to 4.3 billion years and so is his night ie. 4.3 billion years. 4.3 billion year is 1 Day of Brahma which is called Kalpa. We are now in 2nd Parardha of Brahma ie. Brahma is now 51 years old . Hence about 51×360=18360 Kalpas has already passed in this time of Brahma. Each Kalpa is ruled by 14 Manus. Hence up to now about 18360×14=257040 Manus ie.progenitor of mankind have already passed. Hence there are about 2 lakh 57 thousands progenitor of Mankind up to this time of Brahma. _______________________________________ Now you may ask, Who is the 1st Manu in the 1st Day of Brahma? 1st day of Brahma is known as Brahma kalpa. There were also 14 Manus ruling that kalpa. 1st Manu of 1st Kalpa is not also the first Man of this world. It is because there were also previous Brahmas before current Brahma. We cannot even get information about origin of 1st Brahma they go back and back and back in time up to infinity. Hence we can't find the origin of 1st Man and Women in world. _______________________________________ Hence it is impossible to find the first man and women as nature of time is cyclical. But Kalpantak pralaya occurs after each kalpa and physical, celestial and lower realm suffers destruction. Hence it is possible to find 1st man kind generator after that destruction ie, 1st Manu of Kalpa. _______________________________________ We are currently on 28th Kali of Vaivasvat Manwantar of Shewta Varaha Kalpa. For the scriptural reference that we are in 28th chatur yuga see the answer here. Did the Mahabharata and the Ramayana happen in the current Yuga cycle in the current Manvantara? Vaivasvat is 7th Manu of present kalpa. Each manu is slightly greater than 71 chatur yugas. Period of Each manu = 4.3 billion years/ 14 =ie. about 307 hundred million years. The period of total 6 Manu= 6×307 hundred million years=about 1.84 billion years. Passed years of Vaivasvata Manvantara= 28×4320000-427000= about 120 million years. Hence total passed time from Swayambhu Manu to present = 1.84 billion year + 120 million years = about 1.96 billion years. Hence 1st progenitor of Man kind of this kalpa was about before 1.96 billion years from now. His name was Swayambhu and Brahma created him from his skin (kaya). Brahma also gave him his wife Satrupa to populate this earth. Thus Swayambhu and Shatrupa are first Human Progenitors of this Kalpa. [[Note that the above calculation of 1.96 billion year is obtained by using one chaturyuga equals 12000 divine year and each divine year is 360 human year. It is supported by various Purans. But some people debate on these yuga lengths. They argue multiplication of 360 is arbitrarily assigned in Puran. Hence it may also be wrong]] ________________________________________ Furthermore, Hinduism supports multiverse. Srimad Bhagvat tells countless universes appear just like dust particles around the body of Maha Vishnu. Hence if we take multiverse in account then 1st origin of something in world makes no sense, we have to solve them by using concepts of infinity. What am I, a small creature measuring seven spans of my own hand? I am enclosed in a pot-like universe composed of material nature, the total material energy, false ego, ether, air, water and earth. And what is Your glory? Unlimited universes pass through the pores of Your body just as particles of dust pass through the openings of a screened window (Bhagavata Purana 10.14.11) A: Yes, there is a concept of first man and woman in Hinduism. This is mentioned in Brihadaranyaka Upanishad 1.4 which deals with the creation of the world. Verse 1.4.3: स व नैव रेमे, तस्मादेकाकी न रमते; स द्वितीयमैच्छत् । स हैतावानास यथा स्त्रीपुमांसौ सम्परिष्वक्तौ; स इममेवात्मानं द्वेधापातयत्, ततः पतिश्च पत्नी चाभवताम्; तस्मातिदमर्धबृगलमिव स्वः इति ह स्माह याज्ञवल्क्यः; तस्मादयमाकाशः स्त्रिया पूर्यत एव; तां समभवत्, ततो मनुष्या अजायन्त ॥ ३ ॥ sa va naiva reme, tasmādekākī na ramate; sa dvitīyamaicchat | sa haitāvānāsa yathā strīpumāṃsau sampariṣvaktau; sa imamevātmānaṃ dvedhāpātayat, tataḥ patiśca patnī cābhavatām; tasmātidamardhabṛgalamiva svaḥ iti ha smāha yājñavalkyaḥ; tasmādayamākāśaḥ striyā pūryata eva; tāṃ samabhavat, tato manuṣyā ajāyanta || 3 || 3. He was not at all happy. Therefore people (still) are not happy when alone. He desired a mate. He became as big as man and wife embracing each other. He parted this very body into two. From that came husband and wife. Therefore, said Yājñavalkya, this (body) is one-half of oneself, like one of the two hálves of a split pea. Therefore this space is indeed filled by the wife. He was united with her. From that men were born. Śaṅkarācārya interprets the verse as (tr. by Swāmi Mādhavānanda): Here is another reason why the state of Virāj is within the relative world, because he, Virāj, was not at all happy, i.e. was stricken with dissatisfaction, just like us. Because it was so, therefore, on account of loneliness etc., even to-day people are not happy, do not delight, when alone. Delight is a sport due to conjunction with a desired object. A person who is attached to it feels troubled in mind when he is separated from his desired object; this is called dissatisfaction. To remove. that dissatisfaction, he desired a mate, able to take away that dissatisfaction, i. e; a wife. And as he thus longed for a wife, he felt as if he was embraced by his wife. Being of an infallible will, through that idea he became as big—as what ?—as man and wife, in the world, embracing each other to remove their dissatisfaction. He became of that size. He parted this very body, of that size, into two. The emphatic word ‘very’ used after ‘this’ is for distinguishing between the new body and its cause, the original body of Virāj. Virāj did not become of this size by wiping out his former entity, as milk turns into curd by wholly changing its former substance. What then? fíe remained as he was, but being of an infallible resolve, he projected another body of the size of man and wife together. He remained the same Virāj, as we find from the sentence, ‘He became as big as,’ etc., where ‘he’ is co-ordinate with the complement. From that parting came husband (Pati) and wife (Patnī). This is the derivation of terms denoting an ordinary couple. And because the wife is but one-half of oneself separated, therefore this body is one-half, like one of the two halves of a split pea, before one marries a wife. Whose half? Of oneself. Thus said Yājñavalkya, the son of Yajñavalka, lit. the expounder of a sacrifice, i.e. the son of Devarāta. Or it may mean a descendant of Hiraṇyagarbha (who is the expounder). Since one-half of a man is void when he is without a wife representing the other half, therefore this space is indeed again filled by the wife when he marries, as one-half of a split pea gets its complement When again joined to the other half. He, the Virāj called Manu, was united with her, his daughter called Śatarūpā, whom he conceived of as his wife. From that union men were born. Manu-smriti 1.32 also states the same thing: 32. Dividing his own body, the Lord became half male and half female; with that (female) he produced Virag. Brh. Up 1.4.4 further states that the same man and woman kept taking other lifeforms and created the rest of the animal world as we know it: Verse 1.4.4: She thought, 'How can he be united with me after producing me from himself? Well, let me hide myself.' She became a cow, the other became a bull and was united with her; from that cows were born. The one became a mare, the other a stallion; the one became a she-ass, the other became a he-ass and was united with her; from that one-hoofed animals were born. The one became a she-goat, the other a he-goat; the one became a ewe, the other became a ram and was united with her; from that goats and sheep were born. Thus did he project everything that exists in pairs, down to the ants. In the book, Hindu Dharma: The Universal Way of Life, Swami Chandrasekarendra Saraswati opines that the Mundakopaniṣad story of the two birds perched on a tree branch has undergone many changes over the centuries to become the current Adam and Eve story of Abrahamic religions: You must be familiar with the story of Adam and Eve which belongs to the Hebrew tradition. It occurs in the Genesis of the Old Testament and speaks of the Tree of Knowledge and God's commandment that its fruit shall not be eaten. Adam at first did not eat it but Eve did. After that Adam too ate the forbidden fruit. Here an Upaniṣadic concept has taken the form of a biblical story. But because of the change in time and place the original idea has become distorted or even obliterated. The Upaniṣadic story (6) speaks of two birds perched on the branch of a pippala (7) tree. One eats the fruit of the tree while the other merely watches its companion without eating. The pippala tree stands for the body. The first bird represents a being that regards itself as the jīvātman or individual Self and the fruit it eats signifies sensual pleasure. In the same body (symbolised by the tree) the second bird is to be understood as Paramātman. It is the support of all beings but It does not know sensual pleasure. Since It does not eat the fruit It does not naturally have the same experience as the jīvātman (the first bird). The Upanishad speaks with poetic beauty of the two birds. The one who eats the fruit is the individual Self, jīva, and the one who does not eat is the Supreme Reality, the one who knows himself to be the Ātman. It is this jīva that has come to be called "Eve" (8) in the Hebrew religious tradition. "Ji" changes to "i" according to a rule of grammar and "ja” to "ya". We have the example of “Yamuna” becoming "Jamuna” or of "Yogindra” being changed to "Joginder”. In the biblical story "jīva” is "Eve" and "Ātma" (or "Ātman") is "Adam”. “Pippala” has in the same way changed to “apple”. The Tree of Knowledge is our “bodhi-vrkṣa”. “Bodha” means “knowledge”. It is well known that the Buddha attained enlightenment under the bodhi tree. But the pīpal (pippala) was known as the bodhi tree even before his time. The Upaniṣadic ideas transplanted into a distant land underwent a change after the lapse of centuries. Thus we see in the biblical story that the Ātman (Adam) that can never be subject to sensual pleasure also eats the fruit of the Tree of Knowledge. While our bodhi tree stands for enlightenment, the enlightenment that banishes all sensual pleasure, the biblical tree affords worldly pleasure. These differences notwithstanding there is sufficient evidence here that once upon a time, the Vedic religion was prevalent in the land of the Hebrews. (6) The story is told in the Mundakopaniṣad. (7) "Pippala" is the pīpal or Ficus religiosa. (8) The meaning of the original Hebrew word is indeed "life".
{ "pile_set_name": "StackExchange" }
Q: What's a good practice when unittesting views that perform calls to external services in django We have this view that look something like this: from fblib import Facebook def foo(request): fb = Facebook( settings.facebook ) data = fb.get_thingy() return render_to_response( .. , data, .. ) What would be a good way of testing that? Since the view fetches the resource by itself I'm unsure how I could mock Facebook. One alternative in my mind is to create a fake Facebook server and supply the connection details in the settings. So we get a unittest that look something like this: from fakebook import FakeFacebookServer class ViewsFooTests(TestCase): def set_up( self ): self.facebook = FakeFacebookServer().start() def test_foo_connect( self ): response = self.client.get('/foo') self.assertEquals( response.status_code, 200 ) The issue I have with the that is that it seem like making a fake Facebook server seem like a lot of hassle. Ideally I would rather be able to mock the Facebook.get_thingy method. Suggestions? A: You can modify your views module from your tests for mocking your library: # tests.py import myapp.views ... def setUp(self): myapp.views.Facebook = FaceBookMock
{ "pile_set_name": "StackExchange" }
Q: Running Dynamic Web Project within Application Server Tomcat/GlassFish We have a complicated setup via Maven, where different projects are packaged as wars then overlayed on each other. Today I watched a tutorial of creating a Dynamic Web Project that can run directly within GlassFish. You edit the files press save, and the changes are seen in GlassFish. Since our setup is complicated, I currently have to run some build scripts to copy files to a locally installed Tomcat. Is there some way to run my source files (that are in several different /src folders) directly on an application server? So that I can edit files and see their change directly in the Application server. A: Due to maven being the glue holding the project together, this was not possible. I am manually deploying a war then writing many scripts to push files in to update files I'm working on.
{ "pile_set_name": "StackExchange" }
Q: Attempted to access nv(2.8); index must be a positive integer or logical I'm very new to MatLab and I am trying to write a simple flash calculation code, however I am getting the above error. I was wondering if you could help me. I'm not sure what the error is asking. Zi = [0.2, 0.1, 0.1, 0.2, 0.2, 0.2]; pvi = [190, 72.2 51.6, 20.44, 15.57, 4.956]; Ki = [3.8, 1.444, 1.032, 0.4088, 0.3114, 0.09912]; A = 0; B = 0; for i = 1:length(Zi) A = A + Zi(i)*(Ki(i)-1); B = B + Zi(i)*((1/Ki(i))-1); end nv0= A/(A+B); % Display an error message if 0<nv<1 if nv0 > 1 || nv0 < 0 || nv0 ==0 error('nv guess is incorrect') end % Step 2 - Solving Equation 5 - 16 for nv Using Newton-Raphson Method nv = nv0; nv0 = nv + .01; % Is this for the first gues abs dev? itermax = 200; fnkd = 0; fnk = 0; while abs(nv0 - nv) > tol & iter < itermax iter = iter + 1; nv0 = nv; for i= 1:length(Zi) fnk = fnk + ((Zi(i) * (Ki(i)-1))/(nv(Ki(i)-1)+1)); fnkd = fnkd +(-1*(Zi(i)*(Ki(i)-1)^2)/(nv(Ki(i)-1)+1)^2); end if fnkd ~= 0 nv = nv0 - fnk/fnkd; else nv = nv0 + 0.01; end end nv This is the error I'm getting: Error in FlashCal (line 74) fnk = fnk + ((Zi(i) * (Ki(i)-1))/(nv(Ki(i)-1)+1)); Where: fnk = sigma(i) Zi(Ki-1)/nv(Ki-1)+1 fnkd = - sigma(i) Zi(Ki-1)^2/(nv(Ki-1)+1)^2 Many Thanks A: nv(Ki(i)-1) is not valid. Either you mean nv*(Ki(i)-1) or Ki(i)-1 should evaluate to an integer since you use it to access nv at position (Ki(i)-1). However, it is 2.8, i.e. (3.8-1)
{ "pile_set_name": "StackExchange" }
Q: Virtual box Android emulator and Eclipse I start to use this VirtualBox machine as Android emulator in my development: http://www.buildroid.org/blog/?page_id=121 I install and execute my application in this emulator but when I try to connect to Eclipse using adb connect [my ip address] I found problems. When I connect my virtual machine with Eclipse using host only network for eth1 my virtual device lost its internet connection. My device access internet only when eth01 network configuration is NAT but with this configuration I can't connect with Eclipse using adb connect. Any idea about it? A: Finally my Virtual Box emulator work and communicate with Eclipse. When I found the correct network configuration all work perfectly. My correct network configuration is: Et01: NAT Et02: Internal network. In adb -connect I've use the Et01 Ip to connect it with Eclipse. I hope be usefull!!
{ "pile_set_name": "StackExchange" }
Q: Your hand goes in and pull it out Your shirt is on inside-out. "Your hand goes in and pull it out." "Your hand goes in and flip it out." How do we say clearly the action to put the inside-out shirt to right position? A: Reach in and turn it rightside-out This is probably the most natural way explain this. You could say "put your hand in" when instructing young children, but with adults you would use "reach in/into": Reach into the cupboard and get me a cookie, would you? Meanwhile, you turn a shirt (or any similar object) inside-out, and turn it again rightside-out: If you want me to sew up the hole in your jacket, first turn it inside-out for me.
{ "pile_set_name": "StackExchange" }
Q: Why give an Error? I just want to find out why this piece of code throws an Error. The Error is : "Exception in thread "Thread-1" java.lang.Error" class Salmon extends Thread { public static long id; public void run() { for(int i = 0;i<4; i++){ if(i==2&& id ==Thread.currentThread().getId()){ //if(i==2){ new Thread(new Salmon()).start(); throw new Error(); } System.out.println(i + " "); } } public static void main(String[] args) { Thread t1 = new Salmon(); id = t1.getId(); t1.start(); } } A: Because you tell it to. if(i==2){ new Thread(new Salmon()).start(); throw new Error(); // <---- A: I think your question might be better specified "why does execution continue beyond new Thread(new Salmon()).start();? You're starting a new thread. When you call start(), execution of the run() method in the new thread continues in parallel with the continued execution after the immediately-returning start() method.
{ "pile_set_name": "StackExchange" }
Q: Update quantity echo ahref I'm trying to create an integer update form field for my cart system. On the page, I already have a + and - function to increase and decrease the quantity by 1. How could I include an integer form field next to the (+) and (-) to udpate by a certain result and then send this to the cart page. Thank you very much for any help. This is the main part of the code that is enclosed within PHP (I left out the information before the first a href link because it isn't important) <a href="cart.php?increase=<?php echo $num; ?>"> (+) </a> <a href="cart.php?remove=<?php echo $num; ?>"> (-) </a> A: You'll have to post a form to cart.php: <form action="cart.php" method="post"> <input type="text" name="qty"/> <input type="submit" name="submit_increase" value="(+)"/> </form> <form action="cart.php" method="post"> <input type="text" name="qty"/> <input type="submit" name="submit_remove" value="(-)"/> </form> And in your cart.php, you can use if (isset($_POST['submit_increase'])) to determine if you're increasing or decreasing, then $_POST['qty'] to grab the number of items to add/remove. This isn't the only solution. You could use one form, hidden inputs, or javascript to build a query string. Its up to you.
{ "pile_set_name": "StackExchange" }
Q: How to structure SQL Statement I have a table that contains a list of tasks; TableName: Tasks. Fields: (ID Int, Description nvarchar) The tasks are completed daily and are logged in a table like follows; TableName TasksDone. Fields: (TaskID Int, TaskDate DateTime) I need to have a query that runs for a date range and shows the tasks that were NOT done (do not exist in the TasksDone table) for every date in the range. I hope that makes sense... Thanks for any help. A: You will need a numbers or calendar table to make things easy, or we can simulate one if the range is small. Is the TaskDate a plain date, or does it have a time component also? Basic plan of attack is: declare @StartDate datetime declare @EndDate datetime /* Set @StartDate and @EndDate to represent the range */ with Digits as ( select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 ), Numbers as ( select (D1.d * 100) + (D2.d * 10) + D3.d as n from Digits D1,Digits D2,Digits D3 ), TaskDates as ( select t.TaskID, DATEADD(day,n.n,@StartDate) as TaskDate from Tasks t inner join Numbers n on DATEADD(day,n.n,@StartDate) <= @EndDate ) select * from TaskDates td1 left join TasksDone td2 on td1.TaskID = td2.TaskID and DATEDIFF(day,td1.TaskDate,td2.TaskDate) = 0 where td2.TaskID is null The first two CTEs build a small numbers table, the 3rd CTE constructs a set of TaskIDs and Dates within the required range. The final select matches theses against the TasksDone table, and then discards those rows where a match is found. If TasksDone.TaskDate is a plain date (no time component) and @StartDate is also with no time component, then you can ditch the DATEDIFF and just use td1.TaskDate = td2.TaskDate. If you need a large range (above can cover ~3 years), I'd suggest building a proper number table or calendar table
{ "pile_set_name": "StackExchange" }
Q: auto height on parent div of a menu div... how? Well the basic idea is to get the wrapper automaticaly expand height depending on the height of the children. The problem though is that the menu child has a float attr, and if it's bigger than content - it's simply sticking out, this you can see by loading the code. I don't like playing with relative position, table-cells.. And if I set float:left on the wrapper it actually bugs my whole markup for some reason. Is there any other way I can do this? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style> div.wrap{ background-color:grey; padding:5px; } div.left{ background-color:orange; float:left; width:200px; height:400px; } div.content{ margin-left:200px; height:200px; background-color:white; } </style> </head> <body> <div class="wrap"> <div class="left"> Menu </div> <div class="content"> Text </div> </div> </body> </html> A: Inside div.wrap: <div class="clear"></div> Inside <style>: div.clear{ clear:both; }
{ "pile_set_name": "StackExchange" }
Q: Add a folder to a zip blob Utilities.zip(blobs) compress all the blobs in the array argument and generate a "zip" blob. I can create a file in Drive from this blob. I need a zip file with folders in it (actually, I need only one folder). Is there a way to generate a folder in a zip blob? Or is there a way to make a blob from a folder and its content? Thank you A: Well, it turned out to be easy. Let's say I have two blobs blob1 and blob2, and I want blob1 in a folder: blob1.setName('folder/' + blob1.getName()); Utilities.zip([blob1, blob2], 'zipped.zip'); Worked for me. BTW, Utilities.zip() is still undocumented. The only available "documentation" is the autocomplete hint.
{ "pile_set_name": "StackExchange" }
Q: Mantener los 0 a la izquierda Mi programa me ignora los 0 a la izquierda, ejemplo le pasan 001 y lo toma como 1 y lo necesito todo completo. Mi codigo va de la siguiente manera function rotate_to_max($n): int { echo "El numero inicial es ".$n."\n"; $vec = array(); while($n != 0){ $vec[] = $n%10; $n = (integer)($n/10); } rsort($vec); return implode($vec); } Y al conseguir números como 000001 ignora los 0 y no es lo que quiero. Que es lo que hace mi codigo me ordena de mayor a menor el numero pasado, entonces 001 me lo toma como 1 y necesito que 001 lo tome como 100 igual con otro numero que pasen, ejemplo: 00145 => 54100 y lo hace es 00145 => 541, entonces 541 != 54100 A: Creo entender que quieres pasar en tu función números enteros (integer) con 0 liderando. En PHP y creo saber en ningún otro lenguaje, los 0 de la izquierda no se almacenan en la memoria ya que son irrelevantes. Ejemplo: $num = 000001; echo $num; // salida: 1 (integer) echo (string)$num; // salida: "1" (string) No obstante todos los numero liderando con un cero son considerado como sistema octal. Números octales sólo pueden utilizar los dígitos 0-7, al igual en el sistema decimal puedes utilizar 0-9 y 0-1 en números binarias. Números octal: echo 00; // 0 echo 01; // 1 ... echo 06; // 6 echo 07; // 7 echo 08; // Error: no existe echo 010; // 8 echo 011; // 9 echo 012; // 10 Entonces para realizar tu siguiente función rotate_to_max tienes que pasar los números como string y lo puedes resolver de la siguiente manera: <?php // Podemos declarar el modo estricto declare(strict_types=1); // Aquí esperamos un string como valor de entrada function rotate_to_max(string $string) { return "\u{202E}$string"; } echo rotate_to_max('001005'); // ‮001005 + info sobre las nuevas características en PHP7 El compañero Dev.Joel te ha dicho ya que se podría hacer con la función strrev(), pero ya que usas las nuevas características de PHP7 puedes invertir también la cadena con unicode_escape. echo "\u{202E}Reversed text"; // outputs ‮Reversed text Ver Demo A: Hazlo como un string, ejemplo: function rotate_to_max($n): int { echo "El numero inicial es ".$n[0]."\n"; $vec = array(); $i = 0; while($n != 0){ $i++; $vec[] = $n[$i] % 10; $n = (integer)($n[0] /10); } rsort($vec); return implode($vec); } Entonces: $val = rotate_to_max("0004"); Si estas trabajando con flotantes esto no debería ser así.
{ "pile_set_name": "StackExchange" }
Q: Drive Search not working with Client Credentials token Trying to perform a search action on a Drive with a Client Credentials (App) token, like with the following URL: https://graph.microsoft.com/v1.0/groups/{GROUP_ID}/drive/root/search(q='newFileTest.docx') ... results in a 403 error: { "error": { "code": "accessDenied", "message": "The caller does not have permission to perform the action.", "innerError": { "request-id": "**redacted**", "date": "2019-04-17T12:47:10" } } } The client has the Files.ReadWrite.All permisson, which is necessary to be able to execute a search query, and can read/write folders and files without any issues. Executing the same command with Delegated Auth (so with a logged-in user, e.g. the Microsoft Graph Explorer) works, but returns 0 results (see this bug for details). This seems like a bug to me, but would be happy to hear if someone thinks it's not. A: Turns out that for Search to work with Client Credentials, the application needs to have the Sites.ReadWrite.All permission. The Files.ReadWrite.All permission is not enough, even though the documentation mentions "One of the following permissions is required to call this API". Filed a Microsoft Docs GitHub issue.
{ "pile_set_name": "StackExchange" }
Q: Deleting a zipped file Is there anyway to delete a zip file using Excel VBA? I've tried using Kill folderName & "\*.*" but this will only delete the files in a folder and rmdir foldername delete an empty folder. I have this line of code which has the directory of the zipped file dim ws as Worksheet set ws = thisworkbook.sheets("Sheet1") ws.range("P3").value ' contains the directory of the zip file debug.print ws.range("P3").value 'result C:\Documents\MyFilesZip 23-Nov-16_18-06-03.zip kill ws.range("P3").value I've done it that way but it errors saying: `Path not found Can you give me some ideas please? Already figured it out, since the zipped file is hidden, and maybe has other attributes, I've set the attribute of the file first to vbNormal before killing it :) Thanks. A: This works like a charm: Kill "C:\Users\gropc\Desktop\test.zip"
{ "pile_set_name": "StackExchange" }
Q: Remove duplicate rows based on conditions from multiple columns (decreasing order) in R I have a 3-columns data.frame (variables: ID.A, ID.B, DISTANCE). I would like to remove the duplicates under a condition: keeping the row with the smallest value in column 3. It is the same problem than here : R, conditionally remove duplicate rows (Similar one: Remove duplicates based on 2nd column condition) But, in my situation, there is second problem : I have to remove rows when the couples (ID.A, ID.B, DISTANCE) are duplicated, and not only when ID.A is duplicated. I tried several things, such as: df <- ddply(df, 1:3, function(df) return(df[df$DISTANCE==min(df$DISTANCE),])) but it didn't work Example : This dataset id.a id.b dist 1 1 1 12 2 1 1 10 3 1 1 8 4 2 1 20 5 1 1 15 6 3 1 16 Should become: id.a id.b dist 3 1 1 8 4 2 1 20 6 3 1 16 A: Using dplyr, and a suitable modification to Remove duplicated rows using dplyr library(dplyr) df %>% group_by(id.a, id.b) %>% arrange(dist) %>% # in each group, arrange in ascending order by distance filter(row_number() == 1)
{ "pile_set_name": "StackExchange" }
Q: Ruby Rack Heroku: Serving Static Files I have followed the Heroku guide on deploying static files using Ruby Rack (https://devcenter.heroku.com/articles/static-sites-ruby), but I was unable to access any HTML file in \public apart from index.html. Namely, localhost:9292/test.html still maps to index.html. (All my style and js files serve correctly). Below is my config.ru file. I know what's wrong, but not sure about a valid solution? use Rack::Static, :urls => ["/images", "/js", "/css"], :root => "public" run lambda { |env| [ 200, { 'Content-Type' => 'text/html', 'Cache-Control' => 'public, max-age=86400' }, File.open('public/index.html', File::RDONLY) ] } A: For your config.ru file, try: use Rack::Static, :urls => ["/images", "/js", "/css"], :root => "public" run Rack::File.new("public") You could also replace the last line with run Rack::Directory.new("public") which would serve up all your files, but would give a file browser like interface if someone went to the url of a directory (like the root directory)
{ "pile_set_name": "StackExchange" }
Q: Choose image URL from large array, insert into random DIV on page, cycle Bit of an odd request. I have ~300 image URLs and 27 divs. Each div has an id="img1", where 1 is a number between 1 and (you guessed it) 27, and a class="imageblock" (for general styling). Into each of these divs, I'd like to insert an <img src="http://foo.bar/img.jpg" width="640">, where the URL is chosen from a list of about 300 randomly, and inserted into one of the divs randomly. Each of the 27 divs should have its own image chosen from the 300 options. Furthermore, these images should cycle. Every 5 seconds, I'd like to have one random image URL on the page replaced with another random one. This is the (terrible) code I have attempted to cobble together with a little help, but I'm useless with javascript and can't make this work: <script type="text/javascript"> $('document').ready(function() { var divs = $('div'); $("div").each(function() { $(this).html("<img src='http://foo.bar/img1.jpg'alt='"+$(this).attr("id")+"'/>"); }); var imageChanger = setInterval(function() {switchImage()}, 500); function switchImage() { var new_image_url = [ 'http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg']; var random_div = Math.floor(Math.random() * $('div').length); var random_img = Math.floor(Math.random() * $(new_image_url.length); $("div:nth-child("+random_div+")").html('<img src="('+random_img+')" width="640">)'); } }); </script> Note that the remote images do not follow any common pattern, thereby rendering my random_img variable unworking. Any help would be appreciated. A: To select a random element from an array, you can use this: var random_div = divs[Math.floor(Math.random() * divs.length)]; var random_img = new_image_url[Math.floor(Math.random() * new_image_url.length)]; Here's a slightly more efficient version of your code: function random_int(max) { return Math.floor(Math.random() * max); } $(document).ready(function() { var images = ['http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg']; var $divs = $('div'); $divs.each(function() { $('<img />', { src: 'http://foo.bar/img1.jpg', alt: this.id }).appendTo(this); }); function switchImage() { var $div = $divs.eq(random_int($divs.length)); var image = images[random_int(images.length)]; $div.find('img').attr('src', image); } var imageChanger = setInterval(switchImage, 500); });
{ "pile_set_name": "StackExchange" }
Q: Unable to write to SQL Server using C#; no errors produced yet nothing is written to table After several hours of researching and not finding a solution, I am now requesting assistance. I am not a C# wizard; your knowledge and insight on this will be greatly appreciated. My goal is to write an access attempt to an audit log on each page load. I have verified the connection string's Server\Instance, Database, User, and Password I have done a linked server test from another server using the credentials copy/pasted from the connection string, with success. I have validated the query in SSMS. SQL Server Profiler does not even register an attempt to connect to the database My code: using System; using System.Data; using System.Data.SqlClient; using System.Net; using System.Web; namespace NAMESPACE { public partial class Site : System.Web.UI.MasterPage { public string string1 = ""; public string string2 = ""; public string string3 = ""; protected void Page_Load(object sender, EventArgs e) { string1 = DateTime.Now.ToString("yyyyMMdd_") + Guid.NewGuid().ToString().Substring(1,5); string2 = HttpContext.Current.Request.LogonUserIdentity.Name.ToLower(); string3 = HttpContext.Current.Request.Url.ToString(); // Define SQL connection string and query string connString = "Server=SERVER\\INSTANCE;" + "Database=DB;" + "User Id=USER;" + "Password=PSWD;"; string queryString = "insert into dbo.TABLE ([col1], [col2], [col3])" + "values (@val1, @val2, @val3)"; // Write to DB using (SqlConnection conn = new SqlConnection(connString)) { using (SqlCommand cmd = new SqlCommand(queryString, conn)) { cmd.Parameters.Add("@val1", SqlDbType.NVarChar, 100).Value = string1; cmd.Parameters.Add("@val2", SqlDbType.NVarChar, 100).Value = string2; cmd.Parameters.Add("@val3", SqlDbType.NVarChar, 100).Value = string3; conn.Open(); } //conn.Close(); } } } } A: You're not executing the query. using(SqlConnection conn = new SqlConnection(constr)){ conn.open(); using(SqlCommand cmd = new SqlCommand(queryString, conn)){ cmd.Parameters.AddWithValue("@val1", string1); cmd.Parameters.AddWithValue("@val2", string2); cmd.Parameters.AddWithValue("@val3", string3); cmd.ExeucuteNonQuery(); } }
{ "pile_set_name": "StackExchange" }
Q: Preview a camera in DirectShow and capture a still image - in VB.net I am trying to write a program in Visual Studio 2008 that will access a webcam, show a preview on the screen and then save a still snapshot (.jpg) when the button is pushed. Later I am going to integrate it with a database, but I shouldn't have a problem with that part. After doing some research, it looks like DirectShow is the best bet, because WIA didn't work on the camera I had (and I'm not sure it will continue to work into the future). Preferably, I need my solution to work from Windows XP to Windows 7. I have never used DirectShow (or similar) before. One problem I am running into is that most of the code is written in C#, which I have never learned. I found a DirectShow.Net library that also uses vb.net, so that is helpful, but I am still having problems. The following code is taken from the samples in the library, and works, but I want to alter it somewhat and can't quite get it to work. The code right now saves the camera capture to a file. I can rem out the "capGraph.SetOutputFileName" line, the video will just launch into its own window, but I don't how to control that. Basically, I would like to know how to do two things: How do I get DirectShow to display in a control on a form that I specify (picturebox?)? Can I then get a snapshot of that video when the user clicks a button (it can pause the video, or whatever, because at that point I don't need the preview to resume, at least not for a number of seconds.) Thanks a lot, and sorry if some of this is not phrased very well. I am self-taught, and have done a lot in vba and php, but this is a little beyond my experience. '**************************************************************************** 'While the underlying libraries are covered by LGPL, this sample is released 'as public domain. It is distributed in the hope that it will be useful, but 'WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 'or FITNESS FOR A PARTICULAR PURPOSE. '*****************************************************************************/ Imports System Imports System.Drawing Imports System.Drawing.Imaging Imports System.Runtime.InteropServices Imports System.Diagnostics Imports DirectShowLib Public Class Capture Implements ISampleGrabberCB Implements IDisposable #Region "Member variables" ' <summary> graph builder interface. </summary> Private m_graphBuilder As IFilterGraph2 = Nothing Private m_mediaCtrl As IMediaControl = Nothing ' <summary> Set by async routine when it captures an image </summary> Private m_bRunning As Boolean = False ' <summary> Dimensions of the image, calculated once in constructor. </summary> Private m_videoWidth As Integer Private m_videoHeight As Integer Private m_stride As Integer Private m_bmdLogo As BitmapData = Nothing Private m_Bitmap As Bitmap = Nothing #If Debug Then ' Allow you to "Connect to remote graph" from GraphEdit Private m_rot As DsROTEntry = Nothing #End If #End Region #Region "API" Declare Sub CopyMemory Lib "Kernel32.dll" Alias "RtlMoveMemory" (ByVal Destination As IntPtr, ByVal Source As IntPtr, <MarshalAs(UnmanagedType.U4)> ByVal Length As Integer) #End Region ' zero based device index, and some device parms, plus the file name to save to Public Sub New(ByVal iDeviceNum As Integer, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer, ByVal FileName As String) Dim capDevices As DsDevice() ' Get the collection of video devices capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice) If (iDeviceNum + 1 > capDevices.Length) Then Throw New Exception("No video capture devices found at that index!") End If Dim dev As DsDevice = capDevices(iDeviceNum) Try ' Set up the capture graph SetupGraph(dev, iFrameRate, iWidth, iHeight, FileName) Catch Dispose() Throw End Try End Sub ' <summary> release everything. </summary> Public Sub Dispose() Implements IDisposable.Dispose CloseInterfaces() If (Not m_Bitmap Is Nothing) Then m_Bitmap.UnlockBits(m_bmdLogo) m_Bitmap = Nothing m_bmdLogo = Nothing End If End Sub Protected Overloads Overrides Sub finalize() CloseInterfaces() End Sub ' <summary> capture the next image </summary> Public Sub Start() If (m_bRunning = False) Then Dim hr As Integer = m_mediaCtrl.Run() DsError.ThrowExceptionForHR(hr) m_bRunning = True End If End Sub ' Pause the capture graph. ' Running the graph takes up a lot of resources. Pause it when it ' isn't needed. Public Sub Pause() If (m_bRunning) Then Dim hr As Integer = m_mediaCtrl.Pause() DsError.ThrowExceptionForHR(hr) m_bRunning = False End If End Sub ' <summary> Specify the logo file to write onto each frame </summary> Public Sub SetLogo(ByVal fileName As String) SyncLock Me If (fileName.Length > 0) Then m_Bitmap = New Bitmap(fileName) Dim r As Rectangle = New Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height) m_bmdLogo = m_Bitmap.LockBits(r, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb) Else If Not m_Bitmap Is Nothing Then m_Bitmap.UnlockBits(m_bmdLogo) m_Bitmap = Nothing m_bmdLogo = Nothing End If End If End SyncLock End Sub ' <summary> build the capture graph for grabber. </summary> Private Sub SetupGraph(ByVal dev As DsDevice, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer, ByVal FileName As String) Dim hr As Integer Dim sampGrabber As ISampleGrabber = Nothing Dim baseGrabFlt As IBaseFilter = Nothing Dim capFilter As IBaseFilter = Nothing Dim muxFilter As IBaseFilter = Nothing Dim fileWriterFilter As IFileSinkFilter = Nothing Dim capGraph As ICaptureGraphBuilder2 = Nothing ' Get the graphbuilder object m_graphBuilder = DirectCast(New FilterGraph(), IFilterGraph2) m_mediaCtrl = DirectCast(m_graphBuilder, IMediaControl) #If Debug Then m_rot = New DsROTEntry(m_graphBuilder) #End If Try ' Get the ICaptureGraphBuilder2 capGraph = DirectCast(New CaptureGraphBuilder2(), ICaptureGraphBuilder2) ' Get the SampleGrabber interface sampGrabber = DirectCast(New SampleGrabber(), ISampleGrabber) ' Start building the graph hr = capGraph.SetFiltergraph(DirectCast(m_graphBuilder, IGraphBuilder)) DsError.ThrowExceptionForHR(hr) ' Add the video device hr = m_graphBuilder.AddSourceFilterForMoniker(dev.Mon, Nothing, dev.Name, capFilter) DsError.ThrowExceptionForHR(hr) baseGrabFlt = DirectCast(sampGrabber, IBaseFilter) ConfigureSampleGrabber(sampGrabber) ' Add the frame grabber to the graph hr = m_graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber") DsError.ThrowExceptionForHR(hr) ' If any of the default config items are set If (iFrameRate + iHeight + iWidth > 0) Then SetConfigParms(capGraph, capFilter, iFrameRate, iWidth, iHeight) End If hr = capGraph.SetOutputFileName(MediaSubType.Avi, FileName, muxFilter, fileWriterFilter) DsError.ThrowExceptionForHR(hr) hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capFilter, baseGrabFlt, muxFilter) DsError.ThrowExceptionForHR(hr) SaveSizeInfo(sampGrabber) Finally If (Not fileWriterFilter Is Nothing) Then Marshal.ReleaseComObject(fileWriterFilter) fileWriterFilter = Nothing End If If (Not muxFilter Is Nothing) Then Marshal.ReleaseComObject(muxFilter) muxFilter = Nothing End If If (Not capFilter Is Nothing) Then Marshal.ReleaseComObject(capFilter) capFilter = Nothing End If If (Not sampGrabber Is Nothing) Then Marshal.ReleaseComObject(sampGrabber) sampGrabber = Nothing End If End Try End Sub ' <summary> Read and store the properties </summary> Private Sub SaveSizeInfo(ByVal sampGrabber As ISampleGrabber) Dim hr As Integer ' Get the media type from the SampleGrabber Dim media As AMMediaType = New AMMediaType() hr = sampGrabber.GetConnectedMediaType(media) DsError.ThrowExceptionForHR(hr) If (Not (media.formatType.Equals(FormatType.VideoInfo)) AndAlso Not (media.formatPtr.Equals(IntPtr.Zero))) Then Throw New NotSupportedException("Unknown Grabber Media Format") End If ' Grab the size info Dim vInfoHeader As VideoInfoHeader = New VideoInfoHeader() Marshal.PtrToStructure(media.formatPtr, vInfoHeader) m_videoWidth = vInfoHeader.BmiHeader.Width m_videoHeight = vInfoHeader.BmiHeader.Height m_stride = m_videoWidth * (vInfoHeader.BmiHeader.BitCount / 8) DsUtils.FreeAMMediaType(media) media = Nothing End Sub ' <summary> Set the options on the sample grabber </summary> Private Sub ConfigureSampleGrabber(ByVal sampGrabber As ISampleGrabber) Dim hr As Integer Dim media As AMMediaType = New AMMediaType() media.majorType = MediaType.Video media.subType = MediaSubType.RGB24 media.formatType = FormatType.VideoInfo hr = sampGrabber.SetMediaType(media) DsError.ThrowExceptionForHR(hr) DsUtils.FreeAMMediaType(media) media = Nothing ' Configure the samplegrabber callback hr = sampGrabber.SetCallback(Me, 0) DsError.ThrowExceptionForHR(hr) End Sub ' Set the Framerate, and video size Private Sub SetConfigParms(ByVal capGraph As ICaptureGraphBuilder2, ByVal capFilter As IBaseFilter, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer) Dim hr As Integer Dim o As Object = Nothing Dim media As AMMediaType = Nothing Dim videoStreamConfig As IAMStreamConfig Dim videoControl As IAMVideoControl = DirectCast(capFilter, IAMVideoControl) ' Find the stream config interface hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, GetType(IAMStreamConfig).GUID, o) videoStreamConfig = DirectCast(o, IAMStreamConfig) Try If (videoStreamConfig Is Nothing) Then Throw New Exception("Failed to get IAMStreamConfig") End If ' Get the existing format block hr = videoStreamConfig.GetFormat(media) DsError.ThrowExceptionForHR(hr) ' copy out the videoinfoheader Dim v As VideoInfoHeader = New VideoInfoHeader() Marshal.PtrToStructure(media.formatPtr, v) ' if overriding the framerate, set the frame rate If (iFrameRate > 0) Then v.AvgTimePerFrame = 10000000 / iFrameRate End If ' if overriding the width, set the width If (iWidth > 0) Then v.BmiHeader.Width = iWidth End If ' if overriding the Height, set the Height If (iHeight > 0) Then v.BmiHeader.Height = iHeight End If ' Copy the media structure back Marshal.StructureToPtr(v, media.formatPtr, False) ' Set the new format hr = videoStreamConfig.SetFormat(media) DsError.ThrowExceptionForHR(hr) DsUtils.FreeAMMediaType(media) media = Nothing ' Fix upsidedown video If (Not videoControl Is Nothing) Then Dim pCapsFlags As VideoControlFlags Dim pPin As IPin = DsFindPin.ByCategory(capFilter, PinCategory.Capture, 0) hr = videoControl.GetCaps(pPin, pCapsFlags) DsError.ThrowExceptionForHR(hr) If ((pCapsFlags & VideoControlFlags.FlipVertical) > 0) Then hr = videoControl.GetMode(pPin, pCapsFlags) DsError.ThrowExceptionForHR(hr) hr = videoControl.SetMode(pPin, 0) End If End If Finally Marshal.ReleaseComObject(videoStreamConfig) End Try End Sub ' <summary> Shut down capture </summary> Private Sub CloseInterfaces() Dim hr As Integer Try If (Not m_mediaCtrl Is Nothing) Then ' Stop the graph hr = m_mediaCtrl.Stop() m_mediaCtrl = Nothing m_bRunning = False End If Catch ex As Exception Debug.WriteLine(ex) End Try #If Debug Then If (Not m_rot Is Nothing) Then m_rot.Dispose() m_rot = Nothing End If #End If If (Not m_graphBuilder Is Nothing) Then Marshal.ReleaseComObject(m_graphBuilder) m_graphBuilder = Nothing End If GC.Collect() End Sub ' <summary> sample callback, Originally not used - call this with integer 0 on the setcallback method </summary> Function SampleCB(ByVal SampleTime As Double, ByVal pSample As IMediaSample) As Integer Implements ISampleGrabberCB.SampleCB myTest = "In SampleCB" Dim i As Integer=0 Dim hr As Integer 'jk added this code 10-22-13 if IsDBNull(pSample) =True then return -1 dim myLen As Integer = pSample.GetActualDataLength() dim pbuf As IntPtr if pSample.GetPointer(pbuf) = 0 AND mylen > 0 then dim buf As byte()= new byte(myLen) {} Marshal.Copy(pbuf, buf, 0, myLen) for i = 0 to myLen-1 step 2 buf(i) = (255 - buf(i)) Next i Dim g_RowSizeBytes As Integer Dim g_PixBytes() As Byte Dim bm As Bitmap = Nothing Dim m_BitmapData As BitmapData = Nothing Dim bounds As Rectangle = New Rectangle(0, 0, m_videoWidth, m_videoHeight) mytest = "Execution point #2" m_BitmapData = bm.LockBits(bounds, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format24bppRgb) mytest = "Execution point #4" g_RowSizeBytes = m_BitmapData.Stride mytest = "Execution point #5" ' Allocate room for the data. Dim total_size As Integer = m_BitmapData.Stride * m_BitmapData.Height ReDim g_PixBytes(total_size) mytest = "Execution point #10" 'this writes the modified data Marshal.Copy(buf, 0, m_BitmapData.Scan0, mylen) ' Unlock the bitmap. bm.UnlockBits(m_BitmapData) ' Release resources. g_PixBytes = Nothing m_BitmapData = Nothing End If Marshal.ReleaseComObject(pSample) Return 0 End Function ' <summary> buffer callback, COULD BE FROM FOREIGN THREAD. </summary> Function BufferCB(ByVal SampleTime As Double, ByVal pBuffer As IntPtr, ByVal BufferLen As Integer) As Integer Implements ISampleGrabberCB.BufferCB SyncLock Me If (Not m_bmdLogo Is Nothing) Then Dim ipSource As IntPtr = m_bmdLogo.Scan0 Dim ipDest As IntPtr = pBuffer Dim x As Integer For x = 0 To m_bmdLogo.Height - 1 CopyMemory(ipDest, ipSource, m_bmdLogo.Stride) ipDest = New IntPtr(ipDest.ToInt32() + m_stride) ipSource = New IntPtr(ipSource.ToInt32() + m_bmdLogo.Stride) Next x End If End SyncLock Return 0 End Function End Class A: Here is what I finally used for my project - it gives you a preview window, and then on another form you can push a button to take the picture. I take the picture and display that stillshot image as another picturebox on the main form (a little larger). I added a cropbox to choose what portion of that picture box you would ultimately like to save, but am not including that in this answer for simplicities sake. You initialize it with the call: cam = New Capture(my.Settings.VideoDeviceNum, FRAMERATE, my.Settings.CapturePictureWidth, my.Settings.CapturePictureHeight) and cam.Start() The snapshot is take with this call: Dim picError As Boolean=False cam.captureSaved=False cam.TakePicture Dim stTime As date = Now Do Until cam.captureSaved 'do nothing - might want to have an automatic break if this takes too long If DateDiff(DateInterval.Second,stTime,Now) >15 then MsgBox("The camera is taking a long time to capture the picture. Please try again.") picError=True:Exit do End If Loop If not picError then cam.Capturedpic.RotateFlip (RotateFlipType.Rotate180FlipX) 'scale the camera image and place it in the picture box CaptureBox.Image=scaleimage(cam.capturedpic,CaptureBox.Width,CaptureBox.Height) End If SavePicture.Visible = True myStatus.Text = "Picture Taken." The scaleimage function simply scales the snapshot image to the appropriate size for the box I have on the form. I only work with scaling the x, because I only allow a certain aspect ratio, so if you aren't going to lock in your aspect ratios for the camera, it will need to be adjusted: Public Function ScaleImage(source As Bitmap, x As Integer, y As Integer) As Bitmap Dim scale As single = x / source.Width Dim myBmp As new Bitmap(cint(source.Width*scale), cint(source.height*scale),source.PixelFormat) Dim gr As Graphics = Graphics.FromImage(myBmp) gr.DrawImage(source, 0, 0, myBmp.Width + 1, myBmp.Height + 1) Return myBmp End Function The main camera class is below: '**************************************************************************** 'While the underlying libraries are covered by LGPL, this sample is released 'as public domain. It is distributed in the hope that it will be useful, but 'WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 'or FITNESS FOR A PARTICULAR PURPOSE. '*****************************************************************************/ Imports System Imports System.Drawing Imports System.Drawing.Imaging Imports System.Runtime.InteropServices Imports System.Diagnostics Imports DirectShowLib Public Class Capture Implements ISampleGrabberCB Implements IDisposable #Region "Member variables" ' <summary> graph builder interface. </summary> Private m_graphBuilder As IFilterGraph2 = Nothing Private m_mediaCtrl As IMediaControl = Nothing Private mediaEventEx As IMediaEventEx = Nothing Private videoWindow As IVideoWindow = Nothing Private UseHand As IntPtr = MainForm.PreviewBox.Handle Private Const WMGraphNotify As Integer = 13 Private m_takePicture As Boolean = False Public mytest As String = "yes" Dim sampGrabber As ISampleGrabber = Nothing Private bufferedSize As Integer = 0 Private savedArray() As Byte Public capturedPic as bitmap Public captureSaved As Boolean Public unsupportedVideo As Boolean ' <summary> Set by async routine when it captures an image </summary> Public m_bRunning As Boolean = False ' <summary> Dimensions of the image, calculated once in constructor. </summary> Private m_videoWidth As Integer Private m_videoHeight As Integer Private m_stride As Integer Private m_bmdLogo As BitmapData = Nothing Private m_Bitmap As Bitmap = Nothing #If Debug Then ' Allow you to "Connect to remote graph" from GraphEdit Private m_rot As DsROTEntry = Nothing #End If #End Region #Region "API" Declare Sub CopyMemory Lib "Kernel32.dll" Alias "RtlMoveMemory" (ByVal Destination As IntPtr, ByVal Source As IntPtr, <MarshalAs(UnmanagedType.U4)> ByVal Length As Integer) #End Region ' zero based device index, and some device parms, plus the file name to save to Public Sub New(ByVal iDeviceNum As Integer, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer) Dim capDevices As DsDevice() ' Get the collection of video devices capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice) If (iDeviceNum + 1 > capDevices.Length) Then Throw New Exception("No video capture devices found at that index!") End If Dim dev As DsDevice = capDevices(iDeviceNum) Try ' Set up the capture graph SetupGraph(dev, iFrameRate, iWidth, iHeight) Catch Dispose() If unsupportedVideo then msgbox("This video resolution isn't supported by the camera - please choose a different resolution.") Else Throw End If End Try End Sub ' <summary> release everything. </summary> Public Sub Dispose() Implements IDisposable.Dispose CloseInterfaces() If (Not m_Bitmap Is Nothing) Then m_Bitmap.UnlockBits(m_bmdLogo) m_Bitmap = Nothing m_bmdLogo = Nothing End If End Sub Protected Overloads Overrides Sub finalize() CloseInterfaces() End Sub ' <summary> capture the next image </summary> Public Sub Start() If (m_bRunning = False) Then Dim hr As Integer = m_mediaCtrl.Run() DsError.ThrowExceptionForHR(hr) m_bRunning = True End If End Sub ' Pause the capture graph. ' Running the graph takes up a lot of resources. Pause it when it ' isn't needed. Public Sub Pause() If (m_bRunning) Then Dim hr As Integer = m_mediaCtrl.Pause() DsError.ThrowExceptionForHR(hr) m_bRunning = False End If End Sub 'Added by jk Public Sub TakePicture() m_takePicture=True End Sub ' <summary> Specify the logo file to write onto each frame </summary> Public Sub SetLogo(ByVal fileName As String) SyncLock Me If (fileName.Length > 0) Then m_Bitmap = New Bitmap(fileName) Dim r As Rectangle = New Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height) m_bmdLogo = m_Bitmap.LockBits(r, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb) Else If Not m_Bitmap Is Nothing Then m_Bitmap.UnlockBits(m_bmdLogo) m_Bitmap = Nothing m_bmdLogo = Nothing End If End If End SyncLock End Sub ' <summary> build the capture graph for grabber. </summary> Private Sub SetupGraph(ByVal dev As DsDevice, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer) Dim hr As Integer Dim baseGrabFlt As IBaseFilter = Nothing Dim capFilter As IBaseFilter = Nothing Dim muxFilter As IBaseFilter = Nothing Dim fileWriterFilter As IFileSinkFilter = Nothing Dim capGraph As ICaptureGraphBuilder2 = Nothing Dim sampGrabberSnap As ISampleGrabber = Nothing ' Get the graphbuilder object m_graphBuilder = DirectCast(New FilterGraph(), IFilterGraph2) m_mediaCtrl = DirectCast(m_graphBuilder, IMediaControl) 'if taking a picture (a still snapshot), then remove the videowindow If not m_takePicture then mediaEventEx = DirectCast(m_graphBuilder, IMediaEventEx) videoWindow = DirectCast(m_graphBuilder, IVideoWindow) Else mediaEventEx = Nothing videoWindow = Nothing End If #If Debug Then m_rot = New DsROTEntry(m_graphBuilder) #End If Try ' Get the ICaptureGraphBuilder2 capGraph = DirectCast(New CaptureGraphBuilder2(), ICaptureGraphBuilder2) ' Get the SampleGrabber interface sampGrabber = DirectCast(New SampleGrabber(), ISampleGrabber) sampGrabberSnap = DirectCast(New SampleGrabber(), ISampleGrabber) ' Start building the graph hr = capGraph.SetFiltergraph(DirectCast(m_graphBuilder, IGraphBuilder)) DsError.ThrowExceptionForHR(hr) ' Add the video device hr = m_graphBuilder.AddSourceFilterForMoniker(dev.Mon, Nothing, dev.Name, capFilter) DsError.ThrowExceptionForHR(hr) baseGrabFlt = DirectCast(sampGrabber, IBaseFilter) ConfigureSampleGrabber(sampGrabber) ' Add the frame grabber to the graph hr = m_graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber") DsError.ThrowExceptionForHR(hr) ' If any of the default config items are set If (iFrameRate + iHeight + iWidth > 0) Then SetConfigParms(capGraph, capFilter, iFrameRate, iWidth, iHeight) End If hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capFilter, baseGrabFlt, muxFilter) DsError.ThrowExceptionForHR(hr) 'if you set the m_takePicture it won't If Not m_takePicture then 'Set the output of the preview hr = mediaEventEx.SetNotifyWindow(UseHand, WMGraphNotify, IntPtr.Zero) DsError.ThrowExceptionForHR(hr) 'Set Owner to Display Video hr = videoWindow.put_Owner(UseHand) DsError.ThrowExceptionForHR(hr) 'Set window location - this was necessary so that the video didn't move down and to the right when you pushed the start/stop button hr = videoWindow.SetWindowPosition(0, 0, my.Settings.previewwidth, my.Settings.previewHeight) DsError.ThrowExceptionForHR(hr) 'Set Owner Video Style hr = videoWindow.put_WindowStyle(WindowStyle.Child) DsError.ThrowExceptionForHR(hr) End If SaveSizeInfo(sampGrabber) Finally If (Not fileWriterFilter Is Nothing) Then Marshal.ReleaseComObject(fileWriterFilter) fileWriterFilter = Nothing End If If (Not muxFilter Is Nothing) Then Marshal.ReleaseComObject(muxFilter) muxFilter = Nothing End If If (Not capFilter Is Nothing) Then Marshal.ReleaseComObject(capFilter) capFilter = Nothing End If If (Not sampGrabber Is Nothing) Then Marshal.ReleaseComObject(sampGrabber) sampGrabber = Nothing End If End Try End Sub ' <summary> Read and store the properties </summary> Private Sub SaveSizeInfo(ByVal sampGrabber As ISampleGrabber) Dim hr As Integer ' Get the media type from the SampleGrabber Dim media As AMMediaType = New AMMediaType() hr = sampGrabber.GetConnectedMediaType(media) DsError.ThrowExceptionForHR(hr) If (Not (media.formatType.Equals(FormatType.VideoInfo)) AndAlso Not (media.formatPtr.Equals(IntPtr.Zero))) Then Throw New NotSupportedException("Unknown Grabber Media Format") End If ' Grab the size info Dim vInfoHeader As VideoInfoHeader = New VideoInfoHeader() Marshal.PtrToStructure(media.formatPtr, vInfoHeader) m_videoWidth = vInfoHeader.BmiHeader.Width m_videoHeight = vInfoHeader.BmiHeader.Height m_stride = m_videoWidth * (vInfoHeader.BmiHeader.BitCount / 8) DsUtils.FreeAMMediaType(media) media = Nothing End Sub ' <summary> Set the options on the sample grabber </summary> Private Sub ConfigureSampleGrabber(ByVal sampGrabber As ISampleGrabber) Dim hr As Integer Dim media As AMMediaType = New AMMediaType() media.majorType = MediaType.Video media.subType = MediaSubType.RGB24 media.formatType = FormatType.VideoInfo hr = sampGrabber.SetMediaType(media) DsError.ThrowExceptionForHR(hr) DsUtils.FreeAMMediaType(media) media = Nothing ' Configure the samplegrabber callback hr = sampGrabber.SetOneShot(false) DsError.ThrowExceptionForHR(hr) If m_takePicture then hr = sampGrabber.SetCallback(Me, 0) Else hr = sampGrabber.SetCallback(Me, 0) End If DsError.ThrowExceptionForHR(hr) DsError.ThrowExceptionForHR(hr) 'set the samplegrabber sampGrabber.SetBufferSamples(False) End Sub ' Set the Framerate, and video size Private Sub SetConfigParms(ByVal capGraph As ICaptureGraphBuilder2, ByVal capFilter As IBaseFilter, ByVal iFrameRate As Integer, ByVal iWidth As Integer, ByVal iHeight As Integer) Dim hr As Integer Dim o As Object = Nothing Dim media As AMMediaType = Nothing Dim videoStreamConfig As IAMStreamConfig Dim videoControl As IAMVideoControl = DirectCast(capFilter, IAMVideoControl) ' Find the stream config interface hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, GetType(IAMStreamConfig).GUID, o) videoStreamConfig = DirectCast(o, IAMStreamConfig) Try If (videoStreamConfig Is Nothing) Then Throw New Exception("Failed to get IAMStreamConfig") End If ' Get the existing format block hr = videoStreamConfig.GetFormat(media) DsError.ThrowExceptionForHR(hr) ' copy out the videoinfoheader Dim v As VideoInfoHeader = New VideoInfoHeader() Marshal.PtrToStructure(media.formatPtr, v) ' if overriding the framerate, set the frame rate If (iFrameRate > 0) Then v.AvgTimePerFrame = 10000000 / iFrameRate End If ' if overriding the width, set the width If (iWidth > 0) Then v.BmiHeader.Width = iWidth End If ' if overriding the Height, set the Height If (iHeight > 0) Then v.BmiHeader.Height = iHeight End If ' Copy the media structure back Marshal.StructureToPtr(v, media.formatPtr, False) ' Set the new format hr = videoStreamConfig.SetFormat(media) If hr<>0 then unsupportedVideo = True else unsupportedVideo=False DsError.ThrowExceptionForHR(hr) DsUtils.FreeAMMediaType(media) media = Nothing ' Fix upsidedown video If (Not videoControl Is Nothing) Then Dim pCapsFlags As VideoControlFlags Dim pPin As IPin = DsFindPin.ByCategory(capFilter, PinCategory.Capture, 0) hr = videoControl.GetCaps(pPin, pCapsFlags) DsError.ThrowExceptionForHR(hr) If ((pCapsFlags & VideoControlFlags.FlipVertical) > 0) Then hr = videoControl.GetMode(pPin, pCapsFlags) DsError.ThrowExceptionForHR(hr) hr = videoControl.SetMode(pPin, 0) End If End If Finally Marshal.ReleaseComObject(videoStreamConfig) End Try End Sub ' <summary> Shut down capture </summary> Private Sub CloseInterfaces() Dim hr As Integer Try If (Not m_mediaCtrl Is Nothing) Then ' Stop the graph hr = m_mediaCtrl.Stop() m_mediaCtrl = Nothing m_bRunning = False 'Release Window Handle, Reset back to Normal hr = videoWindow.put_Visible(OABool.False) DsError.ThrowExceptionForHR(hr) hr = videoWindow.put_Owner(IntPtr.Zero) DsError.ThrowExceptionForHR(hr) If mediaEventEx Is Nothing = False Then hr = mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero) DsError.ThrowExceptionForHR(hr) End If End If Catch ex As Exception Debug.WriteLine(ex) End Try #If Debug Then If (Not m_rot Is Nothing) Then m_rot.Dispose() m_rot = Nothing End If #End If If (Not m_graphBuilder Is Nothing) Then Marshal.ReleaseComObject(m_graphBuilder) m_graphBuilder = Nothing End If GC.Collect() End Sub ' <summary> sample callback, Originally not used - call this with integer 0 on the setcallback method </summary> Function SampleCB(ByVal SampleTime As Double, ByVal pSample As IMediaSample) As Integer Implements ISampleGrabberCB.SampleCB myTest = "In SampleCB" Dim i As Integer=0 'jk added this code 10-22-13 if IsDBNull(pSample) =True then return -1 dim myLen As Integer = pSample.GetActualDataLength() dim pbuf As IntPtr if pSample.GetPointer(pbuf) = 0 AND mylen > 0 then dim buf As byte()= new byte(myLen) {} Marshal.Copy(pbuf, buf, 0, myLen) 'Alter the video - you could use this to adjust the brightness/red/green, etc. 'for i = myLen-1 to 0 step -1 ' buf(i) = (255 - buf(i)) 'Next i If m_takePicture then Dim bm As new Bitmap(m_videoWidth,m_videoHeight,Imaging.PixelFormat.Format24bppRgb) Dim g_RowSizeBytes As Integer Dim g_PixBytes() As Byte mytest = "Execution point #1" Dim m_BitmapData As BitmapData = Nothing Dim bounds As Rectangle = New Rectangle(0, 0, m_videoWidth, m_videoHeight) mytest = "Execution point #2" m_BitmapData = bm.LockBits(bounds, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format24bppRgb) mytest = "Execution point #4" g_RowSizeBytes = m_BitmapData.Stride mytest = "Execution point #5" ' Allocate room for the data. Dim total_size As Integer = m_BitmapData.Stride * m_BitmapData.Height ReDim g_PixBytes(total_size) mytest = "Execution point #10" 'this writes the data to the Bitmap Marshal.Copy(buf, 0, m_BitmapData.Scan0, mylen) capturedPic=bm mytest = "Execution point #15" ' Release resources. bm.UnlockBits(m_BitmapData) g_PixBytes = Nothing m_BitmapData = Nothing bm=Nothing buf=Nothing m_takePicture=False captureSaved = True mytest = "Execution point #20" End If End If Marshal.ReleaseComObject(pSample) Return 0 End Function ' <summary> buffer callback, Not used - call this with integer 1 on the setcallback method </summary> Function BufferCB(ByVal SampleTime As Double, ByVal pBuffer As IntPtr, ByVal BufferLen As Integer) As Integer Implements ISampleGrabberCB.BufferCB SyncLock Me myTest = "In BufferCB" End SyncLock return 0 End Function End Class I'm sure this could be improved upon, but it works well for my purposes for now, and I hope it helps someone.
{ "pile_set_name": "StackExchange" }
Q: Countdown time for multi row I am working on a countdown time for multiple row using map reactjs I did countdown for 1 hour but I have no idea how to do this for multiple rows here's my code class Example extends React.Component { constructor() { super(); this.state = { time: {}, seconds: 3600, data: [ { "id": 1, "car": 'Audi 2018' } ] }; this.timer = 0; this.startTimer = this.startTimer.bind(this); this.countDown = this.countDown.bind(this); } secondsToTime(secs){ let hours = Math.floor(secs / (60 * 60)); let divisor_for_minutes = secs % (60 * 60); let minutes = Math.floor(divisor_for_minutes / 60); let divisor_for_seconds = divisor_for_minutes % 60; let seconds = Math.ceil(divisor_for_seconds); let obj = { "h": hours, "m": minutes, "s": seconds }; return obj; } componentDidMount() { let timeLeftVar = this.secondsToTime(this.state.seconds); this.setState({ time: timeLeftVar }); this.startTimer() } startTimer() { if (this.timer == 0) { this.timer = setInterval(this.countDown, 1000); } } countDown() { // Remove one second, set state so a re-render happens. let seconds = this.state.seconds - 1; this.setState({ time: this.secondsToTime(seconds), seconds: seconds, }); // Check if we're at zero. if (seconds == 0) { clearInterval(this.timer); } } addCar = () =>{ this.setState(prevState=>({ data: [...prevState.data, { "id": 2, "car": 'New Car' }] })) } render() { return ( <div> {this.state.data.map(row=> <ul key={row.id}> <li>car {row.car} <b>Finish:</b>h: {this.state.time.h} m: {this.state.time.m} s: {this.state.time.s}</li> </ul> )} <button onClick={this.addCar}>Add Car</button> </div> ); } } ReactDOM.render(<Example/>, document.getElementById('View')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="View"></div> the code only shows for one row not all the rows A: You need to extenalise your inner component with his own state: class MyComponent extends Component { constructor(props) { super(props); this.state = { time: {}, seconds: 3600 }; this.timer = 0; this.startTimer = this.startTimer.bind(this); this.countDown = this.countDown.bind(this); } secondsToTime(secs){ let hours = Math.floor(secs / (60 * 60)); let divisor_for_minutes = secs % (60 * 60); let minutes = Math.floor(divisor_for_minutes / 60); let divisor_for_seconds = divisor_for_minutes % 60; let seconds = Math.ceil(divisor_for_seconds); let obj = { "h": hours, "m": minutes, "s": seconds }; return obj; } componentDidMount() { let timeLeftVar = this.secondsToTime(this.state.seconds); this.setState({ time: timeLeftVar }); this.startTimer() } startTimer() { if (this.timer == 0) { this.timer = setInterval(this.countDown, 1000); } } countDown() { // Remove one second, set state so a re-render happens. let seconds = this.state.seconds - 1; this.setState({ time: this.secondsToTime(seconds), seconds: seconds, }); // Check if we're at zero. if (seconds == 0) { clearInterval(this.timer); } } render() { return ( <div>car {this.props.data.car} <b>Finish:</b>h: {this.state.time.h} m: {this.state.time.m} s: {this.state.time.s} ); } } class Example extends React.Component { constructor(props) { super(props); this.state = {data: [{ "id": 1, "car": 'Audi 2018' }]}; } addCar = () =>{ this.setState(prevState=>({ data: [...prevState.data, { "id": 2, "car": 'New Car' }] })) } render() { return ( <div> <ul> {this.state.data.map(row => <MyComponent data={row} key={row.id}/>)} </ul> <button onClick={this.addCar}>Add Car</button> </div> ); } }
{ "pile_set_name": "StackExchange" }
Q: Unity: How to ensure singleton instances for stateful classes across instances of the UnityContainer class? The application I'm working on requires objects to be created on the fly, some of them also use singleton instances (lifetime manager based, of course), because there is state involved (think WCF service sessions, etc...). As long as I resolve via the same instance of the UnityContainer class, everything is fine, but I think here the snake is biting into it's own tail: a) Everyone hates the most intuitive idea of providing a single instance of the UnityContainer - class b) At the same time this seems to be the only logical solution I mean, seriously, if there is so much hate for the ServiceLocator - pattern, what else do you suggest then? Edit: Ok, I found a very good solution. The UnityContainer - class can inject itself as a singleton. Here is an example (it's written in a very ugly style, but it proves my point): static void Main(string[] args) { var container = new UnityContainer().LoadConfiguration(); var test = container.Resolve<MyDependant>(); test.TestTheDependency(); foreach (var registration in container.Registrations) { Console.WriteLine(registration.RegisteredType.Name); } var container2 = container.Resolve<IUnityContainer>(); Console.WriteLine(container.GetHashCode()); Console.WriteLine(container2.GetHashCode()); test.ShowUnityContainerHashCode(); var testD1 = container.Resolve<ITestDependency>(); var testD2 = container2.Resolve<ITestDependency>(); Console.WriteLine(testD1.GetHashCode()); Console.WriteLine(testD2.GetHashCode()); test.ShowTestDependencyHashCode(); } Shows 2 blocks á 3 times the same hash code if <register type="ITestDependency" mapTo="TestDependency"> <lifetime type="singleton"/> </register> <register type="MyDependant" /> is set in app.config. Very nice. I love Unity, seriously. This is hot stuff. A: If you truly must share the same instance between multiple UnityContainer instances, the best solution might be to simply resolve it once and subsequently register the instance in all other UnityContainer instances: var f = container1.Resolve<IFoo>(); // .. container42.RegisterInstance<IFoo>(f); // .. Another alternative that presents itself is to make the implementation a true Singleton, but still register the instance in every container instance. That makes it an implementation detail that there's a Singleton in play, and it removes many of the disadvantages of the Singleton pattern because consumers will never know about it. However, the best solution is to use only a single container. Although I can think of a few, rather exotic, scenarios where an arbitrary number of container instances are appropriate, in the vast majority of cases, a single container instance is the correct configuration.
{ "pile_set_name": "StackExchange" }
Q: visible videos only have to play like Facebook on website I found the JavaScript code in net for playing the video when it's visible other videos should pause, but this code when i go to the page all video it's pause but i august the scroll it's playing all videos, i'll submit that code down and i'm fetch the videos from database and through the while loop i'm getting all videos. Anyone help me fix this issues and tell me the better solution for this. <script> var videos = document.getElementsByClassName('embed-responsive-item'); function checkScroll() { for(var i = 0; i < videos.length; i++) { var video = videos[i]; //alert(video); var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right b = y + h, //bottom visibleX, visibleY, visible; visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset)); visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset)); visible = visibleX * visibleY / (w * h); fraction = 1; //alert(visible); if (visible > fraction) { //alert(visible); video.pause(); } else { video.play(); } } } window.addEventListener('scroll', checkScroll, false); window.addEventListener('resize', checkScroll, false); </script> <?php while($getSharePer01=mysqli_fetch_assoc($getPostStatus01)){ extract($getSharePer01); ?> <video id="sampleMovie" class="embed-responsive-item" height="500" preload controls> <source src="<?php echo $u_pvid; ?>" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'/> <object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" width="640" height="360"> <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" /> <param name="allowFullScreen" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value='config={"clip":{"url":"HTML5Sample_flv.flv","autoPlay":false,"autoBuffering":true}}' /> </object> </video> <?php } ?> A: This is the solution for this question <script> $(document).ready(function() { // Get media - with autoplay disabled (audio or video) var media = $('video').not("[autoplay='autoplay']"); var tolerancePixel = 20; function checkMedia(){ // Get current browser top and bottom var scrollTop = $(window).scrollTop() + tolerancePixel; var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel; media.each(function(index, el) { var yTopMedia = $(this).offset().top; var yBottomMedia = $(this).height() + yTopMedia; if(scrollTop < yBottomMedia && scrollBottom > yTopMedia){ //view explaination in `In brief` section above $(this).get(0).play(); } else { $(this).get(0).pause(); } }); //} } $(document).on('scroll', checkMedia); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Problems after deactivation TLS 1.0 on IIS 6 (Windows Server 2008r2) Deactivated the TLS 1.0 on our webserver to use TLS 1.2. After that the website does have problems, when it comes to the transaction. I tried different things like Installed all pending Windows Updates Upgraded IIS 6 to version 7 Recompiled the whole project as 4.5 and re-imported it in IIS Deactivated the .NET 3 feature in the IIS Updating all Project target Frameworks to 4.5 Controlled Application pool and set it to v4.0 (it should use 4.5) First it seems like a problem with the application. But then I tried the project in debug mode in VS and everything worked? Compared to the server which falls back to SSL3 instead of using TLS 1.1 or TLS 1.2. (It seems like there is missing some feature and the by Technet named registry keys are not enough.) I think the problem could be the use of some classes like (HttpApplication.cs) System.Web System.Web.Security Because of the lack of experience I came to the conclusion to ask you about the problem. Do you maybe have any more ideas? Some other things just came into mind: There was one Project in the VS which used .NET 4.0. I changed the target framework and then the project does have problems to find some namespace. (all project does have the same target framework (.Net) at this time). The namespaces did exist but VS wasn't able to find it. So I rebuild, cleaned the solution but it didn't help. Then I closed VS and re-opened it. Suddenly the project did work. The framework is 4.0 in the properties. (Maybe this could be a problem too?) Since I am under pressure of time, I am grateful for any help. EDIT: Is there maybe an easy way to test things out (TLS test) and displaying the used .Net version? EDIT2: Found a solution to test out the framework with a nuget package. http://haacked.com/archive/2010/12/05/asp-net-mvc-diagnostics-using-nuget.aspx/ (will try that later) I also managed to step through the breakpoints with remote debugging and found where the failure happens. There is a file "References.cs" with this head: //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18034 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.18034. // #pragma warning disable 1591 where this code creates the problem: /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace="http://....", ResponseNamespace="http://....", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlElementAttribute("out", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public PaymentResult SelectPayment([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] uint merchantID, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string mdxi, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string getDataURL, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string tid) { object[] results = this.Invoke("SelectPayment", new object[] { merchantID, mdxi, getDataURL, tid}); return ((PaymentResult)(results[0])); } The object "results" never get a value. I pressed F1 to see what the Invoke is doing and this site opens: https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke);k(SolutionItemsProject);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true EDIT3: It seems like the Invoke is the reference System.Web.Services But in the project the version is Runtime Version: v4.0.30319 Version: 4.0.0.0 I think this is the problem because it should be 4.5... System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream. A: I finally was able to fix the problem. What I did was adding some try-catch before the return of the method try { result = SelectPayment(...); } catch (System.Web.Services.Protocols.SoapException e) { Logger.Error("[SelectPayment]: Can't Invoke XML Web service method synchronisly using " + e); } catch (System.InvalidOperationException e) { Logger.Error("[SelectPayment]: Can't Invoke XML Web service method synchronisly using " + e); } return result; to see the exact error message System.IO.IOException: Authentication failed because the remote party has closed the transport stream. that was described in Authentication failed because remote party has closed the transport stream Then I added this line before the HTTP Soap Invoke (before the try of SelectPayment) in the code: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; And finally after hours the program did work! :) It seems like the Runtime Version: v4.0.30319 Version: 4.0.0.0 is using always the TLS 1.0 on default, if you don't tell them to use TLS 1.2. Imported info for IIS6 from this site https://forums.iis.net/t/1189663.aspx?TLS+1+1+or+1+2+on+IIS6+Win2003+ IIS 7.5 (Windows 7 and Windows server 2008 R2) are the only web servers on MS platforms which supports TLS 1.1 and TLS 1.2.
{ "pile_set_name": "StackExchange" }
Q: Can "whatever" be split into two words? I tend to write, "say whatever they want", but I'm always tempted to write "say what ever they want". Is it acceptable to split the word in this context? A: No it is not acceptable to split the word in your context: say whatever they want Here, whatever is a relative pronoun and it is always written as one word. The only instance where one will find what ever is in the interrogative. For example: What ever does he want? What ever does she do besides complain? In these cases, ever (an adverb) modifies the pronoun what and, as such, it cannot and should not be compounded with what. However, one could also have whatever as an interrogative pronoun: Whatever's wrong with you? And, finally, whatever, as an adjective, can be used in the following manner: Run whatever distance you can. I'll take whatever solution you've got.
{ "pile_set_name": "StackExchange" }
Q: Spaces between elements in RPN expression java I have a method getRPNString(), which returns Reverse Polish Notation string. I want to split this string by spacebars to calculate it. Now I can't understand how to add spacebars in my RNP string right, because it's not working with two digits numbers. public class Calc1 { public static void main(String[] args) { String in = "((5+3*(4+2)*12)+3)/(1+3)+5"; String out = getRPNString(in); System.out.println(out); } private static String getRPNString(String in) { LinkedList<Character> oplist = new LinkedList<>(); StringBuilder out = new StringBuilder(); for (int i = 0; i < in.length(); i++) { char op = in.charAt(i); if (op == ')') { while (oplist.getLast() != '(') { out.append(oplist.removeLast()); } oplist.removeLast(); } if (Character.isDigit(op)) { out.append(op); /*int j = i + 1; for (; j < in.length(); j++) { if (!Character.isDigit(j)) { break; } i++; } out.append(in.substring(i, j));*/ } if (op == '(') { oplist.add(op); } if (isOperator(op)) { if (oplist.isEmpty()) { oplist.add(op); } else { int priority = getPriority(op); if (priority > getPriority(oplist.getLast())) { oplist.add(op); } else { while (!oplist.isEmpty() && priority <= getPriority(oplist.getLast())) { out.append(oplist.removeLast()); } oplist.add(op); } } } } while (!oplist.isEmpty()) { out.append(oplist.removeLast()); } return out.toString(); } private static boolean isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; } private static int getPriority(char op) { switch (op) { case '*': case '/': return 3; case '+': case '-': return 2; case '(': return 1; default: return -1; } } } I tried to add spacebars by append(' ') in my StringBuilder variable out. But it' s not right with two digits. I think I totally do not understand how to make it. For example if input is String in = "((5+3*(4+2)*12)+3)/(1+3)+5"; the out will be 5342+12+3+13+/5+, when I add spacebars to all calls out.append(' ')**out is **5 3 4 2 + * 1 2 * + 3 + 1 3 + / 5 +, so numbers like "12" became "1 2". Can you help? A: Just change the code that you have commented out, right after Character.isDigit(op) to: int j = i + 1; int oldI = i;//this is so you save the old value for (; j < in.length(); j++) { if (!Character.isDigit(in.charAt(j))) { break; } i++; } out.append(in.substring(oldI, j)); out.append(' ');
{ "pile_set_name": "StackExchange" }
Q: Widget Update problems using a for loop I try to develop a widget which enabels the functionality of creating tables. It is important that the user can determine how many columns and lines he wants. I already managed to generate a user-specific amount of input fields in the backend. My problem is that I am not able to save the content from the input fields. For that I am using a for-loop within the update method. I hope someone can guide me into the right direction. Tank you very much! My Code: class table_widget extends WP_Widget { function __construct() { $widget_ops = array( 'classname' => 'table_det_widget', 'description' => 'Tabelle erstellen', ); parent:: __construct(false, $name = __('Tabelle'), $widget_ops); } function form($instance) { /*Ausgabe im Backend*/ echo '<label for="' . $this->get_field_id('wp_table_title') . '">Überschrift: </label>'; echo '<input class="widefat" type="text" value="' . $instance['wp_table_title'] .'" name="' . $this->get_field_name('wp_table_title') . '" id="' . $this->get_field_id('wp_table_title') . '" >'; echo '<label for="' . $this->get_field_id('wp_table_subtitle') . '">Unterüberschrift: </label>'; echo '<input class="widefat" type="text" value="' . $instance['wp_table_subtitle'] .'" name="' . $this->get_field_name('wp_table_subtitle') . '" id="' . $this->get_field_id('wp_table_subtitle') . '" >'; echo '<label for="' . $this->get_field_id('wp_column') . '">Spalten: </label>'; echo '<input class="widefat" type="text" value="' . $instance['wp_column'] .'" name="' . $this->get_field_name('wp_column') . '" id="' . $this->get_field_id('wp_column') . '" >'; echo '<label for="' . $this->get_field_id('wp_line') . '">Zeilen pro Spalte: </label>'; echo '<input class="widefat" type="text" value="' . $instance['wp_line'] .'" name="' . $this->get_field_name('wp_line') . '" id="' . $this->get_field_id('wp_line') . '" >'; if($instance['wp_column'] == '' || $instance['wp_line'] == '') { echo 'Bitte beide Felder ausfüllen!'; } else { $spalten = $instance['wp_column']; $zeilen = $instance['wp_line']; for ($i = 1; $i <= $zeilen; $i++) { echo "<label style='display: block; margin-top: 10px;'>Zeile {$i}</label>"; for ($j = 1; $j <= $spalten; $j++) { $instSpecLine = $instance["spec_line_{$i}_{$j}"]; echo "<input class='widefat' type='text' value='{$instSpecLine}' name='{$instSpecLine}' id='{$instSpecLine}' placeholder='Spalte {$j}' >"; } $j = 0; } } } function update($new_instance, $old_instance) { $instance = $old_instance; $instance['wp_table_title'] = $new_instance['wp_table_title']; $instance['wp_table_subtitle'] = $new_instance['wp_table_subtitle']; $instance['wp_line'] = $new_instance['wp_line']; $instance['wp_column'] = $new_instance['wp_column']; $spalten = $instance['wp_column']; $zeilen = $instance['wp_line']; for ($i = 1; $i <= $zeilen; $i++) { for ($j = 1; $j <= $spalten; $j++) { $instSpecLine = "spec_line_{$i}_{$j}"; $instance[$instSpecLine] = $new_instance[$instSpecLine]; } } return $instance; } A: Please replace below line: echo "<input class='widefat' type='text' value='{$instSpecLine}' name='{$instSpecLine}' id='{$instSpecLine}' placeholder='Spalte {$j}' >"; With Below code: echo "<input class='widefat' type='text' value='{$instSpecLine}' name='".$this->get_field_name("spec_line_{$i}_{$j}")."' id='{$instSpecLine}' placeholder='Spalte {$j}' >"; Hope this will help you
{ "pile_set_name": "StackExchange" }
Q: Get values from collection in one module into combobox in userform I have a worksheet with data in column 'EGM'. My code saves values from this column in the collection. If there is only one value in the collection, then variable sSelectedEGM is equal to this value. But if there is more than one values, a user should has possibility to choose only one value (I wanted to do this in the combobox) and save selected item into variable sSelectedEGM. My problem is, that I can't get values from this collection into userform. When my code go into useform, the error "Type mismatch" appear. My code in worksheet: Public sSelectedEGM As String Public vElement As Variant Public cEGMList As New VBA.Collection Sub kolekcjaproba() ' =================================== ' LOOP THROUGH EGMS AND WRITE THEM INTO COLLECTION ' =================================== Dim iOpenedFileFirstEGMRow As Integer Dim iOpenedFileLastEGMRow As Integer Dim iOpenedFileEGMColumn As Integer Dim iOpenedFileEGMRow As Integer Dim sOpenedFileEGMName As String Dim ws As Worksheet Dim wb As Workbook Set wb = ThisWorkbook Set ws = wb.Worksheets(1) iOpenedFileFirstEGMRow = Cells.Find("EGM").Offset(1, 0).Row iOpenedFileLastEGMRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, iOpenedFileFirstEGMRow).End(xlUp).Row iOpenedFileEGMColumn = Cells.Find("EGM").Column For iOpenedFileEGMRow = iOpenedFileFirstEGMRow To iOpenedFileLastEGMRow sOpenedFileEGMName = Cells(iOpenedFileEGMRow, iOpenedFileEGMColumn).Value For Each vElement In cEGMList If vElement = sOpenedFileEGMName Then GoTo NextEGM End If Next vElement cEGMList.Add sOpenedFileEGMName NextEGM: Next If cEGMList.Count = 1 Then sSelectedEGM = cEGMList.Item(1) ElseIf cEGMList.Count = 0 Then MsgBox "No EGM found" Else Load UserForm1 UserForm1.Show End If End Sub And my code in a userform (There is only a combobox on it) Private Sub UserForm_Initialize() For Each vElement In cEGMList UserForm1.ComboBox1.AddItem vElement Next vElement End Sub Private Sub ComboBox1_Change() If ComboBox1.ListIndex <> -1 Then sSelectedEGM = ComboBox1.List(ComboBox1.ListIndex) End If End Sub A: you have to declare cEGMList and sSelectedEGM in a standard module as public and not in a worksheet module. Or even better: create a property on the form for the collection and for the returned values. It's always better to avoid global vars wherever possible. This is a simplified example. In the form you can define properties and methods like that: Option Explicit Public TestProperty As Integer Public Sub TestMethod() MsgBox (TestProperty) End Sub Public Function TestMethodWithReturn() As Integer TestMethodWithReturn = TestProperty * 2 End Function outside the form you can then use this as a normal property/method of the form: Private Sub Test() Dim retValue As Integer UserForm1.TestProperty = 123 UserForm1.Show vbModeless UserForm1.TestMethod retValue = UserForm1.TestMethodWithReturn Debug.Print retValue End Sub
{ "pile_set_name": "StackExchange" }
Q: Taxi Cab Geometry: Correct way to describe the discrepancy between "stair step" & diagonal lines? The taxi-cab geometry problem is described here: https://www.intmath.com/blog/mathematics/taxicab-geometry-4941 In what way is a diagonal line different than a zig-zag line following its path as described in taxi-cab-geometry? Is a diagonal line considered to be "off grid", in another dimension? What is an accurate way to describe the difference/relationship? In the above image all the total length of the zig-zag line is equal to $CA+AB$ The diagonal is equal to $\sqrt{CA^2 + AB^2}$ You can approximate the irrational number $pi$ like so: But the same does the apply the first example. In what way are these two examples different? Both start off with apparent low-resolution approximations, but one does approximate an irrational number while the other does not? A: It means that any method you use to try to formalize the idea of how curves can vary and relate to one another will satisfy one (or both!) of the following two properties: Stairsteps do not converge to the diagonal Length is not a continuous function on curves For example, one of the things we might want to insist on for convergence is for both points and slopes to converge, rather than just points. Clearly, the slope of the stairsteps does not converge to the slope of the diagonal, since the former are always (when defined) in the set $\{ 0, \infty \}$, but the slopes of the latter are always $1$.
{ "pile_set_name": "StackExchange" }
Q: Apple Mach-O Linker errors and I have no idea what to do I'm following a nextpeer guidelines for integrating nextpeer in cocos2d-x with c++, i have copied the required frameworks and classes in project, then added the required frameworks for nextpeer, also add the linker flags but there are Apple Mach-O linker errors, here is a log: Undefined symbols for architecture i386: "_CTFontCopyFullName", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextBold:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFontCreateCopyWithAttributes", referenced from: ___NP_NSAttributedStringByScalingFontSize_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) "_CTFontCreateCopyWithSymbolicTraits", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextBold:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFontCreateUIFontForLanguage", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextBold:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFontCreateWithFontDescriptor", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFontCreateWithName", referenced from: _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontName:size:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFontDescriptorCreateWithAttributes", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFontGetSize", referenced from: ___39+[NP_OHASBasicMarkupParser tagMappings]_block_invoke_3 in Nextpeer(NP_OHASBasicMarkupParser.o) ___NP_NSAttributedStringByScalingFontSize_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) "_CTFontGetSymbolicTraits", referenced from: -[NSAttributedString(NP_OHCommodityConstructors) npTextIsBoldAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFrameGetLineOrigins", referenced from: -[NP_TTTAttributedLabel characterIndexAtPoint:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTFrameGetLines", referenced from: -[NP_TTTAttributedLabel characterIndexAtPoint:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel sizeThatFits:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTFramesetterCreateFrame", referenced from: -[NP_TTTAttributedLabel characterIndexAtPoint:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel sizeThatFits:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTFramesetterCreateWithAttributedString", referenced from: -[NP_TTTAttributedLabel framesetter] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawTextInRect:] in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npSizeConstrainedToSize:fitRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTFramesetterSuggestFrameSizeWithConstraints", referenced from: -[NP_TTTAttributedLabel textRectForBounds:limitedToNumberOfLines:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel sizeThatFits:] in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npSizeConstrainedToSize:fitRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTLineCreateTruncatedLine", referenced from: -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTLineCreateWithAttributedString", referenced from: -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTLineDraw", referenced from: -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTLineGetStringIndexForPosition", referenced from: -[NP_TTTAttributedLabel characterIndexAtPoint:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTLineGetStringRange", referenced from: -[NP_TTTAttributedLabel drawFramesetter:attributedString:textRange:inRect:context:] in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel sizeThatFits:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTLineGetTypographicBounds", referenced from: -[NP_TTTAttributedLabel characterIndexAtPoint:] in Nextpeer(NP_TTTAttributedLabel.o) "_CTParagraphStyleCreate", referenced from: -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextAlignment:lineBreakMode:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_CTParagraphStyleGetValueForSpecifier", referenced from: -[NSAttributedString(NP_OHCommodityConstructors) npTextAlignmentAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSAttributedString(NP_OHCommodityConstructors) npLineBreakModeAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_kCTFontAttributeName", referenced from: _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawTextInRect:] in Nextpeer(NP_TTTAttributedLabel.o) ___NP_NSAttributedStringByScalingFontSize_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npFontAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontName:size:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextBold:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) ... _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawTextInRect:] in Nextpeer(NP_TTTAttributedLabel.o) ___NP_NSAttributedStringByScalingFontSize_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npFontAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontName:size:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextBold:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) ... "_kCTFontFamilyNameAttribute", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_kCTFontSymbolicTrait", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_kCTFontTraitsAttribute", referenced from: -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetFontFamily:size:bold:italic:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_kCTForegroundColorAttributeName", referenced from: -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawTextInRect:] in Nextpeer(NP_TTTAttributedLabel.o) ___NP_NSAttributedStringBySettingColorFromContext_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npTextColorAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextColor:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NP_TTTAttributedLabel drawTextInRect:] in Nextpeer(NP_TTTAttributedLabel.o) ___NP_NSAttributedStringBySettingColorFromContext_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npTextColorAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextColor:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_kCTForegroundColorFromContextAttributeName", referenced from: -[NP_TTTAttributedLabel renderedAttributedText] in Nextpeer(NP_TTTAttributedLabel.o) ___NP_NSAttributedStringBySettingColorFromContext_block_invoke in Nextpeer(NP_TTTAttributedLabel.o) "_kCTParagraphStyleAttributeName", referenced from: -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npTextAlignmentAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSAttributedString(NP_OHCommodityConstructors) npLineBreakModeAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextAlignment:lineBreakMode:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) _NP_NSAttributedStringAttributesFromLabel in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npTextAlignmentAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSAttributedString(NP_OHCommodityConstructors) npLineBreakModeAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextAlignment:lineBreakMode:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) "_kCTUnderlineStyleAttributeName", referenced from: -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npTextUnderlineStyleAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextUnderlineStyle:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NP_TTTAttributedLabel commonInit] in Nextpeer(NP_TTTAttributedLabel.o) -[NSAttributedString(NP_OHCommodityConstructors) npTextUnderlineStyleAtIndex:effectiveRange:] in Nextpeer(NP_NSAttributedString+Attributes.o) -[NSMutableAttributedString(NP_OHCommodityStyleModifiers) npSetTextUnderlineStyle:range:] in Nextpeer(NP_NSAttributedString+Attributes.o) ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) these are the frameworks which i've added in my project: CoreText.framework OpenGLES.framework Security.framework MobileCoreServices.framework StoreKit.framework SystemConfiguration.framework CFNetwork.framework MessageUI.framework AdSupport.framework - (**) Optional QuartzCore.framework UIKit.framework CoreGraphics.framework Foundation.framework libz.dylib libsqlite3.dylib and this is the linker flag which i have added -ObjC How Do i Fix this? please help. A: You need to link the CoreText framework into your app.
{ "pile_set_name": "StackExchange" }
Q: Why does gradle Project API return String for getParent(), when documentation says it must return Parent type? I am defining a gradle task in which I want to go to the parent directory of the current project. According to the documentation at https://docs.gradle.org/current/javadoc/org/gradle/api/Project.html, I should have been able to use getParent() property on my current project. But when I try it, it returns a String (path of the parent directory) though the documentation clearly states the method should return a Project. Why is this happening? A: Most certainly you are calling getParent() on a file/directory, or inside a closure that delegates to a java.io.File, which indeed returns String with parent folder's path. Try to call project.parent explicitly and see if it helps. ps. Actual code snippet might help as well.
{ "pile_set_name": "StackExchange" }
Q: Element is not horizontally centered in IE11 with Flexbox when parent has flex-flow: column wrap; JSFiddle Link .thing { background-color: tomato; max-width: 300px; padding: 30px; display: flex; margin: 0 auto; flex-flow: column wrap; } .not-centered { max-width: 150px; background-color: #fefefe; margin: 0 auto; } <div class="thing"> <div class="not-centered"> im not centeredi in ie11 </div> </div> I supposed it to work because if max-width and margin: 0 auto set. But as you can see, it is not horizontally centered because his parent .thing has flex-flow: column wrap. Any ideas to fix this in this setup? P.S. Works in Chrome/FF A: Wrapping .not-centered in a div with block display resolves the issue in IE11
{ "pile_set_name": "StackExchange" }
Q: Where is data written to on a hard drive after a wipe? I just used the "windows media creation tool" on a 1TB HD, and my drive was mistakenly wiped in the process. I did not read the warnings when using "windows media creation tool," so tried to use a hard drive with data, thinking that new files would just be added onto the current partition. The 1TB drive was formatted and repartitioned down to 31GB, and 4gb of windows 10 iso were written onto the drive. Where on a hard drive is data written to after a wipe? Would the files be written onto previously unused areas, or does the write location move back to the first area? A: First note that logical location (the block addresses used by the OS) doesn't always correspond to physical location (where those blocks reside on disk platters or flash memory). The disk is free to make its own decisions on how to translate between the two, as long as it remains invisible to the OS. With HDs, things like "previously unused areas" and "write location moving back" don't quite work – data is just written wherever the OS asks it to be written. That is, the same logical address (LBA) usually corresponds to the same physical location. (SSDs, on the other hand, do keep track in firmware of which locations are "in use", which have been freed (using TRIM), etc. so if the OS writes twice to the same logical address, it will probably (I think?) get a different physical area every time.) The logical location is constrained by the partitions. If the app has set up a 32 GB partition that starts at the beginning of the disk, then new files were written only within those first 32 GB, and the rest of the terabyte should remain untouched. (A real disk wipe tool would have erased the whole disk, but that's not what the Media Creation Tool does – it only cares about writing as much as it actually needs.) Space inside the partition, however, is managed by the filesystem's allocation algorithm (which usually picks varying locations in order to avoid fragmentation), so new data could've been written nearly anywhere within those 32 GB.
{ "pile_set_name": "StackExchange" }
Q: Button Inside Android ListView doesnt respond to clicks I have a default ListView that i have added my custom views for the list items, but the buttons inside of these views are not clickable most of the time. I output a Log.v when the button receives a click event, but i have to tap the button almost a dozen times before it will register the click. The other problem related tot his that i am having is that when the button is pressed i want an animation to happen revealing a menu sliding out from beneath it. At the moment i have tried several different methods like making a custom class for the views versus just using a layout inflater to get the relativeLayout object for the view, but nothing is working properly. I have even tried using listview.getAdapter().notifyDataSetChanged(); but that only has a pop-into-place for the extended view when i want an animation. I have searched everywhere and it seems like the only possible solutions are to either rewrite my own custom listview or to use a linearlayout with a scrollview. The latter seems easier but i dont think it is nearly as optimized as the listview is. Any suggestions would be greatly appreciated, if you need to see some code, please let me know... Thanks! UPDATE: the getView() contains this: Holder hold; convertView = friends.get(position); hold = new Holder(); hold.pos = position; convertView.setTag(hold); return convertView; basically i pass an ArrayList<RelativeLayout>, at the moment, to the Adapter so that i dont have to create a new view each time and so that the animation will stay animated when i scroll down... inside the OnCreate() for this activity i set that ArrayList<RelativeLayout> with this next code, but this is only temporary as i plan to use another method later, like an Async task or something so that this view contains some data... RelativeLayout temp; for(int i=0; i<30; i++){ temp = (RelativeLayout) inflater.inflate(R.layout.list_item, null); final LinearLayout extraListItemInfo = (LinearLayout) temp.findViewById(R.id.extraListItemInfo); Button infoBtn = (Button) temp.findViewById(R.id.infoBtn); infoBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Log.v("ListItem", "Button has been clicked... "); extraListItemInfo .setVisibility(View.VISIBLE); ExpandAnimation closeAnim = new ExpandAnimation(extraListItemInfo , animHeight); closeAnim.setDuration(750); closeAnim.setFillAfter(true); if(extraListItemInfo .getTag() == null || !extraListItemInfo .getTag().equals("expanded")){ extraListItemInfo .getLayoutParams().height = 0; friendInfoList.startAnimation(closeAnim.expand()); extraListItemInfo .setTag("expanded"); }else if(extraListItemInfo .getTag().equals("expanded")){ extraListItemInfo .startAnimation(closeAnim.collapse()); extraListItemInfo .setTag("closed"); } //((BaseAdapter) listview.getAdapter()).notifyDataSetChanged(); i tried it here once but then left it //as the only action inside the listview's onitemclick() } }); listItems.add(temp); } this is the list item that i am using: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/darkgrey" android:paddingBottom="5dp" > <LinearLayout android:id="@+id/extraListItemInfo " android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/listItemInfo" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="-10dp" android:background="@color/grey" android:orientation="vertical" android:visibility="gone" > <RelativeLayout android:id="@+id/RelativeLayout04" android:layout_width="match_parent" android:layout_height="@dimen/activity_list_height" android:layout_marginTop="5dp" > <ImageView android:id="@+id/ImageView04" android:layout_width="wrap_content" android:layout_height="25dp" android:layout_margin="5dp" android:src="@drawable/logo_d" /> <TextView android:id="@+id/TextView04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/ImageView04" android:text="TextView" android:textColor="@color/black" android:textSize="17dp" /> </RelativeLayout> <RelativeLayout android:id="@+id/RelativeLayout03" android:layout_width="match_parent" android:layout_height="@dimen/activity_list_height" > <ImageView android:id="@+id/ImageView03" android:layout_width="wrap_content" android:layout_height="25dp" android:layout_margin="5dp" android:src="@drawable/logo_d" /> <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/ImageView03" android:text="TextView" android:textColor="@color/black" android:textSize="17dp" /> </RelativeLayout> <RelativeLayout android:id="@+id/RelativeLayout02" android:layout_width="match_parent" android:layout_height="@dimen/activity_list_height" > <ImageView android:id="@+id/ImageView02" android:layout_width="wrap_content" android:layout_height="25dp" android:layout_margin="5dp" android:src="@drawable/logo_d" /> <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/ImageView02" android:text="TextView" android:textColor="@color/black" android:textSize="17dp" /> </RelativeLayout> <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="match_parent" android:layout_height="@dimen/activity_list_height" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="25dp" android:layout_margin="5dp" android:src="@drawable/logo_d" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@id/imageView1" android:text="TextView" android:textColor="@color/black" android:textSize="17dp" /> </RelativeLayout> <RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="match_parent" android:layout_height="@dimen/activity_list_height"> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="25dp" android:layout_margin="5dp" android:src="@drawable/logo_d" /> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/ImageView01" android:text="TextView" android:textColor="@color/black" android:textSize="17dp" /> </RelativeLayout> </LinearLayout> <RelativeLayout android:id="@+id/listItemInfo" android:layout_width="wrap_content" android:layout_height="95dp" android:background="@drawable/friend_cell_background2x" android:clickable="true" > <RelativeLayout android:id="@+id/leftLayout" android:layout_width="90dp" android:layout_height="match_parent" > <ImageView android:id="@+id/imgCompany" android:layout_width="60dp" android:layout_height="50dp" android:layout_centerHorizontal="true" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:scaleType="centerInside" android:src="@drawable/user2x" /> <ImageView android:id="@+id/imageView2" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:scaleType="fitXY" android:src="@drawable/online_indicator2s" /> </RelativeLayout> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_marginTop="5dp" android:layout_toRightOf="@+id/leftLayout" android:background="@android:color/transparent" android:gravity="left|center" android:orientation="vertical" android:paddingLeft="5dp" > <TextView android:id="@+id/lblCompanyName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Contact Name" android:textColor="@color/white" android:textSize="18dp" android:textStyle="bold" > </TextView> <TextView android:id="@+id/lblReawrdDesc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Last Played Offer" android:textColor="@color/white" android:textSize="17dp" > </TextView> </LinearLayout> <ImageView android:id="@+id/imageView4" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="5dp" android:src="@drawable/facebook_btn2x" /> <Button android:id="@+id/infoBtn" style="?android:attr/buttonStyleSmall" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentBottom="true" android:layout_alignRight="@+id/imageView4" android:background="@drawable/info_btn2x" android:clickable="true" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="13dp" android:layout_toLeftOf="@+id/infoBtn" android:text="Follows 30+" android:textColor="@color/white" android:textSize="11dp" /> <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="75dp" android:layout_height="20dp" android:layout_alignParentBottom="true" android:layout_marginBottom="10dp" android:layout_marginRight="10dp" android:layout_toLeftOf="@+id/textView2" android:background="@drawable/fan_btn2x" android:text="Fans 30+" android:textColor="@color/white" android:textSize="11dp" /> <ImageView android:id="@+id/imageView5" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/imageView4" android:src="@drawable/google_btn2x" /> </RelativeLayout> </RelativeLayout> sorry for any layout problems that may make things difficult to read... but i hope this helps you guys to understand my problem... Thanks UPDATE 2: All of these answers have been helpful in some way, but i think the main issue that i must first fix is why the buttons do not receive click events until i have first scrolled away from that listItem, then back to it, then clicked the button again... If someone can help find a solution to THAT i think that everything else will be much easier to solve... Thanks... A screenshot as requested, but remember that this shot was taken on a samsung galaxy tab 10.1 and due to me using the same layout for this larger screen, it looks much different from what it does on the phone i usually test with (Motorola droid x that isnt rooted and cant take screenshots...) Another Update: I managed to get the clicking and animation working nicely by Extending ArrayAdapter instead of base adapter. Sadly i am still experiencing problems as only the bottom half of the list is clickable. The top half of the list still behaves as before with the very glitchy click events... Any ideas as to what is happening this time? Thanks... A: Well this isn't really an answer, but after rewriting this a few times I managed to fix it so that it functions exactly the way I wanted. This time I left all of the data separate from each view and had each list item be a custom class inheriting RelativeLayout and also implementing its own OnClickListener for its specific infoBtn. My adapter now simply extends ArrayAdapter<> and overrides this getView() method: public View getView(int position, View convertView, ViewGroup parent) { if(convertView != null && (convertView instanceof FriendListItem2)) ((FriendListItem2) convertView).setFriendInfo(friends.get(position)); else convertView = new FriendListItem2(getContext(), friends.get(position)); return convertView; } Finally, in the main activity for this page I simply set the ListView with an adapter that I passed the data to. This is all much cleaner than I had before and I wish it hadn't taken several rewrites of the code to get it right. Hopefully someone can benefit from this, though I still have no clue why I was getting a problem before. Thanks for all previous suggestions.
{ "pile_set_name": "StackExchange" }
Q: Using CSS3Pie htc for border-radius in IE8 I'm using the CSS3Pie htc file to enable border-radius in IE8, but I'm getting no effect. My CSS is: button { border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px; behavior: url(PIE.htc); } I've put PIE.htc in the public root (as is done on the CSS3PIE demo page), having tried in the same folder, using a relative uri and an absolute uri. The demos are working; just not my code! Thanks, Adam A: Try adding position:relative; z-index: 0; as suggested here http://css3pie.com/forum/viewtopic.php?f=3&t=10 This question is similar to the one posted here: CSS3 PIE - Giving IE border-radius support not working? A: The URL of PIE.htc as referenced in behavior: url(PIE.htc); is a relative URL, so it is probably looking for it in the same directory as the stylesheet, so I'd suggest adding a slash to make it an absolute URL. But you say you've already done that. Check that the URL you're specifying does actually load the PIE.htc file - ie put that URL directly into your browswer and see what comes out. It is possible that your web server is not serving it correctly for one reason or another (not recognising the mime type? etc) Have you gone through the known problems on the PIE site? Have you added position:relative; to your style? Could it be the known z-index issue? You specify that it doesn't work in IE8. Have you tried it in IE7? IE6? Same result? (this will eliminate ths possibility of it being an IE8-specific issue) By the way -- unrelated point, but you should put the border-radius style below the versions with the browser-specific prefixes. This is the standard way to do things, as it means that when for example, Firefox starts supporting border-radius, it'll pick up the standard style over -moz-border-radius. If you've got the -moz version below it, that one will continue getting used, which may not be what you want. A: As Daniel Rehner stated, you need to use the position: relative and z-index properties for IE8. If you are using a website with sub directories to call the CSS file, you will also need to use an absolute path in your CSS to PIE.htc - this was one part of our issue. The other part of the issue could be that your server is not outputting the PIE.htc file as text/x-component. You can correct that via IIS or Apache, or call the PIE.php script in your CSS. More info here: http://css3pie.com/documentation/known-issues/#content-type Both of these issues had gotten us, and hope they help you out.
{ "pile_set_name": "StackExchange" }