text
stringlengths
64
81.1k
meta
dict
Q: Como disponibilizar um pacote criado com composer? O json abaixo faz parte do arquivo composer.json de um pacote que criei: { "name": "libspkgs/utils", "type": "library", "description": "Descrição aqui.", "keywords": ["key1", "key2"], "homepage": "https://endereco.com", "license": "MIT", "authors": [ { "name": "Nome do autor", "email": "[email protected]" } ], "require": { "php": ">=5.6.27" }, "autoload": { "psr-4": { "Pkg\\": "lib/" } }, "minimum-stability": "dev" } Estou adicionando o mesmo ao Laravel desta forma: composer require libspkgs/utils v1.0.0 Mas como faço para adicionar sempre a ultima release? A: Disponibilização padrão de um package Primeiramente, você precisa ter uma conta no Packagist. Atualmente (ano de 2016), você pode usar a sua conta do Github para criá-la. Depois, você precisa ter um repositório público para ser apontado pelo Packagist. É importante falar que, por conta de questões de organização, o nome do repositório tenha o mesmo library name que vai ser usado no Composer. Por exemplo: para um pacote chamado vendor_name/library_name no Packagist, seria importante que o seu repositório no Github chamasse library_name. Observação: Vendor Name é o nome do "fornecedor" da biblioteca e Library Name é o nome da biblioteca. O Composer utiliza "vendor name/library name" como padrão de nome para as bibliotecas. Nota: para continuar esse "tutorial", você deve ter em mente que você precisa ter um considerável conhecimento sobre ferramentas de versionamento (como o GIT, por exemplo). Depois de criar seu repositório, recomendo seguir alguns padrões para a criação da sua biblioteca. Por exemplo, um padrão muito utilizado, é definir o seu namespace a partir da pasta src do seu projeto: library_name/ .gitignore composer.json src/ Hello.php Assim, poderíamos configurar o composer.json da seguinte forma: "name" : "vendor_name/library_name", "required" : { "php" : ">=5.4" }, "autoload" : { "psr-4" : { "VendorName\\LibraryName\\" : "src/" } } Sua classe Hello.php dentro de src, obviamente, deve ficar assim: namespace VendorName\LibraryName; class Hello {} Nota: Para testar sua biblioteca antes de enviá-la, é necessário rodar o comando composer dump para gerar o autoload. Caso possua dependências a outras libraries, você deve usar composer install. Depois de tudo isso, você pode fazer o commit e o push de suas alterações para o repositório: >>> cd library_name >>> git commit -am "my first commit" >>> git push Após isso, você precisa submeter a sua biblioteca para o Packagist, através desse formulário: Depois da submissão, é necessário inserir o seu TOKEN API do Packagist nas configurações do seu repositório do Github. Você deve clicar na opção "settings" e em seguida "integrations and services". Depois disso, na opção "add service" você deve escolher "packagist". Depois disso, você deve clicar no serviço "packagist" que foi adicionado, e configurá-lo, colocando seu usuário e o token do Packagist. Veja: O Token que deverá ser adicionado, pode ser encontrado nessa tela do Packagist: Depois de fazer tudo isso, você já poderá testar se sua biblioteca está funcionando corretamente utilizando o comando: composer require vendor_name/library_name Mas e o versionamento? Você precisa definir uma tag no seu repositório para poder demarcar uma versão "utilizável" da sua biblioteca. Por exemplo, se você já tem certeza que sua biblioteca está pronta para o uso, poderá definir uma versão para ela. Você pode definir uma tag dessa forma: git tag 0.0.1 Depois, para enviá-la ao seu repositório, você precisa rodar o comando: git push --tags Note que as tags precisam seguir um padrão. Eu geralmente, sempre uso os três conjuntos de números. As versões no seu Packagist será organizado de acordo com esses números. Por exemplo; 1.0.0 0.0.3 0.0.2 0.0.1 Para a resposta não ficar muito longa, sugiro a leitura de alguns posts do site: Qual é a diferença entre um "branch" e uma "tag"? Quando incrementar a versão usando Semantic Versioning?
{ "pile_set_name": "StackExchange" }
Q: How can i use group by a column 1 and get the most frequent occurance of column 2 in the same output in bigquery I have got data I want output like this I tried SELECT email, time_of_day,COUNT(time_day) AS numtrips FROM internal.data100k GROUP BY email, time_of_day desc limit 26; and many nested but getting error and no idea on what the logic be A: Below is for BigQuery Standard SQL #standardSQL SELECT email, action, SUM(time_of_day_repetition) total_individual_action_count, ARRAY_AGG( STRUCT(time_of_day AS time_of_day_with_max_repetition, time_of_day_repetition AS max_repetition) ORDER BY time_of_day_repetition DESC LIMIT 1 )[OFFSET(0)].* FROM ( SELECT email, action, time_of_day, COUNT(1) time_of_day_repetition FROM `project.dataset.table` GROUP BY email, action, time_of_day ) GROUP BY email, action
{ "pile_set_name": "StackExchange" }
Q: combine a binary file and a .txt file to a single file in python I have a binary file (.bin) and a (.txt) file. Using Python3, is there any way to combine these two files into one file (WITHOUT using any compressor tool if possible)? And if I have to use a compressor, I want to do this with python. As an example, I have 'file.txt' and 'file.bin', I want a library that gets these two and gives me one file, and also be able to un-merge the file. Thank you A: Just create a tar archive, a module that let's you accomplish this task is already bundled with Cpython, and it's called tarfile. more examples here.
{ "pile_set_name": "StackExchange" }
Q: What does it mean to be "sixty-fortied"? I came across this on an episode of Gilmore Girls (2.16 - There's the Rub), where Emily Gilmore says "I can't believe you let me get sixty-fortied!" (60-40d) I can't find much reference to this online, just this one. A: The episode transcript earlier explains LORELAI: This isn’t a singles bar, Mom. It’s a sixty-forty bar. EMILY: A what? LORELAI: Sixty-year-old men hitting on forty-year-old women, divorcees mostly. When later the expression you mentioned comes up it refers to that: EMILY: Yes, by sitting me at a bar where you practically forced me to engage in inappropriate behavior. LORELAI: What? EMILY: You let me get sixty-fortied! As Silenius describes in the comments this is a form of transforming another class of words to a verb - or verbing / verbification. Therefore using the numbers as a verb by putting them in the right context and adding a verb ending.
{ "pile_set_name": "StackExchange" }
Q: urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them. The server-side is plain-vanilla Apache 2 on Ubuntu over port 80. The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files: urllib2.URLError: <urlopen error <10048, 'Address already in use'>> This link: http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out. The code (called once for each of the 55,000 files it downloads) is this: request = urllib2.Request(file_remote_path) opener = urllib2.build_opener() datastream = opener.open(request) outfileobj = open(temp_file_path, 'wb') try: while True: chunk = datastream.read(CHUNK_SIZE) if chunk == '': break else: outfileobj.write(chunk) finally: outfileobj = outfileobj.close() datastream.close() UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option. A: If it is really a resource problem (freeing os socket resources) try this: request = urllib2.Request(file_remote_path) opener = urllib2.build_opener() retry = 3 # 3 tries while retry : try : datastream = opener.open(request) except urllib2.URLError, ue: if ue.reason.find('10048') > -1 : if retry : retry -= 1 else : raise urllib2.URLError("Address already in use / retries exhausted") else : retry = 0 if datastream : retry = 0 outfileobj = open(temp_file_path, 'wb') try: while True: chunk = datastream.read(CHUNK_SIZE) if chunk == '': break else: outfileobj.write(chunk) finally: outfileobj = outfileobj.close() datastream.close() if you want you can insert a sleep or you make it os depended on my win-xp the problem doesn't show up (I reached 5000 downloads) I watch my processes and network with process hacker.
{ "pile_set_name": "StackExchange" }
Q: json.stringify does not process object methods I am trying to develop an offline HTML5 application that should work in most modern browsers (Chrome, Firefox, IE 9+, Safari, Opera). Since IndexedDB isn't supported by Safari (yet), and WebSQL is deprecated, I decided on using localStorage to store user-generated JavaScript objects and JSON.stringify()/JSON.parse() to put in or pull out the objects. However, I found out that JSON.stringify() does not handle methods. Here is an example object with a simple method: var myObject = {}; myObject.foo = 'bar'; myObject.someFunction = function () {/*code in this function*/} If I stringify this object (and later put it into localStorage), all that will be retained is myObject.foo, not myObject.someFunction(). //put object into localStorage localStorage.setItem('myObject',JSON.stringify(myObject)); //pull it out of localStorage and set it to myObject myObject = localStorage.getItem('myObject'); //undefined! myObject.someFunction I'm sure many of you probably already know of this limitation/feature/whatever you want to call it. The workaround that I've come up with is to create an object with the methods(myObject = new objectConstructor()), pull out the object properties from localStorage, and assign them to the new object I created. I feel that this is a roundabout approach, but I'm new to the JavaScript world, so this is how I solved it. So here is my grand question: I'd like the whole object (properties + methods) to be included in localStorage. How do I do this? If you can perhaps show me a better algorithm, or maybe another JSON method I don't know about, I'd greatly appreciate it. A: Functions in javascript are more than just their code. They also have scope. Code can be stringified, but scope cannot. JSON.stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans. Anything else will be ignored or throw errors. Functions are not a supported entity in JSON. JSON handles pure data only, functions are not data, but behavior with more complex semantics. That said you can change how JSON.stringify() works. The second argument is a replacer function. So you could force the behavior you want by forcing the strinigification of functions: var obj = { foo: function() { return "I'm a function!"; } }; var json = JSON.stringify(obj, function(key, value) { if (typeof value === 'function') { return value.toString(); } else { return value; } }); console.log(json); // {"foo":"function () { return \"I'm a function!\" }"} But when you read that back in you would have to eval the function string and set the result back to the object, because JSON does not support functions. All in all encoding functions in JSON can get pretty hairy. Are you sure you want to do this? There is probably a better way... Perhaps you could instead save raw data, and pass that to a constructor from your JS loaded on the page. localStorage would only hold the data, but your code loaded onto the page would provide the methods to operate on that data. // contrived example... var MyClass = function(data) { this.firstName = data.firstName; this.lastName = data.lastName; } MyClass.prototype.getName() { return this.firstName + ' ' + this.lastName; } localStorage.peopleData = [{ firstName: 'Bob', lastName: 'McDudeFace' }]; var peopleData = localStorage.peopleData; var bob = new MyClass(peopleData[0]); bob.getName() // 'Bob McDudeFace' We don't need to save the getName() method to localStorage. We just need to feed that data into a constructor that will provide that method.
{ "pile_set_name": "StackExchange" }
Q: 4 IF AND Statements in one cell Trying to get two equations to then present one of four options. Example: Have no idea where to start, all four need to sit in the one cell. A: =IF(AND(O34 > O33; Q34 > Q33); Z28; IF(AND(O34 < O33; Q34 > Q33); Z29; IF(AND(O34 > O33; Q34 < Q33); Z30; IF(AND(O34 < O33; Q34 > Q33); Z31; )))) If you want to include equality add = behind >< like: <= or >=. For inequality use: <>. Also, AND can be changed to OR if you need such logic.
{ "pile_set_name": "StackExchange" }
Q: DateTime wrong result (potential bug?) for verification as a bug, can someone test this with his php: $timeZone = new DateTimeZone('Europe/Berlin'); $startDate = new DateTime('first day this month 00:00:00', $timeZone); echo $startDate->format('d.m.Y'); Result: 02.02.2013 I've tested it with php 5.2 and PHP 5.3, with same result.... As a "resolution", what's the best alternate way to do this? $timeZone = new DateTimeZone('Europe/Berlin'); $startDateAlt = new DateTime('now', $timeZone); $startDateAlt->setTimestamp(mktime(0, 0, 0, date("m") , 1, date("Y"))); A: You omitted the of, so it parses it as something else: $timeZone = new DateTimeZone('Europe/Berlin'); $startDate = new DateTime('first day of this month 00:00:00', $timeZone); echo $startDate->format('d.m.Y'); returns 01.02.2013 If for some reason this doesn't work (old php version it seems from your comment), you can try this? Bit of a hack maybe... $startDate = new DateTime(); $days = $startDate->format('d'); $days = $days - 1; $startDate->modify("-{$day} days"); $startDate->setTime(0,0,0); echo $startDate->format('d.m.Y');
{ "pile_set_name": "StackExchange" }
Q: Open SharePoint 2013 panel in browser after creating a new Web Application with PowerShell I have SharePoint 2013 on a local virtual machine and I created a local Web Application using that PowerShell script: #This is the Web Application URL $WebApplicationURL = "http://test.intranet.local"; #This is the Display Name for the SharePoint Web Application $WebApplicationName = "Test"; #This is the Display Name for the Application Pool $ApplicationPoolDisplayName = "TestApp Pool"; #This is identity of the Application Pool which will be used (Domain\User) $ApplicationPoolIdentity = "domain\username"; if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Microsoft.SharePoint.PowerShell" } $HostHeader = $WebApplicationURL.Substring(7) $HTTPPort = "80" $ContentDatabase = "Test ContentDatabase" New-SPServiceApplicationPool -Name $ApplicationPoolDisplayName -Account $ApplicationPoolIdentity $AppPool = (Get-SPServiceApplicationPool $ApplicationPoolDisplayName) $AppPoolManagedAccount = (Get-SPManagedAccount $ApplicationPoolIdentity | select username) $ap = New-SPAuthenticationProvider $WebApp = New-SPWebApplication -ApplicationPool $AppPool.Name -ApplicationPoolAccount $AppPoolManagedAccount.Username -Name $WebApplicationName -url $WebApplicationURL -port $HTTPPort -DatabaseName $ContentDatabase -HostHeader $hostHeader -AuthenticationProvider $ap When I run the script everything works fine. After that I created the root site: $template = Get-SPWebTemplate "STS#0"; $WebApplicationURL = "http://test.intranet.local"; $SiteCollectionURL= $WebApplicationURL+ "/" $site = New-SPSite -Url $SiteCollectionURL -OwnerAlias "domain\username" -Template $template When I try opening the SharePoint panel on Internet Explorer using the Web Application URL I can't display the page. I'm a SharePoint newbie and I remember I faced this problem in the past and I resolved it adding the URL in a configuration file. Now I don't remember how I did that thing, could anyone help me? A: Since this is a development/test machine, you need to DisableLoopbackCheck on your machine and add a host entry. Steps are as below: Open powershell and add the following command: New-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword If you want to do it manually, go to Run > type regedit and then click OK In Registry Editor, locate the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa Right-click Lsa, point to New, and then click DWORD Value. (In Win 2008, its DWORD 32bit) Type DisableLoopbackCheck, and then press ENTER. Right-click DisableLoopbackCheck, and then click Modify. In the Value data box, type 1 and then click OK. Quit Registry Editor. You may need to restart your server. After doing , that you need to add the entry in the hosts file as below: Go to this path C:\Windows\System32\drivers\etc\ Open the hosts file Add the entry as 127.0.0.1 test.intranet.local Restart browser Open the site collection, you will get the authentication prompt.
{ "pile_set_name": "StackExchange" }
Q: Dependency injection in Specflow, is it one context object per feature? In Specflow it's possible to share context between step definitions using dependency injection Does this mean that you end up with a different "context" class for each feature? If so, wouldn't this make it impractical to share step definitions across features? Do you assume fields have been set? A: Does this mean that you end up with a different "context" class for each feature? I don't think this would be the case. When writing a spec you will most certainly mention several "kind" of parts of your system. Let's say we have the following scenario: Scenario: List todo items Given I'm registered as [email protected] And I'm logged in as [email protected] And I add a todo item with the text 'Listen to stackoverflow podcast' When I list all my todo items Then I should see the following items | Text | Completed | | Listen to stackoverflow podcast | false | In this case we're interacting with several parts of the system: Registration Authentication TodoItem creation TodoItem listing When implementing the steps for this feature we'll probably end up with a step files organized like this: AuthSteps Given I'm registered as __ Given I'm logged in as __ TodoItemsSteps I add a todo item with the text '__' When I list all my todo items Then I should see the following items In this case using context injection we would want to share the value of CurrentUser to be able to say things like "When I list all my todo items", referring to the current user. This way any other steps in any other stepFile can be contextual of previous steps. On the other hand, I wouldn't use context injection with the results of When I list all my todo items because the only steps that would share those feature specific concerns will be in the same feature file. You can have multiple variations of the then "statement", like Then I should see n items. Although I do think you might have more than one class you use with using context injection to share dependencies of the services you're constructing, or maybe the services themselves (Storage, Session, etc...)
{ "pile_set_name": "StackExchange" }
Q: How to find which serial port is in use? The Question: I plugged in a device (i.e. GSM modem) through a serial port (a.k.a. RS-232), and I need to see with which file in /dev/ filesystem this device was tied up, to be able to communicate with it. Unfortunately there is no newly created file in /dev/ nor can be seen anything in dmesg output. So this seems to be a hard question. Background: I had never worked with a serial device, so yesterday, when there appeared a need, I tried to Google it but couldn't find anything helpful. I spent a few hours in seek, and I want to share a found answer as it could be helpful for someone. A: Unfortunately serial ports are non-PlugNPlay, so kernel doesn't know which device was plugged in. After reading a HowTo tutorial I've got the working idea. The /dev/ directory of unix like OSes contains files named as ttySn (with n being a number). Most of them doesn't correspond to existing devices. To find which ones do, issue a command: $ dmesg | grep ttyS [ 0.872181] 00:06: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A [ 0.892626] 00:07: ttyS1 at I/O 0x2f8 (irq = 3) is a 16550A [ 0.915797] 0000:01:01.0: ttyS4 at I/O 0x9800 (irq = 19) is a ST16650V2 [ 0.936942] 0000:01:01.1: ttyS5 at I/O 0x9c00 (irq = 18) is a ST16650V2 Above is an example output of my PC. You can see the initialization of a few serial ports: ttyS0, ttyS1, ttyS4, ttyS5. One of them is going to have a positive voltage upon a device plugged in. So by comparing the content of the file /proc/tty/driver/serial with and without the device plugged in we can easily find the ttyS related to our device. So, now do: $ sudo cat /proc/tty/driver/serial> /tmp/1 (un)plug a device $ sudo cat /proc/tty/driver/serial> /tmp/2 Next check the difference between the two files. Below is an output of my PC: $ diff /tmp/1 /tmp/2 2c2 < 0: uart:16550A port:000003F8 irq:4 tx:6 rx:0 --- > 0: uart:16550A port:000003F8 irq:4 tx:6 rx:0 CTS|DSR By comparing the three numbers with the dmesg output we can determine which one is the port: [ 0.872181] 00:06: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A Hence, our device is /dev/ttyS0, mission accomplished!
{ "pile_set_name": "StackExchange" }
Q: Removing surrounding brackets in Math expression PHP I am trying to figure out, how to remove surrounding brackets in math expressions using php. Some cases are: (A+B)(B+C) should stay the same ((((A)))) should get A ((A(B+C))) should get A*(B+C) (((((B+C)*A)))) should get (B+C)*A I cannot find a solution which is right in any case. Using math rules like distributive property is no option. I am not looking for copy-and-paste algorithm, just a criterion which fits all of my cases. This is the latest attempt, I tried different methods like regex, but I did not figure it out. function removeSurroundingBrackets($str) { $res=$str; if(strcmp($res[0],'(')===0 && strcmp($res[strlen($res)-1],')')===0) { $firstOther=0; for(; $firstOther<strlen($str);$firstOther++) { if(strcmp($str[$firstOther],'(')!==0) break; } $removableCount=0; $removableCount=substr_count($str,')',$firstOther)-substr_count($str,'(',$firstOther); } return substr($str,$removableCount,-$removableCount); } EDIT: I found a Solution: function removeSurroundingBrackets($str) { $res=$str; while(strcmp($res[0],'(')===0 && strcmp($res[strlen($res)-1],')')===0) { if($this->checkBrackets(substr($res,1,-1))) $res=substr($res,1,-1); else return $res; } return $res; } function checkBrackets($str) { $currdepth=0; foreach(str_split($str) as $char) { if(strcmp($char,')')===0) { if($currdepth<=0) return false; else $currdepth--; } else if(strcmp($char,'(')===0) $currdepth++; } return true; } A: With preg_match: $pattern = '~\A(?:\((?=([^()]*(?:\((?1)\)[^()]*)*)(\)\2?+)\z))*\K(?(1)\1|.*)~'; if ( preg_match($pattern, $str, $m) ) echo $m[0], PHP_EOL; The idea is to consume parenthesis at the start of the string as long as they are outermost parenthesis. To be sure that they are outermost parenthesis, you need to check if there's always a well balanced expression inside them. To consume/count these outermost parenthesis, I use this design: \A # from the start of the string (?: # an eventually repeated non-capturing group \( (?= # a lookahead to check if the corresponding closing parenthesis exists ([^()]*(?:\((?1)\)[^()]*)*) # balanced expression inside ( \) \2?+ ) # capture group grows at each non-capturing group repetition \z # anchored at the end of the string ) )* # since the quantifier is greedy, it will consume all opening parenthesis Then, you only need to use \K to remove these parenthesis from the match result and to test if the capture group 1 exists: \K (?(?1) # if the capture group 1 exists \1 # match its content | # else .* # match all the string )
{ "pile_set_name": "StackExchange" }
Q: Path in variable How can I add letter to path? For example if i have a path like 'c:\example2\media\uploads\test5.txt' (stored in a variable), but I need something like r'c:\example2\media\uploads\test5.txt', how can I add letter `r? Because the function open() does not want to open the first path. When I try add path to function open() it gives me an error and path like this: u'c:\\example2\\media\\uploads\\test5.txt' and says that file or directory is absent. What should i do? Error looks like: [Error 3] The system cannot find the path specified: u'C:\\example2\\media\\upload\\ZipFile.zip' when i do this open('c:\example2\media\uploads\test5.txt') it not work. And gives me error ( which you can see on the top) A: From the error message it is clear that the string is stored in the correct format (backslashes are escaped by doubling). So it seems the path is wrong, and the file is indeed absent. On the other hand, in your second example that you added in your edit, you use open('c:\example2\media\uploads\test5.txt') - this will definitely fail because \t is a tab character (whereas all the other backslash-letter combinations don't exist, so the backslash will be treated like it was escaped correctly). But you said that the string was stored in a variable, so I don't see how this example helps here. Consider the following: >>> path = 'c:\example2\media\uploads\test5.txt' >>> path 'c:\\example2\\media\\uploads\test5.txt' See? All the backslashes are converted to escaped backslashes except for the \t one because that's the only one with special meaning. And now, of course, this path is wrong. So if the variables you're referring to have been defined this way (and now contain invalid paths) there's not much you can do except fix the source: >>> path = r'c:\example2\media\uploads\test5.txt' >>> path 'c:\\example2\\media\\uploads\\test5.txt' You might think you could "fix" a defective path afterwards like this: >>> path = 'c:\example2\media\uploads\test5.txt' >>> path.replace("\t","\\t") 'c:\\example2\\media\\uploads\\test5.txt' ...but there are many other escape codes (\b, \r, \n etc.), so that's not really a feasible way, especially because you'd be doctoring around the symptoms instead of fixing the underlying problem.
{ "pile_set_name": "StackExchange" }
Q: System wide proxy with encypted ISA server request I recently install Linux Mint Debian on my computer. It is working fine and I also have internet. But just firefox is able to get through the proxy. After some research I found out that the ISA server in my network is automatically refusing all authentifications that are not encrypted. So setting a system wide proxy with using export HTTP_PROXY="http://user:passwd@proxy:port/" Will not work. So how do I get my system to send encrypted requests to the ISA server? A: Install a bridge proxy like cntlm or ntlmaps. Both are available in Debian.
{ "pile_set_name": "StackExchange" }
Q: How to make reactive variables, like the data() in Vue? Vue+Typescript How to maintain the reactivity of variables, I’ve only thought of creating a data object, to simulate a date in Vue, but maybe there are more normal ways? example of my code: <script lang="ts"> import {Vue, Component, Inject} from 'vue-property-decorator'; import {DependencyConstants} from "@/dependency/DependencyConstants"; import {WorkspaceService, Employee, EmployeesResponse} from "@/service/WorkspaceService"; interface Data{ empList: Employee[]; } @Component({}) export default class Employees extends Vue { @Inject(DependencyConstants.WORKSPACESERVICE) private employees !: WorkspaceService; private data: Data = { empList: [], }; public getEmployees(): void { const employees: EmployeesResponse = this.employees.getEmployees(new Date()); const empList: Employee[] | undefined = employees.employees; this.data.empList = empList as Employee[] } public created(): void { this.getEmployees(); } } </script> A: If you use vue.js and typescript I strongly advise you to look at this link. You will find how to properly define data, computed, methods and so on. You will find the following example : <template> <div> <input v-model="msg"> <p>prop: {{propMessage}}</p> <p>msg: {{msg}}</p> <p>helloMsg: {{helloMsg}}</p> <p>computed msg: {{computedMsg}}</p> <button @click="greet">Greet</button> </div> </template> <script> import Vue from 'vue' import Component from 'vue-class-component' @Component({ props: { propMessage: String } }) export default class App extends Vue { // initial data msg = 123 // use prop values for initial data helloMsg = 'Hello, ' + this.propMessage // lifecycle hook mounted () { this.greet() } // computed get computedMsg () { return 'computed ' + this.msg } // method greet () { alert('greeting: ' + this.msg) } } </script> If you want reactive data, you can use property accessors (get) to declare computed properties. From what I understood about your code, you can just do this : @Component({}) export default class Employees extends Vue { @Inject(DependencyConstants.WORKSPACESERVICE) private employees !: WorkspaceService; get employees() { const employees: EmployeesResponse = this.employees.getEmployees(new Date()); const empList: Employee[] | undefined = employees.employees; return empList } public created(): void { this.getEmployees(); } } Yo can access directly to employees from your template. For istance : <template> <ul> <li v-for="employee in employees" :key="employee.id"> {{employee.name}} // I assume your employee have an id and a name </li> </ul> </template>
{ "pile_set_name": "StackExchange" }
Q: how to make Jenkins create a tunnel before polling from SVN I need to create a tunnel like the following before code can be checked out from SVN : ssh -L 9898:some_server.com:9898 user@another_server.com Now, I added pre-scm-buildstep plugin and wrote a script to open the tunnel before updating the repository as explained here, but it doesn't work with polling. It only works if I ask Jenkins to 'Build now'. In the setup where I have set it up to poll, its red saying that its unable to access the repository url, which can only happen if the tunnel was not created. Is there any plugin such that I can execute a script before it polls, so that I can open the tunnel before it starts polling A: Use ProxyCommand in your ssh config to have ssh automatically create the tunnel for you. e.g., Host another_server.com ProxyCommand ssh some_server.com exec nc %h %p With the above in ~jenkins/.ssh/config (or whatever user jenkins runs as), when it tries to ssh to another_server.com it will actually ssh to some_server.com and run nc to forward the ssh connection to the another_server.com.
{ "pile_set_name": "StackExchange" }
Q: How to make the two way binding in AngularJS Isolated scope? directive('confButton', function () { return { restrict: 'EA', replace: false, scope: { modalbtntext: '@', btntext: '@', iconclass: '@', btnclass:'@', callback: '&', disabled: '=' }, templateUrl : '/app/scripts/mod/Directives/ConfirmationDirective/ConfrimationDirect.html', controller: ['$scope', '$element', '$attrs', '$transclude', 'modalService', function ($scope, $element, $attsr, $transclude, modalService) { $scope.open = function () { console.log($scope.disabled); var bodyMessage = ''; if ($scope.modalbtntext.toLowerCase() == "edit") { bodyMessage = "Are you sure you want to edit this ?" } else{ bodyMessage = 'Are you sure you want to delete this customer?' } var modalOptions = { closeButtonText: 'Cancel', actionButtonText: $scope.modalbtntext, headerText: 'Please Confirm your Request', bodyText: bodyMessage }; modalService.showModal({}, modalOptions).then(function (result) { $scope.callback(); }); } }] } }); and this is my Tempalte <button class="{{btnclass}}" ng-disabled="{{disabled}}" ng-click="open()"><i class="{{iconclass}}"></i> {{btntext}} </button> here is the implementation of the directive <conf-button modalbtntext="Delete" disabled="gridOptions.selectedItems.length == 0" btntext="Delete Selected" btnclass="btn btn-default hidden-xs" iconclass ="glyphicon glyphicon-trash" callback="deleteCity()"> </conf-button> The point is I want to implement the two way binding in the button .. it's disabled by default as no item is selected .. but when I choose any item it still disabled. how can I achieve the two way binding in this case ? A: To make 2 way binding to work you need to bind it to an object. What happens is that you bind the value to a primitive during the expression evaluation so the binding doesn't update. You can use $watch to update a certain value. .controller('someCtrl', function($scope){ $scope.gridOption.selectedItems = []; $scope.$watch(function(){ //Watch for these changes return $scope.gridOptions.selectedItems.length == 0; }, function(newVal){ //Change will trigger this callback function with the new value $scope.btnDisabled = newVal; }); }); HTML markup: <conf-button modalbtntext="Delete" disabled="btnDisabled" btntext="Delete Selected" btnclass="btn btn-default hidden-xs" iconclass ="glyphicon glyphicon-trash" callback="deleteCity()"> </conf-button>
{ "pile_set_name": "StackExchange" }
Q: Ruby on Rails HABTM adding records to table I am trying to use a Has and belongs to many relationship to link users to teams, the issue I am having is that I cannot work out how to add the ids into my user_teams table. In my model I have done the following User Model has_and_belongs_to_many :teams Team Model has_many :users Teams Controller def create @team = Team.new(params[:team]) respond_to do |format| if @team.save @team.users << User.find(current_user) format.html { redirect_to @team, notice: 'Team was successfully created.' } format.json { render json: @team, status: :created, location: @team } else format.html { render action: "new" } format.json { render json: @team.errors, status: :unprocessable_entity } end end end A: You don't have proper relationship. You should to take care of association and habtm migration, Have a look to below example, I have two model "User" and "Organization" organization model class Organization < ActiveRecord::Base has_and_belongs_to_many :users, :association_foreign_key => 'user_id', :class_name => 'User', :join_table => 'organizations_users' attr_accessible :address, :name end user model class User < ActiveRecord::Base has_and_belongs_to_many :organizations, :association_foreign_key => 'organization_id', :class_name => 'Organization', :join_table => 'organizations_users' attr_accessible :name, :phone end Then need to create new OrganizationsUsers migration like below. class CreateOrganizationsUsersTable < ActiveRecord::Migration def self.up create_table :organizations_users, :id => false do |t| t.references :organization t.references :user end add_index :organizations_users, [:organization_id, :user_id] add_index :organizations_users, [:user_id, :organization_id] end def self.down drop_table :organizations_users end end You can get working example from here.
{ "pile_set_name": "StackExchange" }
Q: Value of an UNSET NEW.Column in Before Update Trigger SETUP A very simple table with 2 columns. (UserName, Password) In this table I have a Before Update trigger: BEGIN SET NEW.Password = SHA2(NEW.Password,256); END Problem When ever I update the username AND password, all is great. BUT when I try to update just the username: UPDATE `UserCreds` SET `UserName`= 'BOB' WHERE `UserID`= 156 the password Also changes. Question How do I get the password field to update ONLY when the update statement contains SET `Password` = 'supersafepassword' What I tried I tried a few variations of the following but everything still seems to evaluate to true, and the password still changes. BEGIN IF NEW.Password IS NOT NULL THEN SET NEW.Password = SHA2(NEW.Password,256); END IF; END So i guess the real question is, What does the value of NEW.Password equal when the Update statement doesn't set it equal to anything? In Short If I don't Set the password in my update statement i don't want my password to change (as in changing username only)... but if I DO set it, I want it to be encrypted before saving. A: Maybe mysql documentation is not so clear, but NEW is in fact refers to pseudorecord which contains new values (let's ignore access right for simplicity). It's probably more accurate to say that it gives you access to the row as it will be stored in the table , whereas OLD gives access to the row as it was right before UPDATE/DELETE executed. Keeping that in mind, comparision in trigger body OLD.PASSWORD <> NEW.PASSWORD will be true (assuming "password" field is not null, otherwise you need to use IFNULL or something similar) only if PASSWORD field was actually changed by UPDATE statement.
{ "pile_set_name": "StackExchange" }
Q: Python/JSON: How to Resolve UnicodeDecodeError I have been trying to learn Python recently and following along with the book, Python for Data Analysis and using Python 2.7 with Canopy. In the book, they provided a link to some raw data which I saved and assigned to a path variable. After trying to convert the text file to a list of dictionaries using JSON: records = [json.loads(line) for line in open(path)] I received the following error: --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-17-b1e0b494454a> in <module>() ----> 1 records = [json.loads(line) for line in open(path)] C:\Users\Marc\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win- x86_64\lib\json\__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 336 parse_int is None and parse_float is None and 337 parse_constant is None and object_pairs_hook is None and not kw): --> 338 return _default_decoder.decode(s) 339 if cls is None: 340 cls = JSONDecoder C:\Users\Marc\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win- x86_64\lib\json\decoder.pyc in decode(self, s, _w) 363 364 """ --> 365 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 366 end = _w(s, end).end() 367 if end != len(s): C:\Users\Marc\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\json\decoder.pyc in raw_decode(self, s, idx) 379 """ 380 try: --> 381 obj, end = self.scan_once(s, idx) 382 except StopIteration: 383 raise ValueError("No JSON object could be decoded") UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 6: invalid start byte The weird thing is that this worked on a different computer, which I thought was using the same version of Python. Thanks in advance. A: The data in question contains one U+2019 RIGHT SINGLE QUOTATION MARK character, encoded to UTF-8. But you used copy-and-paste to save the data rather than save the text straight to disk. In doing so, somewhere along the way the data was decoded, then encoded again, to Windows Codepage 1252: >>> u'\u2019'.encode('cp1252') '\x92' In other words, your data file is not the same. It probably contains the same data but using a different encoding. The JSON standard states data needs to be encoded to UTF-8, UTF-16 or UTF-32, with UTF-8 being the default, and that is what the Python json module will use if you don't give it an encoding. Because you are feeding it CP-1252 data instead, the decoding fails.
{ "pile_set_name": "StackExchange" }
Q: How to assign string value to variable from curl and jq in shell script? I am trying to assign a string I get from curl and jq to a variable. this is my code below, but it doesn't work. I am a Mac user. value=$(curl -X GET curl -X GET https://apitest.onkore.com/onkore/api/v1/storeCategories | jq '.[2] | ._id') A: $ value=$(curl -X GET https://apitest.onkore.com/onkore/api/v1/storeCategories | jq '.[2] | ._id') $ echo "$value" "59178d2a4ca53714085a0903" In other words, "curl -X GET curl -X GET" is incorrect. P.S. You might want to use the -r command-line option of jq.
{ "pile_set_name": "StackExchange" }
Q: Java: Processing an array in parallel, find which position an exception occurred First, I have an array which is filled with 0's except for position 5, which is filled with "a" (put there intentionally to throw an NumberFormatException). And then I call testMethod passing the array, the size of the array, and how many Callables there will be. In this example the array has a size of 10, and there are 4 callables.. the array is processed in chunks: First chunk is positions 0 and 1 Second chunk is positions 2 and 3 Third chunk is positions 4 and 5 Fourth chunk is positions 6 and 7 Fifth chunk is positions 8 and 9 Sixth chunk is position 10 I need to find out which position the NumberFormatException occurs, or in a more general sense: I need to know what the position is when any exception occurs. So I can print out in the message "Execution exception occurred at position 5" I'm quite new to using ExceutorService/Callables so I'm not quite sure how to achieve this... And if it's impossible to achieve using my current set up... is there a similar way to do this parallel processing that will also give me the ability to find the position where the exception occurred? import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class ThreadTest { private final static ArrayList<Callable<Boolean>> mCallables = new ArrayList<>(); private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4); public static void main(String[] args) throws Exception { /*Fill the array with 0's, except for position 5 which is a letter and will throw number format exception*/ final String[] nums = new String[10]; for (int i = 0; i < 5; i++) { nums[i] = "0"; } nums[5] = "a"; for (int i = 6; i < nums.length; i++) { nums[i] = "0"; } testMethod(nums, 10, 4); } static void testMethod(String[] nums, int size, int processors) throws Exception { mCallables.clear(); int chunk = (size / processors) == 0 ? size : size / processors; System.out.println("Chunk size: "+chunk); for (int low = 0; low < size; low += chunk) { final int start = low; final int end = Math.min(size, low + chunk); mCallables.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { System.out.println("New call"); for (int pos = start; pos < end; pos++) { System.out.println("Pos is " + pos); System.out.println("Num is " + nums[pos]); double d = Double.parseDouble(nums[pos]); } //end inner loop return true; } //end call method }); //end callable anonymous class } try { List<Future<Boolean>> f = mExecutor.invokeAll(mCallables); for (int i = 0; i < f.size(); i++) { f.get(i).get(); } } catch (ExecutionException e) { String s = e.toString(); System.out.println(s); System.out.println("Execution exception"); //need to write here which pos the numberFormat exception occurred } mExecutor.shutdown(); } } A: Can't you add a try/catch over the Double.parseDouble line and throw an exception which includes the position ?
{ "pile_set_name": "StackExchange" }
Q: Calling child block methods in main block phtml Basically what i want to is to include child blocks in my main block, and use their methods without making them input any html. If i have this structure: <block type="core/template" template"/custom.phtml"> <block type="catalog/product_view_options" /> </block> In custom.phtml i want to be able to call method from options block. $this->some_method_from_options_block(); That way i wont need to use createBlock inside the custom.phtml every time i need to access some method A: When you write in the xml: <block type="core/template" template="custom.phtml"> Your block's class is Mage_Core_Block_Template and you can access any methods inside that class and the class it extends. So you can have 2 options here, your parent class extends your child class ( I believe this is what you want, but is a bit wrong ). Inside Magento you'll see that for this you have something like: <block type="core/template" template="custom.phtml"> <block type="catalog/product_view_options" template="custom_child.phtml" /> </block> And inside custom_child.phtml you'll have $this->some_method_from_options_block(); Also you can use a helper to have all your methods in one class. And when you use child blocks in xml, all you have to do in parents phtml templates is echo $this->getChildHtml('child_name'); (you don't need createBlock) ofc - the parent class has to have the method defined or extend Mage_Core_Block_Abstract (Mage_Core_Block_Template). You should take a look inside folder Mage/Core/Block for more info about the methods some of the core classes have.
{ "pile_set_name": "StackExchange" }
Q: How to show a progress bar notification in xamarin forms I am using xamarin forms and i came across this plugin https://github.com/thudugala/Plugin.LocalNotification in order to show notifications to user. But how can a progress bar be shown on notification area? I cant find an example of how this is done. This is the code i use for sending notification CrossLocalNotifications.Current.Show("title", "body"); Is there a cross platform solution as the above example? Or a correct implementation using Dependency Services? A: What you're trying to achieve is not possible with the local notification plugin. However, it should be rather trivial to extend the library to add an additional argument for the progress data shown on the progress bar. Basically, you just need to pass two additional values from the Notification Builder by calling the SetProgress(int max, int progress, bool intermediate) method. This is best explained in Google's Android documentation here. The method were you should add the call to SetProgress() is ShowNow() in the Android specific class /Platform/Droid/NotificationServiceImpl.cs. Of course you also need to make changes elsewhere so that you can provide the max and progress values from the cross-platform code. If the above solution seems too complex and you're not using the plugin extensively, perhaps you can just construct the notifications yourself in the Android project and execute that code using the dependency service. Edit: I removed the Google Books link which doesn't seem to work for everyone. Instead, here is an article from Microsoft Docs, detailing how the local notifications can be created. The only additional thing that is missing from the guies is the SetProgress method which is required to show the progress bar. Also, notice that you need to submit the notification again and again to show progress in the progress bar. Check the third reply (from Cheesebaron) on this thread in the Xamarin Forums for a short explanation and bits of code on how it works.
{ "pile_set_name": "StackExchange" }
Q: Create mxnet.ndarray.NDArray from pycuda.driver.DeviceAllocation I am trying to pass output of some pycuda operation to the input of mxnet computational graph. I am able to achieve this via numpy conversion with the following code import pycuda.driver as cuda import pycuda.autoinit import numpy as np import mxnet as mx batch_shape = (1, 1, 10, 10) h_input = np.zeros(shape=batch_shape, dtype=np.float32) # init output with ones to see if contents really changed h_output = np.ones(shape=batch_shape, dtype=np.float32) device_ptr = cuda.mem_alloc(input.nbytes) stream = cuda.Stream() cuda.memcpy_htod_async(d_input, h_input, stream) # here some actions with d_input may be performed, e.g. kernel calls # but for the sake of simplicity we'll just transfer it back to host cuda.memcpy_dtoh_async(d_input, h_output, stream) stream.synchronize() mx_input = mx.nd(h_output, ctx=mx.gpu(0)) print('output after pycuda calls: ', h_output) print('mx_input: ', mx_input) However i would like to avoid the overhead of device-to-host and host-to-device memory copying. I couldn't find a way to construct mxnet.ndarray.NDArray directly from h_output. The closest thing that i was able to find is construction of ndarray from dlpack. But it is not clear how to work with dlpack object from python. Is there a way fo achieve NDArray <-> pycuda interoperability without copying memory via host? A: Unfortunately, it is not possible at the moment.
{ "pile_set_name": "StackExchange" }
Q: How to select Input checkbox and create automatically div in other div I have a simple form with two checkbox: <form id="formTest"> <input type="checkbox" id="imageOne"> <img src="/uploads/imagens/imageone.jpg"> <input type="checkbox" id="imageTwo"> <img src="/uploads/imagens/imageone.jpg"> </form> <div id="test"> </div> I'm following this jQuery tutorial for creating new elements: http://jquerybrasil.org/criando-elementos-com-jquery/ <script> $("#formTest").change(function () { $('<div>',{ id : 'imageTow or One', }); }); </script> When any checkbox is selected, I need to create a div inside div#test with the corresponding checkbox image inside it. How can I do it? Below is a image explaining what should happen. A: If I got it right, whenever a checkbox is clicked it should create a div inside div test with the corresponding checkbox image. I made some changes in the form, so jQuery can get the image elements easier. Corrected the inputs, they must have name and value attributes Added label elements, the for is a reference for the input with that id Bonus: because we are using label and it is referencing the checkbox, when you click the image itself, it will also behave as if you clicked the checkbox, this eases the user experience <form id="formTest"> <input type="checkbox" name="imageOne" id="imageOne" value="1"/> <label for="imageOne" id="labelimageOne"> <img src="/uploads/imagens/imageone.jpg"> </label> <input type="checkbox" name="imageTwo" id="imageTwo" value="1"/> <label for="imageTwo" id="labelimageTwo"> <img src="/uploads/imagens/imageone.jpg"> </label> </form> Your div test is lacking the id attribute, so correct it: <div id="test"> </div> This is the code you're looking for, I also commented some lines for better understanding. // Whenever a checkbox is clicked, execute the following function $('form#formTest input:checkbox').on('click', function(){ // this var will be true when checkbox is marked, false otherwise var isChecked = $(this).prop('checked'); // this var contains the id attribute of the checkbox clicked var idClicked = $(this).attr('id'); // When checkbox is marked, create the div with image inside if (isChecked) { // this var contains the div test element var divTest = $('div#test'); // this var contains the closest img element to the checkbox clicked var image = $('#label'+idClicked+' img'); // Append a div inside div test, with the corresponding image html divTest.append('<div class="imageOne">'+image.prop('outerHTML')+'</div>'); } }); PS: .prop('outerHTML') will work if you're using jQuery 1.6+ Guessing from the link you pasted, I guess you know portuguese. If you have trouble with this english stackoverflow, you can use Portuguese Stackoverflow
{ "pile_set_name": "StackExchange" }
Q: Install Captvty in 16.04 under Wine Looking for a specialized tool to search, watch and download online videos from French tv stations and especially from arte tv, Captvty seems one of the most powerful, the main advantage being that it is able to display all the available titles. But this is a Windows program, and the different methods to install it under Wine seemed obscure and contradictory to me. The idea behind this question is for me to find, test and post here the steps needed to make this program work under Wine in 16.04. A: Playonlinux As the initial Wine-only solution was rather complicated (see below) I have found a Playonlinux solution that I posted on U&L. Wine-only (without Playonlinux) To be sure, remove the previous Wine installation from Synaptic. rm -rf ~/.wine sudo add-apt-repository ppa:ubuntu-wine/ppa -y && sudo apt-get update sudo apt-get install wine1.8 export WINEARCH=win32 At this point winetricks is needed. You can install it with sudo apt-get install winetricks but that version is subject to a possible error described here. To avoid that error the solution is (after removing winetricks if already installed) to use the github link: sudo apt-get remove winetricks wget https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks chmod +x winetricks Then move winetricks file from ~/ to /usr/bin by copy/paste in root file manager or sudo mv winetricks /usr/bin/ Then, the Microsoft XML Parser file is needed. Download it and put it in ~/.cache/winetricks/msxml3 (create folder if it's not there). Run the command: winetricks vcrun2010 dotnet40 gdiplus comctl32 ie8 (If, as indicated in the source link posted at the end, the command is run before installing msxml3, you will be prompted in terminal to download it as indicated above.) Do not approve updates and such from Windows. Download, unpack the Captvty package on your home partition and execute captvty.exe ('open with' - Wine), it should work now. The program has an option to watch the videos without downloading them using internal or external players. The internal player is flashplayer for Windows. To get that and be able to whatch the videos in this way: Go to http://get.adobe.com/en/flashplayer/otherversions/ Download the Windows 7, Internet Explorer version, in ~/ then wine install_flash_player_ax.exe The internal flash player works fine and seems totally preferable to external players, because the Linux native video players cannot be used (only Windows players in Wine). (The latter can only theoretically be used in the same way, on the condition that Wine supports them, and then added through Captvty options. The only one that (kind of) worked when testing was the portable mpv for Windows, but compared to the 'internal' flash player there is a long/huge (5 minutes!) lag between the moment the command to start the video is made and the moment the video starts playing: otherwise it works fine... when it does... but it's not worth the effort: to watch the video use the other methods presented in this answer to get the video url and play it in a native video player.) To search & launch Captvty (from Dash in Unity, krun in KDE, Synapse, etc) and see it among other Internet applications in menu launchers, create a .desktop file like so: Using gedit: gedit ~/.local/share/applications/captvty-wine.desktop and paste this, changing the path to the .exe file for Exec= line: [Desktop Entry] Categories=AudioVideo; Exec=bash -c 'wine /path/to/the/program/folder/captvty-2.5.1/Captvty.exe' Icon=captvty Name=TV Downloader Captvty StartupNotify=true Terminal=false Type=Application Categories=Network;System; To have an icon for that, find a png, name it captvty.png and put it in ~/.local/share/icons Credits: the answer is based on these posts here and here. Version update: Tested the above with 2.3.8.2 version and also with 2.5.1. Testing the more recent 2.5.4.1 the arte 7+ option gave no results, while this worked with the older version.
{ "pile_set_name": "StackExchange" }
Q: MacBook Pro battery and speed issues My sister's MacBook Pro often shuts down at ~20% battery. It won't turn on again until it has been plugged in for about 10 minutes. A: Your battery is in very bad condition. In those cases it's not uncommon that the remaining time is not calculated properly, and your computer will turn off (ungracefully) as soon as the battery can't provide the necessary power levels. You should have your battery looked at and replaced. Depending on the battery age and reason of defect, this might be replaced under warranty. However, if the battery died of age, it likely isn't. Check the battery replacement conditions here: http://www.apple.com/batteries/replacements.html
{ "pile_set_name": "StackExchange" }
Q: Why doesn't a sound file loop in HTML? <embed src="CantinaBand.mp3" autostart="true" loop="true" width="2" height="0"> </embed> I have this line in my HTML file, I want the music to loop once it ends but I can't get it to work. Any ideas? A: Because you're using an old, non-standard tag. You should be using a <audio> tag. <audio src="CantinaBand.mp3" autoplay loop></audio>
{ "pile_set_name": "StackExchange" }
Q: sequelize.js - how to find all items by nested elements attribute? i have two tables, 'places' & 'photos'. each place hasMany photos, and each photo has an attribute called user_id. how can i findAll the places which have photos which have a specific user_id? A: you can use includes option in sequelize places.findAll({ include: [{ models : photos , where : { user_id = xx} }] }) or You can use raw query
{ "pile_set_name": "StackExchange" }
Q: find grid points inside the parallelogram defined by an origin and two vectors I hope someone knows an efficient computational approach to the following 2D problem: Given two vectors $\mathbf{A}$ and $\mathbf{B}$, find all grid points that lie within the parallelogram spanned by these vectors. This feels like it should be a "known" problem, but I lack the vocabulary to search for the right terms. I know how to determine that a given point is inside; I would like not to have to test lots of points... are there any tricks I should know? As I look at the picture, I am thinking "starting at the origin, you need to move to the left to find points; at a certain X coordinate you can go up a step without crossing A". But as A and B can be swapped, and pointing in any direction, the approach I need has to be a little more robust. Ultimately I need to know not only the coordinates, but actually the values of $a$ and $b$ for each valid (green, in the diagram) grid point $\mathbf{P}$ such that $$\mathbf{P} = a\mathbf{A} + b\mathbf{B}$$ for all integer-valued P(i,j) where $a,b \in [0,1\rangle$. If that is actually easier... that's the problem I ultimately need to solve (so I need coordinates (i,j) and their transform (a,b); obviously when I have one, I can find the other). A: I suggest that you break the query into two parts, points_inside(parallelogram) := points_inside(triangle1) union points_inside(triangle2), where the triangles are formed by T(origin,origin+A,origin+A+B) andT (origin,origin+A+B,origin+B). Regarding the find-all-points-in-a-triangle query, this is basically a scanline-conversion problem. You can find solutions in computer-graphics like sources (for drawing triangles onto grids of pixels, that sort of thing). One of the (many) hits for "scanline conversion of a triangle": http://vis.uky.edu/~ryang/Teaching/CS335-spr05/Lectures/g_05_fill.pdf You can probably find better ones. You could probably work with the polygon directly, it'll just be a little more complicated and might be a bit harder to find good tutorials. You could also try drawing the edges into a small image, then do some floodfill-like search until you hit them. Bresenhams is the prototypical algorithm for scanline conversion of a line. A: Depending on the performances that you want, there are an easy and a more complicated algorithm. Algo 1: interior test in bbox (simple) For each point p with integer coordinates in the bounding box of the parallelogram (q1,q2,q3,q4) If sign(det(p-q1, p-q2)) = sign(det(p-q2, p-q3)) = sign(det(p-q3, p-q4)) = sign(det(p-q4, p-q1)) mark p where det( (x1,y1), (x2, y2)) = x1*y2 - x2*y1 denotes the determinant and sign() its sign (positive, zero or negative). Algo 2: scanline rasterization (more delicate) Compute the interval [Ymin Ymax] that bounds the Y's of the parallelogram Determine for each value of Y in [Ymin Ymax] the leftmost XL[Y] and rightmost XR[Y] intersection between the horizontal line and the border of the parallelogram For Y in Ymin ... Ymax For X in XL[Y] ... XR[Y] Mark X,Y Step 2 (computing the scalines) can be done using Bresenham algorithm. The algorithm is described in full details in [1]. The second algorithm was used in early 3D game engines (before graphic boards were available) and is very efficient. More notes (if performance is really an issue) Starting from Algo 1 and refining it, it is possible to obtain an even faster algorithm: the determinant computations can be split into what depends on X and what depends on Y, and one can compute at the beginning of the loop how the determinant vary. Then in the loop there are only additions and sign comparisons to do. The method is fully detailed in [2] (excellent article by Nick Capens, who implemented a full software emulation of DirectX 10 compatible graphic boards ages ago). [1] http://www.idav.ucdavis.edu/education/GraphicsNotes/Rasterizing-Polygons/Rasterizing-Polygons.html [2] http://forum.devmaster.net/t/advanced-rasterization/6145
{ "pile_set_name": "StackExchange" }
Q: Удаление класса при наведении Здравствуйте! Есть блок у которого изначально есть внутренняя тень(inset). Так же внутри этого блока есть кнопка, которая скрыта с помощью класса .dspNone. Необходимо чтобы при наведении на блок, тень внутри блока исчезла, а кнопка появилась(для этого я так понимаю необходимо удалить класс .dspNone у кнопки). На данный момент получилось сделать следующее,при наведении тень пропадает, но кнопка почему-то не появляется. Или это по другому делается? .block:hover { box-shadow: none; } .dspNone { display: none; } .block { box-shadow: 0 0 0 99999px rgba(0, 0, 0, 0.8) inset; } .block { background: red; } .block:hover > .btn1 { display: block; } .block:hover > .text { display: none; } .text { padding-top:10px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block" style="width: 50px; height: 50px"> <p class="text">TextText</p> <button class="dspNone btn1">Кнопка</button> </div> A: Можно сделать на css, так : .block:hover > .btn1 { display: block; } Если же все-таки нужен jquery : $(".block").hover(function() { $('.btn1').removeClass("dspNone"); }); $(".block").mouseleave(function() { $('.btn1').addClass("dspNone"); }); .block:hover { box-shadow: none; } .dspNone { display: none; } .block { box-shadow: 0 0 0 99999px rgba(0, 0, 0, 0.8) inset; } .block { background: red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block" style="width: 50px; height: 50px"> <button class="dspNone btn1">Кнопка</button> </div> По комментарию и уточнениям в вопросе, я смог сделать так (нарыл на enSO): .block:hover { box-shadow: none; } .dspNone { display: none; } .block { width: 60px; height: 50px; display: -ms-flexbox; display: -webkit-flex; display: flex; -ms-flex-align: center; -webkit-align-items: center; -webkit-box-align: center; align-items: center; box-shadow: 0 0 0 99999px rgba(0, 0, 0, 0.8) inset; } .block { background: red; } .block:hover>.btn1 { display: block; } .block:hover>.text { display: none; } .text { color: red; } <div class="block"> <p class="text">TextText</p> <button class="dspNone btn1">Кнопка</button> </div>
{ "pile_set_name": "StackExchange" }
Q: Open and edit in google drive from my php-application users can upload files from my php-application which are to be stored in my google drive. users need to view those documents and are able to update the files.how can i make this possible.i am new to google apis.please help me. thanks in advance for any answers A: You can give the users editor permissions on those files. Look at the permissions.insert method of the Drive API. You will create a permission for every user who need to be able to edit the file, and then they can edit it in Google Drive.
{ "pile_set_name": "StackExchange" }
Q: Adding numbers found in a Json object I have a Json object that I am parsing and then comparing to another array to find where they match. I have the code to this point, var gpaGrades = '{"A": 4, "A-": 3.67, "B+": 3.33, "B": 3, "B-": 2.67, "C+": 2.33, "C": 2, "C-": 1.67, "D+": 1.33, "D": 1, "D-": 0.67, "F":0}'; var letterGrades = ["A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-"] var fallGrades = ["Fall 2015", "A-", "B+", "A", "B", "A"]; var springGrades = ["Spring 2016", "A+", "A+", "A-", "B+", "A"]; var gpa = JSON.parse(gpaGrades); var sum = 0; function getGrades(semester){ if(semester === "Fall 2015"){ for (var i = 1; i < fallGrades.length; i++) { for(var x = 0; x < letterGrades.length; x++){ if (letterGrades[x].indexOf(fallGrades[i]) >= 0) { var getGPA = fallGrades[i]; console.log(gpa[getGPA]); } } } } } This works and gives me all the values that match the letter grades and their corresponding point values. The problem is I need to get a sum of the gpa[getGPA] values to then calculate the GPA for that semester that I will then divide by the length. I have tried var sum += gpa[getGPA]; Not sure why this won't work as I saw a similar example with just an array of ints working fine. Thanks for any help. A: Don't use var inside the loop, this re-declares sum each time. Use var outside the loops (should still work inside the function). And then use sum += gpa[getGPA]; inside the loops.
{ "pile_set_name": "StackExchange" }
Q: Continuity of anti-derivative multivariate functions I just need some hints to solve the following problem. Let $f(x_1,\ldots, x_n)$ be a continuous and integrable function on $\mathbb{R}^n.$ Is the function $$ g(x_1,\ldots, x_{n-1}) = \int \limits_{-\infty}^{\infty}f(x_1,\ldots, x_n)\,dx_{n} $$ continuous on $\mathbb{R}^{n-1}$? If it is, how can I prove that? Thanks in advance! A: Suppose on $\mathbb {R}^2$ we set $f(x,y) = \exp[-|y||x|^{1/2}(1+x^2)].$ Then $f$ is continuous and integrable on $\mathbb {R}^2$ (see below), but if $$g(x) = \int_{-\infty}^\infty f(x,y)\,dy,$$ then $g(0)=\infty,$ so $g$ is not continuous on $\mathbb {R}.$ (To see $f$ is integrable on $\mathbb R ^2,$ integrate first with respect to $y,$ making the change of variables $y = t/[|x|^{1/2}(1+x^2)],$ and then integrate with respect to $x.$ We are using Fubini here.)
{ "pile_set_name": "StackExchange" }
Q: Apply hash pattern to polygon in openlayers I am creating a vector layer comprised of polygons from a KML file using Openlayers and I need to apply a "hash" pattern (diagonal striping) to the polygons. I know Openlayers doesn't natively support adding a background image to a polygon in a vector layer but I'm wondering if anyone has any ideas on how to accomplish this? The styling of a vector polygon appears to be limited to solid colors and opacity. If need be I'll extend OpenLayers to add this functionality in by manually drawing the hash lines within the polygon boundaries but I'm hoping someone has a simpler suggestion before I head down that road. A: Using SLD this can now be done. Not sure if it's in version 2.11 or the trunk development but i saw the addition was committed about 6 months ago. It uses an ExternalGraphic so you can set an image of whatever pattern or color you want. Here's the Example
{ "pile_set_name": "StackExchange" }
Q: How do I make an Arraylist accessible to many classes? I'm making a vertical shooter game and I am having trouble with collision detection. Collisions are detected through the Rectangle method "intersect", but in order to keep track of everything that could collide, I need Arraylists to keep track of all the bullets and enemy ships. The Enemy and Player class both spawn Bullets (which also have there own class) so I would like to have 2 different Arraylists in my GameView class (which controls the games graphics and hopefully collisions when I'm done here). What would be the most efficient way to allow the Bullets to be added to their respective ArrayLists upon being spawned? Bullet class: public class Bullet extends Location{ private Fights bulletOwner; private int damage; private int velocity; public Bullet(Fights owner, int dmg, Rectangle loca) { super(loca); bulletOwner = owner; damage = dmg; } public Fights getOwner(){return bulletOwner;} public int getDamage(){return damage;} public int getVelocity(){return velocity;} } Location class import java.awt.Rectangle; public class Location { protected Rectangle loc; public Location (Rectangle location) { loc = location; } public Rectangle getLocation() { return loc; } public void updateLocation(Rectangle location) { loc = location; } } A: You can have a GameState class that has the arraylist of locations and pass the GameState instance as an argument to the constructor of the Location derived classes.
{ "pile_set_name": "StackExchange" }
Q: are session variables in php confidential suppose if I where to store the query of a url using $_GET['query'] and finally convert into a session variable $_SESSION['var'] and post it on webpage if I have different queries will different people see same or different query? Also if the same person is using different queries will he say the same or different one? A: Anything you store in $_SESSION is specific to that session and nothing in $_SESSION is directly accessible to any user, it is only accessible if you make it accessible, for instance with an echo. However, sessions are identified by a session identifier (also called an sid) which is passed back and forth between the server and the user (usually in a cookie, sometimes in the query string in the URL). Session hijacking occurs when someone other than the person who initiated the session gets a hold of the sid and is then able to make a request using the same session. In this case, they will have access to anything that the legitimate user has access to. So in this case, no they are not confidential. There are lots of ways to protect against session hijacking, the best being to use secure connections (HTTPS). But that's a different question. What a person sees depends on how you're presenting it. Showing us some sample code would help clarify things. For instance, if you do: <?php session_start(); if(isset($_SESSION["query"])) { echo $_SESSION["query"]; } $_SESSION["query"] = $_GET["query"]; ?> Then the user will always see the query they sent with the last request. Honestly, it sounds like you're a little confused over what what a query is and what a session is. If you can clarify what you're trying to do, and especially if you can provide some sample code, we might be able to help you more.
{ "pile_set_name": "StackExchange" }
Q: hamburgermenu checkbox doesn't get unchecked if i click far away to keep it short and simple: My hamburger menu doesn't close if i click somewhere else. I tried it in jquery and tried to make it with removeClass and so on, but even with removeClass it didnt work. Here's the code: https://jsfiddle.net/dtgd551q/ And i think to just uncheck the checkbox is the simplest way to do it. Thanks to everyone who can give me help. A: You can do this : $(document).on('click', function(e){ if(e.target.type == "checkbox") return; else{ var elem = $('#menuToggle').find('input[type=checkbox]'); if($(elem).prop('checked')){ $(elem).trigger('click'); } } }); body { overflow-x: hidden; margin: 0; padding: 0; font-family: "Avenir Next", "Avenir", sans-serif; } a { text-decoration: none; color: white; transition: color 0.1s ease; } a:hover { color: black; } nav { display: inline-block; } #menuToggle { display: block; position: relative; top: 50px; left: 50px; z-index: 1; -webkit-user-select: none; user-select: none; } #menuToggle input { display: block; width: 40px; height: 32px; position: absolute; top: -7px; left: -5px; cursor: pointer; opacity: 0; /* hide this */ z-index: 2; /* and place it over the hamburger */ -webkit-touch-callout: none; } /* * Just a quick hamburger */ #menuToggle span { display: block; width: 33px; height: 4px; margin-bottom: 5px; position: relative; background: black; border-radius: 3px; z-index: 1; transform-origin: 4px 0px; transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0), background 0.5s cubic-bezier(0.77,0.2,0.05,1.0), opacity 0.55s ease; } #menuToggle span:first-child { transform-origin: 0% 0%; } #menuToggle span:nth-last-child(2) { transform-origin: 0% 100%; } /* * Transform all the slices of hamburger * into a crossmark. */ #menuToggle input:checked ~ span { opacity: 1; transform: rotate(45deg) translate(-2px, -1px); background: white } /* * But let's hide the middle one. */ #menuToggle input:checked ~ span:nth-last-child(3) { opacity: 0; transform: rotate(0deg) scale(0.2, 0.2); } /* * Ohyeah and the last one should go the other direction */ #menuToggle input:checked ~ span:nth-last-child(2) { opacity: 1; transform: rotate(-45deg) translate(0, -1px); } /* * Make this absolute positioned * at the top left of the screen */ #menu { position: absolute; width: 400px; margin: -100px 0 0 -50px; padding: 50px; padding-top: 125px; background: black; list-style-type: none; -webkit-font-smoothing: antialiased; /* to stop flickering of text in safari */ transform-origin: 0% 0%; transform: translate(-100%, 0); transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0); } #menu li { padding: 10px 0; font-size: 22px; } /* * And let's fade it in from the left */ #menuToggle input:checked ~ ul { transform: scale(1.0, 1.0); opacity: 1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav role="navigation"> <div id="menuToggle"> <input type="checkbox" /> <span></span> <span></span> <span></span> <ul id="menu"> <a href="#"><li>Home</li></a> <a href="#"><li>About</li></a> <a href="#"><li>Info</li></a> <a href="#"><li>Contact</li></a> <a href="#"><li>Contact</li></a> <a href="#"><li>Contact</li></a> <a href="#"><li>Contact</li></a> <a href="#"><li>Contact</li></a> <a href="https://erikterwan.com/" target="_blank"><li>Show me more</li></a> </ul> </div> </nav> You can detect click on any part of the page except the checkbox as click on checkbox is already working. So, return command inside e.target.type == "checkbox" confirms that the clicked element is not the checkbox. Now, if it's not checkbox then check if the menu is already opened. If it is opened then $(elem).trigger('click'); will generate a click on the checkbox which will close it.
{ "pile_set_name": "StackExchange" }
Q: While form is processing show spinner gif I have a form that takes about 15 seconds to process and would like to show a spinner gif once the form is submitted and remove it once the form is complete. Also the form redirects to a new page and was wondering what the best method is to accomplish this? Should I be submitting this form with Ajax? Thanks in advance for your advice! A: Yes, you can do it via ajax.. Use this ajaxStop() and ajaxStart() to show and hide your animation while ajax request is processing.
{ "pile_set_name": "StackExchange" }
Q: Java: Instantiated object variable error i have a problem that i'm afraid is very simple, yet i can't figure it out even with the help of lectures and tutorials. I have this piece of code to create a class with some variables: public class Symbol { public String sign; public boolean win; } I then want to instantiate the class as an object and set its variables to a certain value like this: Symbol x = new Symbol(); x.sign = "Rock"; x.win = true; I did this exactly like the lecture i took said, but still i get the following error: "<identifier> expected" What am i doing wrong? There was no identifier declared in any example i looked at. I am breaking my head over this for several hours now and - as embarresing as that is - i am at my wits end. Please help. On a side note: I am using BlueJ to compile and run the code - if that is of any relevance. Thanks a lot A: You were all right. The problem was, infact, with BlueJ. When I ran the code with another editor it worked as intended. I guess I know what I take away from this one ... Still, thanks for all your answers.
{ "pile_set_name": "StackExchange" }
Q: Powershell: tablet output to string of lines with one space $allSoftwareObj = Get-WmiObject -Class Win32_Product | Select-Object -Property Name, Version | ft -HideTableHeaders | ft -Wrap -AutoSize -Property Name, Version $allSoftware = Out-String -InputObject $allSoftwareObj echo $allSoftware When I output this, I get a table structure. I don't want that. How to get a new line per new output with only space between the Name and Version? Wrong output now: Microsoft SQL Server System CLR Types 10.51.2500.0 SQL Server 2012 Client Tools 11.1.3000.0 Wanted output: Microsoft SQL Server System CLR Types 10.51.2500.0 Or: Microsoft SQL Server System CLR Types (10.51.2500.0) A: Try replacing the whole line with this: Get-WmiObject -Class Win32_Product | % {"$($_.Name) ($($_.Version))"}
{ "pile_set_name": "StackExchange" }
Q: How To Create Equal Height Columns with CSS only and without flexbox? I have 3 columns in my footer (f-box). I want them to have equal height. I don't want to use flexbox for this one. I am trying to achieve the result using - display:table on my container of the boxes and make display:table-cell for every box. But it doesn't work. Why? How to do it with this display: table method @import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700;800&family=Quantico:wght@400;700&display=swap"); * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: "Open Sans", sans-serif; line-height: 1.5; } h1, h2, h3, h4, h5, h6 { font-family: "Quantico", sans-serif; margin-bottom: 20px; } p { font-size: 15px; color: #666; line-height: 26px; margin-bottom: 15px; } a { font-family: "Quantico", sans-serif; text-decoration: none; color: #111; } ul { list-style: none; } img { width: 100%; display: block; } /* Theme */ .container { margin: auto; max-width: 1500px; padding: 0 15px; } .logo { font-size: 30px; padding: 20px 0; float: left; margin: 0; } .main-color { color: #009603; } .btn { display: inline-block; text-transform: uppercase; background: #009603; color: #fff; padding: 14px 30px; font-weight: 700; } /* Nav */ nav { overflow: hidden; text-transform: uppercase; } nav ul { float: right; } nav ul li { float: left; margin-right: 32px; position: relative; } nav ul li a { display: block; padding: 31px 8px; font-weight: 700; } nav ul li a:after { position: absolute; left: 0; bottom: 0; height: 3px; width: 100%; background: #009603; content: ""; opacity: 0; transition: all 0.3s; } nav ul li.active a:after { opacity: 1; } nav ul li:hover > a:after { opacity: 1; } /* Showcase */ #showcase { background: url("../img/bg.jpg") no-repeat center center/cover; height: 900px; } #showcase .showcase-content { color: #fff; text-align: center; padding-top: 300px; } #showcase .showcase-content h2 { font-size: 60px; font-weight: 700; text-transform: uppercase; } #showcase .showcase-content p { margin-bottom: 30px; line-height: 30px; color: #fff; } /* Features */ #features { padding-bottom: 60px; } #features .container { margin-top: -70px; max-width: 1400px; overflow: hidden; } #features .box { background: #fff; float: left; max-width: 30%; margin: 0 15px 30px 15px; padding: 10px 10px 18px 10px; box-shadow: 0px 10px 25px rgba(206, 206, 206, 0.5); text-align: center; } #features .box img { margin-bottom: 28px; } #features .box h3 { color: #191039; font-weight: 700; text-transform: uppercase; margin-bottom: 10px; font-size: 30px; } /* Footer */ footer { padding-top: 70px; overflow: hidden; background-color: #000; } footer .container { max-width: 1400px; display: table; } footer .f-box { display: table-cell; float: left; max-width: 33.3%; margin-bottom: 30px; padding: 0 15px; } footer .logo { padding-top: 0; color: #fff; text-transform: uppercase; float: none; } footer p { color: #c4c4c4; margin-bottom: 20px; } footer .social i { color: #fff; margin-right: 20px; } footer h5 { color: #fff; text-transform: uppercase; font-size: 20px; font-weight: 700px; margin-bottom: 35px; padding-top: 5px; } footer img { float: left; width: calc(33.33% - 5px); margin-right: 5px; } footer form { position: relative; } footer input { width: 100%; height: 50px; font-size: 15px; color: #c4c4c4; padding-left: 20px; border: 1px solid #009603; background: transparent; } footer form button { font-size: 18px; color: #fff; background: #009603; height: 50px; width: 50px; border: none; position: absolute; right: 0; top: 0; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Pacocha | Garden Projects</title> <link rel="stylesheet" href="css/style.css" /> <script src="https://kit.fontawesome.com/1685e275a4.js" crossorigin="anonymous" ></script> </head> <body> <header> <nav> <div class="container"> <a href="index.html"> <h1 class="logo"><i class="fas fa-leaf main-color"></i> Pacocha</h1> </a> <ul> <li class="active"><a href="index.html">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="services.html">Services</a></li> </ul> </div> </nav> <div id="showcase"> <div class="container"> <div class="showcase-content"> <h2>Garden Projects</h2> <p> We have the best home improvement projects, expert advice, and DIY home improvement ideas for your home. <br /> You can create your dream home with smart planning and the right home improvement contractors. </p> <a href="about.html" class="btn">About Us</a> </div> </div> </div> </header> <!-- Features --> <section id="features"> <div class="container"> <div class="box"> <img src="img/feat1.jpeg" alt="" /> <h3>Gardening</h3> <p> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Maiores magnam reprehenderit aspernatur neque nam ipsum enim, vitae minus totam voluptates. </p> </div> <div class="box"> <img src="img/feat2.jpg" alt="" /> <h3>Decorating</h3> <p> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Maiores magnam reprehenderit aspernatur neque nam ipsum enim, vitae minus totam voluptates. </p> </div> <div class="box"> <img src="img/feat3.jpg" alt="" /> <h3>Ideas</h3> <p> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Maiores magnam reprehenderit aspernatur neque nam ipsum enim, vitae minus totam voluptates. </p> </div> </div> </section> <footer> <div class="container"> <div class="f-box"> <h1 class="logo"><i class="fas fa-leaf main-color"></i> Pacocha</h1> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione corporis nostrum ex perferendis! Adipisci, molestias. </p> <div class="social"> <a href="index.html"><i class="fab fa-facebook-f"></i></a> <a href="index.html"><i class="fab fa-twitter"></i></a> <a href="index.html"><i class="fab fa-youtube"></i></a> <a href="index.html"><i class="fab fa-instagram"></i></a> </div> </div> <div class="f-box"> <h5>Instagram</h5> <img src="img/insta1.jpg" alt="" /> <img src="img/insta2.jpg" alt="" /> <img src="img/insta3.jpg" alt="" /> </div> <div class="f-box"> <h5>Subscribe</h5> <p> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Necessitatibus, vel? </p> <form action=""> <input type="email" placeholder="Email" /> <button type="submit"><i class="fa fa-send"></i></button> </form> </div> </div> </footer> </body> </html> A: you just need this css footer { padding: 70px 0; } footer .f-box { display: table-cell; float: none; width: 33.3%; margin-bottom: 30px; /*the margin property is not applicable to display:table-cell elements.*/ padding: 0 15px; } and it will behave like this - equal column height
{ "pile_set_name": "StackExchange" }
Q: Improving the linearity of a potentiometer after loading I could not understand why is adding 'Rlin' in the second figure improves the linearity of the system? A little help pls! A: The highest output resistance of the pot connected as a voltage divider is at mid-rotation and it is obviously Rpot/4, since the resistance of the two halves is in parallel to stiff voltage sources. By connecting a resistor equal to the load to the opposite rail you can reduce the nominal error at mid-rotation to zero. You are still left with the 'S'-shaped residual error that is maximum around 1/4 and 3/4 rotation. That's the hand-waving explanation that should be intuitively useful, but if you want to get real numbers, you can run the rather simple math through Scilab, Excel, a C program, or whatever. This being Q2 2016 (as of this writing), in many cases it's just as easy to throw an op-amp buffer at the problem and then the loading becomes just the bias current of the op-amp. There may be other problems (the op-amp may not be able to work right to the rails, for example, or the offset drift of the op-amp may be much worse than the pot) but nonlinearity due to loading is pretty much eliminated.
{ "pile_set_name": "StackExchange" }
Q: Access violation in delphi-7 OK i'm writing an educational program that uses different forms. This is the first time i'm coding with multiple form as i'm still a novice programmer. when my "sign in" button is clicked it opens the new form but then displays an access violation code. unit SignInNew_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, xpman; type TSignInNew = class(TForm) Panel1: TPanel; Label2: TLabel; Label3: TLabel; Label1: TLabel; Label4: TLabel; edtName: TEdit; edtSurname: TEdit; btnSignIn: TButton; help: TButton; procedure btnSignInClick(Sender: TObject); procedure helpClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var SignInNew: TSignInNew; implementation uses HelpNew_u, ElementsNew; {$R *.dfm} procedure TSignInNew.btnSignInClick(Sender: TObject); var sName,sSurname,text:string; User:TextFile; begin ElementsNew.TMain.Create(self); ElementsNew.Main.Show; Main.WindowState:= wsMaximized; end; procedure TSignInNew.helpClick(Sender: TObject); begin HelpNew := THelpNew.Create(self); HelpNew.Show; HelpNew.Width:=281; HelpNew.Height:=481; end; end. This is how it looks any help would be appreciated. A: Looking your code, you are instantiating a class (TMain) ElementsNew.TMain.Create(self); but never assigning it to a variable. You are using a nil var (Main) ElementsNew.Main.Show; Main.WindowState:= wsMaximized; To solve this: Main := ElementsNew.TMain.Create(self); Main.Show;
{ "pile_set_name": "StackExchange" }
Q: Why is Visual Studio 2013 not willing to run my Web Performance / Load Test? I am attempting to run a simple Web Performance Test that I recorded in Visual Studio 2013 Ultimate. I click the 'Run Load Test' icon inside of VS, only to be greeted with the following error details: An unexpected error occurred. Please close this page and re-open it using Load Test Manager, available in the Load Test menu. Failed to queue test run [test name] The active test settings is configured to run test using Visual Studio Online. Connect to a Visual Studio Online account using Team Explorer and try again. I then click on Load Test > Load Test Manager, only to receive another error: The action you are trying to perform requires a connection to Visual Studio Online. Connect to a Visual Studio Online account using Team Explorer and try again. Thing is, I just want to run my test on the local network; I don't want to use cloud-based testing right now. What am I doing wrong? Where can I change my active test settings not to use Visual Studio Online? A: According to Visual Studio: Load testing in the cloud, here are the steps to switch the test from using Visual Studio Online to running locally: Simply open your existing project using Visual Studio 2013 first. Within the Solution Explorer, expand the 'Solution Items' folder, then open Local.testsettings. Edit the test settings file to configure your project to run your tests on the local computer. A: You can have more than one ".testsettings" file. On a recent project we used three Local.testsettings - for test development and low load tests driven entirely from one computer. Agent.testsettings - for testing with a controller plus two agents, for bigger loads. Cloud.testsettings - for running tests on Visual Studio Online. To switch between the three files use the context (right click) menu in solution explorer and "tick" the "Active load and web test settings" entry.
{ "pile_set_name": "StackExchange" }
Q: MySQLi & fetch_all(MYSQLI_ASSOC) Returns nothing In phpMyAdmin, I can use the following SQL without errors, and I get a table with 3 entries: SELECT * FROM ticket_orders WHERE 1 However, when I run this php code: $quickDbConn = new mysqli($dbHost, $dbUser, $dbPass, $dbName); $result = $quickDbConn->query('SELECT * FROM ticket_orders WHERE 1'); var_dump($quickDbConn); var_dump($quickDbConn->client_info); var_dump($quickDbConn->client_version); var_dump($quickDbConn->info); var_dump($result); var_dump(!!$result); var_dump(MYSQLI_ASSOC); var_dump($result->fetch_all(MYSQLI_ASSOC)); $quickDbConn->close(); I get the following output: object(mysqli)#1 (19) { ["affected_rows"]=> int(3) ["client_info"]=> string(6) "5.5.30" ["client_version"]=> int(50530) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(7) ["host_info"]=> string(23) "xx.xx.xxx.xx via TCP/IP" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(6) "5.5.30" ["server_version"]=> int(50530) ["stat"]=> string(144) "Uptime: 156684 Threads: 1 Questions: 2835826 Slow queries: 36 Opens: 19439 Flush tables: 1 Open tables: 64 Queries per second avg: 18.099" ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(74151) ["warning_count"]=> int(0) } string(6) "5.5.30" int(50530) NULL object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(7) ["lengths"]=> NULL ["num_rows"]=> int(3) ["type"]=> int(0) } bool(true) int(1) Can anyone explain to me why $result->fetch_all(MYSQLI_ASSOC) is returning nothing? Or how I can fix this? A: It won't work because fetch_all work only with mysqlnd. However if you want to get query result as enumerated array and associative array at the same time, you have to use fetch_array(MYSQLI_BOTH) that would do. fetch_array()
{ "pile_set_name": "StackExchange" }
Q: ABAP free internal table The answer to the question below is given as 2. Why does refresh delete only the first row? Is it not expected that it deletes all rows of an internal table? What will be output by the following code? DATA: BEGIN OF itab OCCURS 0, fval type i, END OF itab. itab­-fval = 1. APPEND itab. itab­-fval = 2. APPEND itab. REFRESH itab. WRITE: /1 itab­-fval. A: 1 B: 2 C: blank D: 0 Answer: B A: If the code did not contain any syntax errors, e.g. the missing '-' when assigning the value 2 and when writing the value, then B is the correct answer but not for the reason you state. It is not that the REFRESH only removes the first line from the table, it is because REFRESH does not clear the header line of the table. So after the REFRESH the header line still has the latest assigned value which is 2. This can be easily ascertained when running the program in the debugger. Note that the use of internal table with header lines is obsolete, as mentioned in SAP help.
{ "pile_set_name": "StackExchange" }
Q: Can I autologin someone directly in app? So let's say I have 2 apps., basically 2 different targets , and I'm currently in the main one logged in , receiving a response from the server with a field that includes also the "user_id" . The question is if I can redirect the user to the other target ( open the other app if installed ) and forge a login based on the "user_id" which acctually is the user_id of that specific user for the second app. I managed to open the other app, but could I force autologin the user and also open another VC and not the initial one. Please ask me if you want more informations. Thanks A: Suppose you want to go from firstApp to secondApp, you have to call secondApp:// url to open the other app, now after the //, you can specify more information in firstApp, In your case , user_id: secondApp://<Append your user_id here> After this, you can handle this in your secondApp in AppDelegate like this: func application(_ application: UIApplication, handleOpen url: URL) -> Bool { //Handle the url here //Extract the user_id from url return true } Hope it helps!!
{ "pile_set_name": "StackExchange" }
Q: Beforeunload event does not fire after page refresh Chrome I have this simple code <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <!--<script src="angular.min.js"></script>--> <script> window.onload = function () { window.addEventListener("unload", function () { debugger; }); window.addEventListener("beforeunload", function () { debugger; }); window.onbeforeunload = function () { } } </script> </head> <body ng-app="app"> </body> </html> I want unload or beforeunload events be fired after I refresh the page. This is not happening in Chrome Versión 67.0.3396.62. I have tried firefox and edge and it works well. It also works when i close the tab. The error ocurrs only when i refresh the page. A: You've run into an issue that was already reported. It looks like a bug, but according to a Chrome dev (kozy) it is a feature: Thanks for repro. It is actually feature. As soon as you pressed reload we ignore all breakpoints before page reloaded. It is useful all the time when you have a lot of breakpoints and need to reload page to restart debugging session. Workaround: instead of pressing reload button you can navigate to the same url using omnibox then all breakpoint will work as expected. I've added bold emphasis to point out the workaround proposed by kozy. I've tried it and found that it works. Other than the issue with the debugger statement, the handlers are executed whether you are reloading or closing the tab. In both cases that follow, I get the stock prompt that Chrome provides when returning true: window.addEventListener("beforeunload", function (ev) { ev.returnValue = true; // `return true` won't work here. }); This works too: window.onbeforeunload = function () { return true; } It used to be that you could use a return value with a message and the browser would show your custom message but browsers generally no longer support this. Whether or not you want to set the handler for beforeunload inside a handler for load is entirely dependent on your goals. For instance, I have an application for editing documents that does not set the beforeunload handler until the application has started initializing, which is much later than the load event. The beforeunload handler is there to make sure the user does not leave the page with unsaved modifications.
{ "pile_set_name": "StackExchange" }
Q: How to change spatial resolution using gdalwarp? I just realized that I have Geo-TIFF's in the same coordinate system but different spatial resolution. DOP20 (20cm=1px) and DOP10 (10cm=1px) mix. Now wanted to use gdalwarp to transform the DOP20 TIFF into DOP 10. The commandline should be simple gdalwarp.exe -tr 20000 20000 -r bilinear in.tiff out.tiff but gdalwarp complains: Creating outputfile that is 0Px0L Error 1 Attempt to create 0x0 dataset... I thought it is a simple graphics operation, "blowing" a 10000x10000 pixel TIFF into a 20000x20000 pixel TIFF. Can anybody help me understand what's wrong here? A: You don't say what your coordinate system is, but if it's in meters, your -tr arguments should be -tr 0.1 0.1. -tr sets the resolution (m), not the image size (cols/rows.) Just guessing but GDAL is probably complaining because you're trying to create an image that occupies less than 1 cell. A: If your source dataset has a size of 10000x10000 Pixels, the command line should be gdalwarp.exe -ts 20000 20000 -r bilinear in.tiff out.tiff or gdal_translate -outsize 20000 20000 -r bilinear in.tiff out.tiff
{ "pile_set_name": "StackExchange" }
Q: Where (UK) can we rent an adult tricycle or recumbent tricycle There are a lot of cycle tracks (mostly old railway lines) in the UK that have bike rental, however very few of them have adult tricycle or recumbent tricycle. Does anyone have the list of where you can rent an adult tricycle in the UK? A: Where abouts in the UK are you? You might want to check out the following places: London Recumbants - http://www.londonrecumbents.co.uk/bikes_we_hire.html DTek - don't have a web site but can be emailed on [email protected] FutureCycles - futurecycles.co.uk Hope you get sorted.
{ "pile_set_name": "StackExchange" }
Q: Spring boot multi tenancy per schema issue I'm creating the app with multi-tenant support. I did as done in this project on GitHub: https://github.com/singram/spring-boot-multitenant It works fine while manually add schema and tables for it. It sets up schema name automatically. But how I can generate schemas programmatically, not manually? P.S: I want generate schema for user after his registration in the system. A: To update schema manually you should use SchemaUpdate class of hibernate along with this you will have to create a reference of StandardServiceRegistry interface which will have the information regarding database connectivity and MetadataImplementor reference. Use MetadataSources to create reference of MetadataImplementor. We need to tell hibernate that to create tables for these classes for this MetadataSources provides method addAnnotatedClass(). Here is the example: try { Map < String, String > map = new HashMap < String, String > (); map.put(Environment.HBM2DDL_AUTO, "update"); map.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect"); map.put(Environment.DRIVER, "com.mysql.jdbc.Driver"); map.put(Environment.URL, "jdbc:mysql://localhost:3306/" + databaseName); map.put(Environment.USER, "root"); map.put(Environment.PASS, "root"); map.put(Environment.SHOW_SQL, "false"); StandardServiceRegistry ssr = new StandardServiceRegistryBuilder() .applySettings(map) .build(); try { MetadataSources metaDataSource = new MetadataSources(ssr); Set < Class << ? extends Object >> classes = getClassInPackage("com.domain"); for (Class << ? extends Object > c : classes) { metaDataSource.addAnnotatedClass(c); } final MetadataImplementor metadata = (MetadataImplementor) metaDataSource .buildMetadata(); metadata.validate(); SchemaUpdate su = new SchemaUpdate(ssr, metadata); su.setHaltOnError(true); su.setDelimiter(";"); su.setFormat(true); su.execute(true, true); } finally { StandardServiceRegistryBuilder.destroy(ssr); } } catch (GenericJDBCException e) { e.printStackTrace(); } The above code uses MYSQL database configuration . To get entity classes in a package i have used reflections . you can add below dependency to your pom.xml <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.11</version> </dependency> And the code for getClassInPackage() method is as below: private Set < Class << ? extends Object >> getClassInPackage(String packagePath) { Reflections reflections = new Reflections(packagePath, new SubTypesScanner(false)); Set < Class << ? extends Object >> allClasses = reflections.getSubTypesOf(Object.class); return allClasses; }
{ "pile_set_name": "StackExchange" }
Q: Linear dependency in certain fields EDIT: I made a vital mistake switching $4$ by $3$ Let $q$ be a prime number and $n\in\mathbb{N}$. Suppose that $q^n\equiv 1\pmod{3}$. Is it possible that there are $0\neq a,b\in \mathbb{F}_{q^n}$ and $0\neq\lambda,\mu\in\mathbb{F}_q$ $$\lambda a+\mu b=0,\lambda a^4+\mu b^4=0,a\neq b$$ A: Solve the equation: $$\lambda a +\mu b=\lambda a^3+\mu b^3\implies \lambda a(a-1)(a+1)+\mu b(b-1)(b+1)=0$$ and thus you can easily check that $\;a=0, b=1\;$ solve the question, for example...and there are several more solutions, and it isn't that important that $\;q^n=1\pmod3\;$ If it must be that $\;ab\neq0\;$ , then choose $\;a=1\,,\,\,b=-1\;$ , which are different unless $\;q=2\;$ . A: With all the variables non-zero the former equation gives $$ \lambda/\mu=-a/b $$ and the latter equation gives $$ \lambda/\mu=-a^4/b^4. $$ So for solutions to exist we must have $-a/b=-a^4/b^4$, or $a^3/b^3=1$ or, equivalently $$a=\omega^j b,$$ where $\omega\in\Bbb{F}_{q^n}$ is a third root of unity (exists, because $3\mid q^n-1$), and $j=0,1$ or $2$. The case $a=b$ was excluded, so we are left with $a=\omega b$, and $a=\omega^2 b$. But, we also have $\lambda/\mu=-\omega^j$, $j=1,2$. Because $\lambda/\mu\in\Bbb{F}_q^*$ we therefore need the third roots of unity to reside in $\Bbb{F}_q$. For solutions to exist it is thus necessary that $q\equiv1\pmod 3$. On the other hand, $\omega\in\Bbb{F}_q$ is clearly a sufficient condition for the existence of solutions. We can simply set $b=\omega a$, $\lambda=-\omega\mu$, and both equations will hold. Solutions $(a,b,\mu,\lambda)$ such that all the variables are non-zero and $a\neq b$ exist if and only if $q\equiv1\pmod3$.
{ "pile_set_name": "StackExchange" }
Q: System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached I just updated to the latest ASP.NET MVC and I am getting: Method not found: 'System.Web.Routing.RouteValueDictionary System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached(System.Object)'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: Method not found: 'System.Web.Routing.RouteValueDictionary System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached(System.Object)'. Source Error: Line 12: public static void RegisterRoutes(RouteCollection routes) Line 13: { Line 14: routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); Line 15: Line 16: //routes.MapRoute( Source File: C:\ProjectX\App_Start\RouteConfig.cs Line: 14 Stack Trace: [MissingMethodException: Method not found: 'System.Web.Routing.RouteValueDictionary System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached(System.Object)'.] System.Web.Mvc.RouteCollectionExtensions.CreateRouteValueDictionaryUncached(Object values) +0 System.Web.Mvc.RouteCollectionExtensions.IgnoreRoute(RouteCollection routes, String url, Object constraints) +94 System.Web.Mvc.RouteCollectionExtensions.IgnoreRoute(RouteCollection routes, String url) +7 COP.RouteConfig.RegisterRoutes(RouteCollection routes) in C:\ProjectX\App_Start\RouteConfig.cs:14 COP.MvcApplication.Application_Start() in C:\ProjectX\Global.asax.cs:27 [HttpException (0x80004005): Method not found: 'System.Web.Routing.RouteValueDictionary System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached(System.Object)'.] System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9935033 System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118 System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172 System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336 System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296 [HttpException (0x80004005): Method not found: 'System.Web.Routing.RouteValueDictionary System.Web.WebPages.TypeHelper.ObjectToDictionaryUncached(System.Object)'.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9913572 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254 I have followed this guide: http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2 I even 2nd passed the DLL list in the document as a check list to make sure I didn't miss anything. However, I am apparently missing something. A: Try revert you Web.config and packages.config to previous workable version and downgrade the NuGet packs... This is likely because your MVC has been upgraded while some relative DLL are still the old and incompatible versions... I met a similar problem and I solved it by modifying Web.config under project folder as below: <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>
{ "pile_set_name": "StackExchange" }
Q: How to configure Dreamweaver CS5.5 for OS X to behave like an OS X application? I've just started using Dreamweaver CS5.5 for OS X and can't find how to configure it to behave like all other OS X editors. There seems to be a slew of subtle differences, and I'm guessing there is a "mode" setting for changing it from Windows style interaction to OS X style interaction. The main difference that is frustrating me right now is that the Command-[arrow left/right] is moving the cursor by words instead of by lines. Shift-Command-[right arrow] selects the entire line in browsers, editable fields, and other OS X editors, but in DW it only selects the next word. Is there a way to configure DW CS5.5 to behave like an OS X application instead of a Windows app? A: I'd guess that it's using custom text fields rather than using the Cocoa API - if so, they need to rewrite it to use the modern API, rather than a simple fix.
{ "pile_set_name": "StackExchange" }
Q: Allowing pagebreaks for shaded theorems using thmtools I just searched for a way of allowing pagebreaks when using shaded theorem-environments from thmtools. I found my question was, somewhat, answered here (the second solution) with a comment from the package's author Ulrich Schwarz. However, I'd like to keep defining theorem-like environments as follows \declaretheorem[shaded={bgcolor=LightGrey},name=Definition,parent=chapter, % refname={definition,definitions}, Refname={Definition,Definitions}]{Def} i.e. without having to declare an extra (rather bulky) theoremstyle for each environment I define. Is it possible to use the "preheadhook-postfoothook-trick" with mdframed globally, while retaining the overall interface and style I would get with my above \declaretheorem-example? As I understand, shaded theorem-environments in thmtools are already implemented using mdframed anyway, so I thought it should be possible to allow pagebreaks by redefining some internal thmtools command, by setting some global option, or something along those lines. I hope this is actually a valid question, as it was, more or less, already answered in 2011. A: Shaded theorems in thmtools are implemented with the shadethm package, not mdframed. You can do the shading with mdframed instead by passing the option mdframed={backgroundcolor=LightGrey} to the theorem declaration. This will allow page breaks in the defintion and gives output as in the sample below. If the options you want to pass to mdframed are more complicated, you can set-up a style \usepackage{mdframed} \mdfdefinestyle{thmstyle}{backgroundcolorl=LightGrey, leftmargin=40pt, rightmargin=40pt} and then pass mdframed={style=thmstyle} to the declaration instead of the shaded option. \documentclass{book} \usepackage{amsthm} \usepackage[svgnames]{xcolor} \usepackage{thmtools} \declaretheorem[mdframed={backgroundcolor=LightGrey}, name=Definition,parent=chapter, Refname={Definition,Definitions}]{Def} \begin{document} \mbox{} \vspace{14cm} \begin{Def} Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. Some long definition. \end{Def} \end{document}
{ "pile_set_name": "StackExchange" }
Q: TCP optimisation I've written a code using SOL_SOCKET protocol but getting error as 10043 (error in socket). The code is as follows: #include <QCoreApplication> #include<QDebug> //#include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdlib.h> #include <stdio.h> /****************************************/ #pragma comment (lib, "Ws2_32.lib") #pragma comment (lib, "Mswsock.lib") #pragma comment (lib, "AdvApi32.lib") /****************************************/ #define DEFAULT_BUFLEN 512 int recvbuflen = DEFAULT_BUFLEN; char recvbuf[DEFAULT_BUFLEN]; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } struct addrinfo *result = NULL, *ptr = NULL, hints; ZeroMemory( &hints, sizeof(hints) ); //hints.ai_family = AF_UNSPEC; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = SOL_SOCKET; //hints.ai_protocol = IPPROTO_TCP; #define DEFAULT_PORT "10990" // Resolve the server address and port iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed: %d\n", iResult); WSACleanup(); return 1; } SOCKET ConnectSocket = INVALID_SOCKET; // Attempt to connect to the first address returned by // the call to getaddrinfo ptr=result; // Create a SOCKET for connecting to server ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (ConnectSocket == INVALID_SOCKET) { printf("Error at socket(): %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } int rcvbuf = 8192; /* recv buffer size */ int z = setsockopt(ConnectSocket,SOL_SOCKET,SO_RCVBUF, (char*)&rcvbuf,sizeof(rcvbuf)); do { iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0); if (iResult > 0) printf("Bytes received: %d\n", iResult); else if (iResult == 0) printf("Connection closed\n"); else printf("recv failed: %d\n", WSAGetLastError()); } while (iResult > 0); return a.exec(); } When I run it shows:: Error in socket:10043 I googled it and found that the error is because of wrong protocol for the socket type,I tried to find the correct protocol and socket type match but couldn't find.I tried every possible socket option and protocol match. Any body facing the same problem? A: You're putting the wrong value in the ai_protocol field. It needs to be one of the IPPROTO_ constants (like e.g. IPPROTO_TCP or IPPROTO_ICMP). SOL_SOCKET is used to set socket options (like you do later in the code). You should normally not set that member, except to zero.
{ "pile_set_name": "StackExchange" }
Q: Does using HVDC for distance transmission make theft of electricity easier to detect? In particular, if you were going to try to steal power from HDVC transmission lines you'd need one cable attached to current going in 1 direction and the other attached to current flowing in the opposite direction. So this would create a branch current and if there are meters measuring the current flow, the utility companies could detect an unexpected drop in current and locate where it is coming from. A: No, using DC rather than AC doesn't make power loss any easier to detect. But it does make theft much harder to begin with. With an AC transmission line, most forms of theft rely on the AC magnetic and or electric fields radiated by the lines — i.e., there is no direct connection to the line at all. With a DC line, there is no radiation of that type, other than any noise generated by the power converters at each end, and the random current variations caused by customers switching loads on and off.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use FindRoot with a function of two variables? How can I use FindRoot with 2 variables function? Is there a different way to do that? For example f[x_,y_]=Sin[x + y^2]; FindRoot[f[x,y], {x, -1}, {y, -3}] A: You cannot use FindRoot to find a root of f[x_, y_] := Sin[x + y^2] because a function of two variables like f doesn't have roots in the sense that a function of one variable has. When a function of two variables intersects the xy-plane, it normally produces contour lines not individual points. You can examine such contours with ContourPlot. Your function f, because of the oscillatory nature of Sin has several contours at f[x, y] == 0 in the vicinity of $(-1,\,-3)$ as can be seen from the following plot. ContourPlot[f[x, y] == 0, {x, -2, 0}, {y, -4, -2}, Epilog -> {Red, AbsolutePointSize[5], Point[{-1, -3}]}]
{ "pile_set_name": "StackExchange" }
Q: Why does Play project fail with "implicit value ... is not applicable here" after upgrading to Slick 3.0? After upgrading to Slick 3.0 and Play! 2.4, I got this pretty dependency injection feature, but I faced with serialization problems. My Application is simple rest server. This is the exception which I get type mismatch; found : play.api.libs.json.OWrites[ReportsDatabase.this.PostEntity] required: play.api.libs.json.Writes[ApiRoot.this.noiseModel.PostEntity] Note: implicit value PostWrites is not applicable here because it comes after the application point and it lacks an explicit result type This is my entity val posts = TableQuery[Posts] case class PostEntity(id: Long, user: Long, text: String, date: LocalDate, lat: Double, lon: Double, pictureID: Long, soundId: Long) class Posts(tag: Tag) extends Table[PostEntity](tag, "post") { implicit val dateColumnType = MappedColumnType.base[LocalDate, String](dateFormatter.print(_), dateFormatter.parseLocalDate) def id = column[Long]("id", O.AutoInc, O.PrimaryKey) def userId = column[Long]("userId") def text = column[String]("text") def date = column[LocalDate]("date_post") def lat = column[Double]("lat") def lon = column[Double]("lon") def pictureId = column[Long]("pictureID") def soundId = column[Long]("soundId") def * = (id, userId, text, date, lat, lon, pictureId, soundId) <>(PostEntity.tupled, PostEntity.unapply) def user = foreignKey("post_user_FK", userId, users)(_.id) } Here is method to get a list of posts def getPostList: Future[Seq[PostEntity]] = db.run(posts.result) My controller starts like this class ApiRoot @Inject() (noiseDao: NoiseModel, noiseModel: ReportsDatabase) extends Controller { import noiseModel._ implicit val PostWrites = Json.writes[noiseModel.PostEntity] def getPostStream = Action.async { implicit request => noiseDao.getPostList.map{posts => Ok(toJson(posts)) } } def getPost(id: Long) = Action.async { implicit request => noiseDao.getPost(id).map{ post => Ok(toJson(post)) } } I haven't found any information in the Internet regarding this problem. Found questions, but any answers. A: My guess is to move implicit val PostWrites to companion object Posts or closer to the DI library (don't know Play that much to offer more help). It happens because of the way DI works in general - first an instance, and then all the goodies are available that are inside the instance.
{ "pile_set_name": "StackExchange" }
Q: MVC 2 model properties not used in view returned as null or empty The issue I am having is when i pass a populated object to a view that doesn't display all of the properties. public ActionResult Edit(Guid clientID) { Property property = PropertyModel.GetPropertyDetails(clientID); return View("Edit", "Site", property); } View: <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<WebFrontend.ViewModels.Property>" %> <% using (Html.BeginForm()) {%> <%: Html.ValidationSummary(true, "Property update was unsuccessful. Please correct the errors and try again.") %> <fieldset> <legend>Edit Account: <%: Model.ClientAccountNo %></legend> <div class="editor-label"> <%: Html.LabelFor(model => model.ClientName)%> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.ClientName)%> <%: Html.ValidationMessageFor(model => model.ClientName)%> </div> <p> <input type="submit" value="Update Property" /> </p> </fieldset> <% } %> When submitted the Property object is passed to this controller method but all of the properties not used in the view are null or empty including Model.ClientAccountNo which is present on the view before submitting. [HttpPost] public ActionResult Edit(Property property) { if (ModelState.IsValid) { bool success = PropertyModel.UpdateProperty(property); if (success) { // property has been updated, take them to the property details screen. return RedirectToAction("Details", "Property", new { clientID = property.ClientID }); } else { ModelState.AddModelError("", "Could not update property."); return View("Activate", "Site", property); } } // If we got this far, something failed, redisplay form return View("Edit", "Site", property); } I can't find anything similar on the web, any explanation for why this is happening and how to fix it would be appreciated. A: This is the way MVC works - it tries to construct an object of the action parameter type from the values in the route, form and query string. In your case it can only get the values in the form collection. It does not know anything about the values that you have stored in your database. If you are only interested in certain properties you would be better off doing a specific view model with just these on - then you can validate for this specific case. If you store values in hidden fields keep in mind that these can be manipulated - if this is a problem definitely go with a specific view model with only the editable fields on.
{ "pile_set_name": "StackExchange" }
Q: How to create a C# regex to accept only these characters? How can I create Regex in c# which accept only this characters? a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z â  ä Ä á à À Á é è ê ë Ê È É Ê Ë - ' ( ) ß ñ Ñ Ç ç Ì Í ì í î ï Î Ï ò ó ô ö Ó Ô Ö Õ ù ú û ü Ù Ú Û Ü I try this regex but i don't think is correct: "[-')(a-zA-ZâÂäÄáàÀÁéèêëÊÈÉÊËßñÑÇçÌÍìíîïÎÏòóôöÓÔÖÕùúûüÙÚÛÜ]*" In my unit test, this value last-'()Name not match a regex A: Something like that: "[-a-zA-ZâÂäÄáàÀÁéèêëÊÈÉÊË')(ßñÑÇçÌÍìíîïÎÏòóôöÓÔÖÕùúûüÙÚÛÜ]*"
{ "pile_set_name": "StackExchange" }
Q: Heating an 1ohm ressistor using mosfet as switch I need to heat an 1 ohm resistor from 3.7v,1000mah battery using an mosfet as switch whose gate voltage is supplied through arduino digital pin output and supply to the arduino is also given from the same battery. The problem i'm facing is that the ardunio nano is on but resistor does not get heated . I have used: irf640 mosfet irl2203 mosfet we tried changing mosfets but it did not work. A: Here's what the conducting IRF640 looks like graphically: - If you had a gate-source voltage of 4.5 volts and put 3.7 volts across drain to source, the current that flowed might be 0.6 amps. If you wanted the volt drop across the MOSFET to be much less you could activate the gate at (say) 15 volts and then you could pull more than 10 amps. So with a measly 3 volt gate drive your resistor is barely going to get warm at all. For your application this MOSFET is unsuitable. You need to find a MOSFET with a much, much lower on resistance and one that is capable of going sub 50 milli ohm with a Vgs of 3 volts. Even 50 milli ohm is a 5% error if you truly wanted 1 ohm placed across the 3.7 volt supply. Following an edit by the OP, he also said that the IRL2203N didn't work. So, I suggest you measure the resistor to ensure it is 1 ohm. I also suggest that you measure the gate-source voltage to ensure that it is 3 volts. Basically double check everything but most importantly: - Ensure that the MOSFET ground and Arduino grounds are connected
{ "pile_set_name": "StackExchange" }
Q: Intellij IDEA Android Resource Jump to Definition XML File instead of R.java In Android Studio, if I reference a resource in code, for example R.string.some_sample_string or R.layout.activity_main, and I jump to definition (CMD + B on OS X) it will take me to the line in the appropriate strings.xml file or the appropriate layout xml file for activity_main.xml. Lately I've been using IntelliJ IDEA Ultimate for Android development. When I jump to definition in IDEA it brings me to the declaration of the class in the generated R.class file instead of the resource XML files. Is there a way to make IDEA behave like Android Studio and jump to the xml files instead of the java class declarations? A: It turns out the issue here was actually my project file. On our team, we use our own project generation with our monorepo to automate selecting which files should be indexed by IntelliJ. As it turns out this is currently an issue/limitation with our internal automation tool. It's not a spectacular answer, but if you are encountering a similar issue I would suspect that the project file has been tampered with and that you should either nuke it and create a new one or take it up with anyone who might be doing this similar kind of project manipulation in your team.
{ "pile_set_name": "StackExchange" }
Q: trying to understand angularjs errors I'm pretty new to js / angularjs and constantly have trouble figuring out why something is not working. what does it mean when angularjs gives out this error?: Error: [$injector:cdep] http://errors.angularjs.org/1.2.11/$injector/cdep?p0=authService%20%3C-%20authInterceptor%20%3C-%20%24http%20%3C-%20%24compile authService and authInterceptor are both my creations. A: Circular dependency detected, you have injected A into B, and B into A, and maybe not directly, it could be through a dependency of one of the injections. Generally it means you need to refactor the injections to break the circular dependency. Hopefully, the thing that both of them need can be moved into its own service (C), then you can inject C into B, and C into A.
{ "pile_set_name": "StackExchange" }
Q: vue js how "process.env" variables in index.html I am trying to use env variables in my html markup to change env variables according to whether I am in production or development mode .. So for context using mixpanel I have two projects one for development and one for production with different api keys. how would I use webpack to do this, accessing my process.env.VUE_APP_MIXPANEL env variable in my html ? A: If you are using the default Webpack template you can access the .env variables in index.html using this syntax (for example): <html> <head> <title><%= VUE_APP_TITLE %></title> </head> <body> ... </body> </html> Obviously you need to have a variable like this VUE_APP_TITLE=My title in your .env file
{ "pile_set_name": "StackExchange" }
Q: php jquery count down timer script i have one count down timer using http://keith-wood.name/countdown.html var austDay = new Date(); austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26); $('#defaultCountdown').countdown({until: austDay,format: 'HMS'}); this works fine. but for one year, as i can see in code that austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26); is generating last date. my last date is coming from PHP and i want to change the above line so that last date will be calculated from one of PHP variable. Thanks A: austDay = new Date('<?php echo date("F d, Y H:i:s", time()); ?>');
{ "pile_set_name": "StackExchange" }
Q: execute a command if substitution succeded I would like to remove \" from perl script with sed, sed -ne ' #(here some substitutions...) s/print "\(.*[^"]\)"/\1/p; ' | \ sed -e 's/\\"/"/g' Is it possible to only substitute \" by " on lines where the first substitution was done? In other word to make this script in one line? Branching is not cool, because if a not listed previous substitution has been done, the condition is considered as true (but the latest substitution has not been done)... EXEMPLE: #! /usr/bin/perl (...) while (@someArray) { print "la variable \"$_\" est cool!\n"; syslog ('info|machin', "la variable \"$_\" est cool!"); } to "la variable "$_" est cool!\n" but no possible substitution in syslog ('info|machin', "la variable \"$_\" est cool!"); If this line was previously selected. A: sed -ne ' # if other substitution are to be made without regarding of s/print.... #(here some substitutions...) s/print "\(.*[^"]\)"/\1/; t bs # if other substitution are to be made if /print... is NOT found #(here some substitutions...) b : bs # if other substitution are to be made if /print... is found #(here some substitutions...) s/\\"/"/g p ' after a s//, there is the t that mean Test and goto label (bs in this case) if true. So here, substitute, if occuring, go to bs and make other substitution than print the result, if not true, go to the end (b without label following) (code review due to different interpretation about other substitution)
{ "pile_set_name": "StackExchange" }
Q: How to implment touch funcationality on a PC running Windows using Jquery/Javascript? I have implemented the touch functionality to my website using these code and it works fine for iPad/iPhone. // registering touch events function initTouchEvents() { // if a device is a touch device if (window.Touch) { document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler, true); document.addEventListener("touchend", touchHandler, true); document.addEventListener("touchcancel", touchHandler, true); } } // making items sortable in touch screen devices function touchHandler(event) { var touches = event.changedTouches, first = touches[0], type = ""; switch (event.type) { case "touchstart": type = "mousedown"; break; case "touchmove": type = "mousemove"; break; case "touchend": type = "mouseup"; break; default: return; } var simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null); first.target.dispatchEvent(simulatedEvent); if (event.type == "touchmove") { event.preventDefault(); } } But when I tested my website on touch screen PC, it doesn't run and I found out that the window.Touch only run for iPhone/iPad. And I also tried various other events like typeof(window.ontouchstart != 'undefined') and ('ontouchstart' in window || typeof TouchEvent != "undefined") but it doesn't detect that it's touch screen and doesn't register the event for touch movement. What I am asking here is for an event in javascript that can detect all the touch devices (that IOS/Android/Windows/OSX) and run register the events. A: Phantom Limb makes desktop browsers simulate touch events https://github.com/brian-c/phantom-limb
{ "pile_set_name": "StackExchange" }
Q: Borůvka cleanup in linear time? Given boruvka's algorithm: MST T <- empty tree Begin with each vertex v as a component While number of components > 1 For each component c let e = minimum edge out of component c if e is not in T add e to T //merging the two components connected by e In each phase I'd like to reduce the graph's size, by saying that after each phase - there is actually no need to remember edges that are within each component (because some were inserted to the MST T already and others are not needed). So instead of each component I'd like to put only a single vertex. The only problem comes when I try to construct my edges - an edge between two new vertices (which were two components before) is the one with the smallest weight among all the edges between a vertex in the first component and a vertex in the second. I wanted to implement this in linear time, but I don't see how I can reduce the edges as well, all in linear time? A: This depends on what you mean by linear time. If you want $O(n)$, then you're out of luck, there's too many edges to consider in the worst case. If you mean $O(n+m)$, then it is possible, and it is reasonable to consider this as linear time, as the input needs to represent the edges as well as the vertices, which takes at least $O(n+m)$ symbols. After each round of selecting which new edges to add, we keep track of which pairs of components are being merged, then we look at these in order (any order is fine) and look at all edges from the new component to each other new component, and record the smallest we have seen. (Note that this is symmetric, so we when we find the smallest edge from new component $A$ to new component $B$, it is also the smallest from $B$ to $A$, so we only need to consider edges going to new components later in the ordering, but this doesn't affect the complexity). To achieve this we can simply look at all edges in order and update the appropriate information.
{ "pile_set_name": "StackExchange" }
Q: Checkbox on Custom Metadata Type Record will not update to True I created a Custom Metadata Type with Public Visibility with Object Name "My_App_Settings". On My_App_Settings, I added a Custom Field: Field Label - "Enable Trigger" Type - Checkbox Field Manageability - Subscriber editable Default Value - Unchecked I created a new "My_App_Setting" with Master Label "Create Contact Trigger Enable" and selected "Enable Trigger" checkbox. When I perform a SOQL query on "My_App_Settings" Object I see the row I created "Create Contact Trigger" but the checkbox is always set to false. I don't quite understand why this is the case. Does it have something to do with Subscriber editable setting on the Custom Field? A: There's a recently discovered issue with external objects and custom metadata types where checkbox fields with API names of 30 characters or more always return false in queries (though not in the native UI). Might this be what you're seeing? The known issue link is https://success.salesforce.com/issues_view?id=a1p300000008bS6AAI .
{ "pile_set_name": "StackExchange" }
Q: MultiOS "Jet Database" for C++/Qt? Hopefully I can articulate this well: I'm porting an application I made years ago from VB6 (I know, I know!) to C++/Qt. In my original application, one thing I liked was that I didn't need an actual SQL server running, I could just use MS Access .mdb files. I was wondering if something similar exists for Qt that will work on multiple OSes - a database stored in a file, pretty much, but that I can still run SQL queries with. Not sure if something like this exists or not, but any help appreciated, thanks! A: I second the comment by "Mosg". Have a look at SQLite.
{ "pile_set_name": "StackExchange" }
Q: Uber native login flagging error I am currently running the example codes provided by Uber SDK (Objective C version). I encounter a problem when I clicked on the Native Login and Ride Request Widget Button provided by the Objective C example. After setting up the app in Uber and also copied the Client ID to the info.plist, I counter the error below: When I click at the Ride Request Widget Button, the app will load a new view with the "Ride there with Uber" button. After clicking the "Ride there with Uber" button, the example app will flag a UIAlert with a message of "There seems to be a problem connecting to Uber. Please go back to AppName and try again". What could be the problem? Btw, I fill in the redirect URL as "myapp://oauth/callback" on both the dashboard and the app info.plist. Anything I miss out during the setup of this example? Thanks. A: Make sure the URL Scheme in Targets > Info is set to something like sampleApp, and not sampleApp://uberSSO. This solved my problem. For reference, here is the snippet from the Info.plist: <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>MySampleAppName</string> <key>CFBundleURLSchemes</key> <array> <string>sampleApp</string> </array> </dict> </array>
{ "pile_set_name": "StackExchange" }
Q: Who does the "Crown prosecutor of Russia" refer to? In an email sent from Rob Goldstone to Donald Trump Jr. that was released by Trump Jr. on Twitter, it was mentioned in one email that the "Crown prosecutor of Russia" met with Aras Agalarov. The Crown prosecutor of Russia met with his father Aras this morning ... I am curious what is a Crown Prosecutor and who holds that position currently? A: Basically, this article by The Atlantic explains that Rob Goldstone likely mixed up the titles. Crown Prosecutor is a title commonly used in Commonwealth realms, that refers to a prosecutor that works for the Crown, i.e. a federal prosecutor or a state prosecutor in the context of a state. However, there is no such position in Russia, so he's likely referring to the Prosecutor General of Russia, a position currently held by Yury Chaika. In the US, the analogue would be the Attorney-General.
{ "pile_set_name": "StackExchange" }
Q: How to access multi-dimensional arrays (like this)? I have an array and I'm not sure how to access certain keys. What I'm trying to accomplish is simply target certain keys/values in the array. Here's a sample of my array. var jobs = [ { // hunting name: 'Hunting', available: [ { name: 'Housemate', description: 'You stick around the cabin of the hunters. You are the lowest class of the hunters.', salary: 10 }, { name: 'Fetcher', description: 'You are the fetcher of the clan. You gather leather, resources, and skin leather.', salary: 15 }, { name: 'Hunter', description: 'You are a basic hunter of the clan. You hunt for food, meat, and leather.', salary: 25 }, { name: 'Elder', description: 'You are a elder of the clan. You are respected among many, and may ask hunters for arrons.', salary: 0 } ], // construction name: 'Construction', available: [ { name: 'Builder', description: 'You are a builder. You are the lowest class of the construction tier.', salary: 45 }, { name: 'Driver', description: 'You are a driver. You do the fetching and gathering of resources.', salary: 55 }, { name: 'Engineer', description: 'You are a engineer. You do the wiring and electrical work in the construction.', salary: 65 }, { name: 'Overseer', description: 'You are the overseer. You watch over the construction and give orders.', salary: 80 } ], } ]; Now keep in mind that I have multiple arrays in one array. Here I try to access the Hunter job category, the Fetcher job, and the construction Engineer salary. alert(jobs.'Hunting'); // gives 'missing name after . operator' error alert(jobs.name[0]); // gives 'name is not defined' error alert(jobs.available.'Fetcher'); //same error as number 1 alert(jobs.available.salary[0]) // gives available is not defined error How can I access those variables? A: Your array of objects is malformed Your original array contained a single item: one object which had the name and available properties defined twice. I suspect you want your array to contain two items: two objects, each with a name and available property. It should be this: var jobs = [ { // hunting name: 'Hunting', available: [ { name: 'Housemate', description: 'You stick around the cabin of the hunters. You are the lowest class of the hunters.', salary: 10 }, { name: 'Fetcher', description: 'You are the fetcher of the clan. You gather leather, resources, and skin leather.', salary: 15 }, { name: 'Hunter', description: 'You are a basic hunter of the clan. You hunt for food, meat, and leather.', salary: 25 }, { name: 'Elder', description: 'You are a elder of the clan. You are respected among many, and may ask hunters for arrons.', salary: 0 } ] }, { // construction name: 'Construction', available: [ { name: 'Builder', description: 'You are a builder. You are the lowest class of the construction tier.', salary: 45 }, { name: 'Driver', description: 'You are a driver. You do the fetching and gathering of resources.', salary: 55 }, { name: 'Engineer', description: 'You are a engineer. You do the wiring and electrical work in the construction.', salary: 65 }, { name: 'Overseer', description: 'You are the overseer. You watch over the construction and give orders.', salary: 80 } ], } ]; Accessing items in the array alert(jobs[0].name); // Returns 'Hunting' alert(jobs[0].available[1].name); // Returns 'Fetcher' alert(jobs[0].available[3].salary); // Returns '0' Why don't the following examples work? You can't use a string in dot notation: alert(jobs.'Hunting'); alert(jobs.available.'Fetcher'); You cannot have a string after the dot. You should have a property name as in object.name, but you first need to define by its index which item in the array you're targeting as in array[i].name. But even if you changed it to… alert(jobs[0].Hunting); // OR alert(jobs[0]['Hunting']); …it would fail because there is no object with a property name of 'Hunting'. Square brackets are misplaced: alert(jobs.name[0]); alert(jobs.available.salary[0]); The above examples don't work because you are passing an index inside square brackets after your property name, where they should be placed after the array name. For example: alert(jobs[0].name); alert(jobs[0].available[0].salary); Accessing objects in array by key/value It looks like you're attempting to access the object's in the array by the value from one of its properties. For example, above it seems you want to get the object whose property of name has a value of 'Hunting', which cannot be done directly. You would need to create a function or use a library that provides a function for this, such as Underscore's _.find. Example of using _.find to get an object by key/value: var hunting = _.find(jobs, function(obj) { return obj.name === 'Hunting'; }); View the above examples in JSFiddle
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of “Tu me présenteras ton adjoint”? I have a sentence in my French workbook which has to be converted into impératif and the highlighted words should be replaced by personal pronouns. The sentence is: Tu me présenteras ton adjoint. I guess this means 'You will present me as your assistant' or 'You will present me your assistant.' So is the given sentence correct and if yes, what does it mean? A: The second answer is correct: “You will present me your assistant.” To put it simply, in the sentence: Tu me présenteras ton adjoint. there is no particle that would play the role of “as” in the French sentence. The sentence corresponding to You will present me as your assistant. would be Tu me présenteras comme ton adjoint.
{ "pile_set_name": "StackExchange" }
Q: Adding left and right images programatically to UIButton I am trying to add an image to the left and right of a UIButton. I've researched and whilst there are many solutions, I haven't been able to get any to work for me. I need to be able to: Show or hide one or both icons Customize the color of the icons based on other logic elsewhere have the content centered Layout is: OUTTER PADDING + LEFT ICON + INSIDE PADDING + LABEL + PADDING + RIGHT ICON + RIGHT PADDING This is the closest I've come but doens't tick all the boxes. I have the following code as an extension on UIButton: func leftImage(image: UIImage, padding: CGFloat, renderMode: UIImage.RenderingMode) { self.setImage(image.withRenderingMode(renderMode), for: .normal) contentHorizontalAlignment = .center let availableSpace = bounds.inset(by: contentEdgeInsets) let availableWidth = availableSpace.width - imageEdgeInsets.right - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0) titleEdgeInsets = UIEdgeInsets(top: 0, left: availableWidth / 2, bottom: 0, right: 0) imageEdgeInsets = UIEdgeInsets(top: 0, left: padding, bottom: 0, right: 0) } func rightImage(image: UIImage, padding: CGFloat, renderMode: UIImage.RenderingMode){ self.setImage(image.withRenderingMode(renderMode), for: .normal) semanticContentAttribute = .forceRightToLeft contentHorizontalAlignment = .center let availableSpace = bounds.inset(by: contentEdgeInsets) let availableWidth = availableSpace.width - imageEdgeInsets.left - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0) titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: availableWidth / 2) imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: padding) } Currently, the problems I have with this code are: 1. can't change the icon colors outside of the tint style 2. rendering isn't laying out correctly 3. I can only get the left or the right icon to show but not both If I call the leftImage method, I get this result: If I call the rightImage method, I get this result: And if I call both, I get this: I apologize in advance if this isn't clear, I'm still new to all this. A: Followed advise from @matt and have the following code: // LEFT IMAGE let newLeftItemToAdd = UIImageView(image: #imageLiteral(resourceName: "star")) myButton.addSubview(newLeftItemToAdd) //Sizing newLeftItemToAdd.width(20) newLeftItemToAdd.height(20) //Vertical positioning newLeftItemToAdd.centerYToSuperview() //Horizontal positioning let padding = 10.0 newLeftItemToAdd.rightToLeft(of: myButton.titleLabel!, offset: CGFloat(-padding), isActive: true) //Change color newLeftItemToAdd.setImageColor(color: .green) // RIGHT IMAGE let newRightItemToAdd = UIImageView(image: #imageLiteral(resourceName: "star")) myButton.addSubview(newRightItemToAdd) //Sizing newRightItemToAdd.width(20) newRightItemToAdd.height(20) //Vertical positioning newRightItemToAdd.centerYToSuperview() //Horizontal positioning newRightItemToAdd.leftToRight(of: myButton.titleLabel!, offset: CGFloat(padding), isActive: true) //Change color newRightItemToAdd.setImageColor(color: .orange) This works perfectly now and gives the flexibility to change colors of each icon individually if I need it. I also created an extension of UIImageview to provide further flexibility: extension UIImageView { func setImageColor(color: UIColor) { let templateImage = self.image?.withRenderingMode(.alwaysTemplate) self.image = templateImage self.tintColor = color } } And this is the end result:
{ "pile_set_name": "StackExchange" }
Q: Mechanism to identify users that are (not) worth the effort (private white/black list?) I'm seeing an increasingly list of vague questions where my comments asking for clarifications ("do you want to do X?") are dismissed angrily in terms like "my question is clear, don't leave comments if you can't help" (and no reference to X). Sometimes I check the user history and find out I had the same problem in previous questions from the same user. It's not positive for anyone that next time he posts a similar vague question I leave another comment but I just can't remember all the user names. It'd be cool if I had a way to tag the user or attach a note to its profile or something similar. I don't mean banning anyone or making those flags public, it'd be something private and merely for personal reference. I'm also not talking about the question itself (which can handled with the usual tools if it's actually not answerable). Perhaps it's possible to solve it in more general terms and implement personal white/black lists which would also help to spot users who make great questions and deserve attention. What do you thing about it? A: There is no need for just you to have this. If a user is terribly bad and keeps on asking unclear questions, posts bad answers, etc., we downvote, close the question, delete answer, comment, etc. In this way, it doesn't only benefit you, it also benefits all of us. A: You really shouldn't need to do this, and I don't approve of it at all, since we're supposed to focus on the question content rather than the user, but there is a userscript called StackPlonk on Stack Apps that allows you to "plonk" a user, which does this: You set it on their profile page, and you can "unplonk" them at any time in the same way. Keep in mind that all you're doing here is ignoring a user for no one's benefit but your own: you could try to help the user, which might improve their questions, or, if they're really on the wrong path, let a moderator take care of them. You're effectively just ignoring the problem, which doesn't make it go away for anyone but you. Again, you really shouldn't do this, but if you must... A: I feel your pain, but the problem I see with a formal mechanism is that it would encourage people to write off others permanently because, as we all know, people do not change. That's sometimes true (people don't change), but also I think "dismissed angrily" paranoid type reactions are often just a stage certain people go through as their experience with technical forums (boards, exchanges, whatever) increases. I certainly remember taking things the wrong way when I first started using a programming board regularly (fortunately, before S.O. existed -- my head is well sorted now, I think). It was only when I started answering more questions than I asked that I realized how hard it can be to remain concise but not seem like like a jerk to someone unacquainted. Occasionally I've ending up doing this: I'm not trying to belittle or dismiss you. I'm trying to help. Don't confuse a friend for an enemy, calm down, and re-read what I've written with that in mind. :) This doesn't always work, but it does have a better than 50% success rate in my experience. All of sudden someone who was antagonistic and paranoid is thanking you and apologizing. Then you get that warm feeling from having turned someone's life around a little bit. Keep in mind that people who are genuine time-wasters and intentionally abusing a system will tend to create new accounts. They may then keep one with a minimal amount of rep to do stuff like close voting, etc.
{ "pile_set_name": "StackExchange" }
Q: The Defining Moment I'm not sure what to put here... but I'll do it regardless! Popular tourist destination, with “the” Throwing a Native American weapon Fruit with a fantastic nickname? President or patriarch Like Nigeria and Chad “Gold” Egyptian boat Seattle player Uproar The answer will be a thematic title. A: The trick to this is that each of the clues has an answer containing AHA, which goes into the central box. (This is hinted by that box and the black square below it forming an exclamation point.) The answers are: BAHAMAS / TOMAHAWKING / PITAHAYA (a.k.a. "dragon fruit") / ABRAHAM (Lincoln or the Biblical patriarch) / SUB-SAHARAN / DAHABEAH / SEAHAWK / BROUHAHA The grid is filled like this: And the shaded cells spell TAKE ON ME, a song by the Norwegian band "A-ha".
{ "pile_set_name": "StackExchange" }
Q: PowerShell logic to remove objects from Array I'm trying to remove objects from an array that contain duplicates and only keep the ones with the highest number in TasteCode. The example below is highly simplified, but it shows the problem. Example: $Fruits Name | Color | TasteCode ----- ------ --------- Apple | Red | 2 Apple | Red | 3 Peer | Green | 0 Banana | Yellow | 1 Banana | Yellow | 0 Banana | Yellow | 3 Desired solution: Name | Color | TasteCode ----- ------ --------- Apple | Red | 3 Peer | Green | 0 Banana | Yellow | 3 I've already succeeded in gathering the ones that need to be removed, but it doesn't work out quite well: $DuplicateMembers = $Fruits | Group-Object Name | Where Count -GE 2 $DuplicateMembers | ForEach-Object { $Remove = $_.Group | Sort-Object TasteCode | Select -First ($_.Group.Count -1) $Fruits = Foreach ($F in $Fruits) { Foreach ($R in $Remove) { if (($F.Name -ne $R.Name) -and ($F.TasteCode -ne $R.TasteCode)) { $F } } } } Thank you for your help. A: How about not performing a remove, but just sort on tastecode descending and taking just one first result? $DuplicateMembers = $Fruits | Group-Object Name $DuplicateMembers | ForEach-Object { $Outcome = $_.Group | Sort-Object TasteCode -descending | Select -First 1 $Outcome } This way you should not bother to remove anything form the result of this query.
{ "pile_set_name": "StackExchange" }
Q: C++ - Create a 2D copy constructor I am trying to study for my final and I tried putting together my dynamic 2d array copy constructor. When I created my backup and printed it to see if it worked, it prints out the same memory address I believe over and over again. This is my copy constructor: Update, here is where I read in data from my file .txt void Matrix::readTemps(ifstream &inFile) { while (!inFile.eof()) { for (int row = 0; row < mnumRows; row++) { for (int col = 0; col < mnumCols; col++) { inFile >> Temps[row][col]; } } } } Matrix::Matrix(const Matrix & original) { mnumRows = original.mnumRows; mnumCols = original.mnumCols; Temps = new double*[mnumRows]; for (int row = 0; row < mnumRows; row++) Temps[row] = new double[mnumCols]; } Matrix& Matrix::operator=(const Matrix & second) { if (this != &second) { delete[] Temps; mnumRows = second.mnumRows; mnumCols = second.mnumCols; Temps = new double*[second.mnumRows]; for (int row = 0; row < mnumRows; row++) Temps[row] = new double[mnumCols]; } return *this; } UPDATE, and this is in my main.cpp: //Example of overloaded assignment operator. Matrix TestMatrix; TestMatrix = NYCTemps; //Example of copy constructor. Matrix copyOfMatrix(NYCTemps); // The traditional way to copy the phonebook. NYCTemps.display(); copyOfMatrix.display(); cout << endl; I believe my assignment overloaded operator is correct as well, but I am posting it just to confirm it is good from more clever minds. A: In your version of copy constructor and copy assignment operator you only allocate memory for 2d array but you don't copy values from original matrix to new one. You should add these lines in both methods for (int r = 0; r < mnumRows; ++r) for (int c = 0; c < mnumCols; ++c) Temps[r][c] = original.Temps[r][c]; // or second.Temps[r][c] Temps is 2d array so in copy assignment operator it must be deleted by (firstly delete memory allocated for columns in every row then delete memory of rows) for (int r = 0; r < mnumRows; ++r) delete[] Temps[r]; delete[] Temps;
{ "pile_set_name": "StackExchange" }
Q: How to declare and assign an array without the app crashing? Basically, I'm implemeting a reversi app for android for my year 13 coursework and this snippet of code is meant to setup the board which is shown here as an array of the class position. However, when run, the app crashes. Position[][] board = new Position[7][7]; //declaring the board// for(int n = 0; n < 8; n ++){ ... for(int i = 0; i < 8; i++ ){ final ImageView button = new ImageView(this); final int countN = n; final int countI = i; board[countI][countN].isPositionEmpty = true; //assigning a value// Any help would be much appreciated!! thanks in advance! A: You've only allocated a 7x7 array, but you're trying to use it as an 8x8 array. Change to use: Position[][] board = new Position[8][8]; Or preferably, have a constant which is used in multiple places: private static final int BOARD_SIZE = 8; ... Position[][] board = new Position[BOARD_SIZE][BOARD_SIZESIZE]; for (int i = 0; i < BOARD_SIZE; i++) { ... } An array allocation like this: Foo[] array = new Foo[size]; creates an array with size elements; valid indexes are in the range 0 to size - 1 inclusive. A: You have to insantiate every index of your matrix too. for(int i = 0; i < 8; i++ ){ board[countI][countN] = new Position(); board[countI][countN].isPositionEmpty = true; //assigning a value// } A: Your for loop goes from 0 to 7 which is actually 8 cells. So you need 8 position objects. Position[][] board = new Position[8][8] or if you want it to be a 7 by 7 board you need to stop at the 6th index for (int i =0; i <7 ; i++)
{ "pile_set_name": "StackExchange" }
Q: Converting a JWT payload back to a struct I'm having trouble converting a JWT payload back to a struct in golang I have two servers which communicate with each other and have a JWT auth to enforce security. The payloads use the below struct type ResponseBody struct { Header dto.MessageHeader `json:"message_header"` OrderBodyParams dto.OrderBodyParams `json:"order_response"` Status string `json:"status"` ErrorMessage string `json:"errors"` } Server A takes this struct - converts it into byte date and sends it as a JWT payload the relevant code is below func request(secretKey string, path string, method string, requestParams interface{}, response interface{}) error { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{ Timeout: time.Second * 15, Transport: tr, } //convert body into byte data requestBody, err := json.Marshal(requestParams) if err != nil { return err } tokenString, expirationTime, err := authentication.GenerateJWTAuthToken(secretKey, requestBody) if err != nil { return err } req, _ := http.NewRequest(method, path, bytes.NewBuffer([]byte(tokenString))) req.Header.Set("Content-Type", "application/json") req.AddCookie(&http.Cookie{ Name: "token", Value: tokenString, Expires: expirationTime, }) _, err = client.Do(req) if err != nil { return err } return nil } As you can see , i'm merely converting the body to byte data - and converting it into a JWT payload the function GenerateJWTAuthToken is like the below type Claims struct { Payload []byte `json:"payload"` jwt.StandardClaims } func GenerateJWTAuthToken(secretKey string, payload []byte) (string, time.Time, error) { var jwtKey = []byte(secretKey) // Set expiration to 5 minutes from now (Maybe lesser?) expirationTime := time.Now().Add(5 * time.Minute) // create the payload claims := &Claims{ Payload: payload, StandardClaims: jwt.StandardClaims{ ExpiresAt: expirationTime.Unix(), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString(jwtKey) if err != nil { return "", time.Time{}, fmt.Errorf("Error generating JWT token : %+v", err) } return tokenString, expirationTime, nil } Now server B - recieves the data and validates the JWT and converts the byte payload back to the ResponseBody struct func Postback(appState *appsetup.AppState) http.HandlerFunc { fn := func(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) tokenString := string(body) if err != nil { w.WriteHeader(http.StatusUnauthorized) return } // Verify the JWT token send from server A and ensure its a valid request // If the token is invalid , dont proceed further token, payload, err := authentication.VerifyJWTToken(appState.SecretKey, tokenString) if err != nil { if err == jwt.ErrSignatureInvalid { w.WriteHeader(http.StatusUnauthorized) return } w.WriteHeader(http.StatusBadRequest) return } if !token.Valid { w.WriteHeader(http.StatusUnauthorized) return } requestData := ResponseBody{} err = binary.Read(bytes.NewReader(payload), binary.LittleEndian, &requestData) if err != nil { fmt.Printf("Couldnt convert payload body to struct : %+v ", err) return } return requestData } return http.HandlerFunc(fn) } The VerifyJWTToken function is pretty straightforward as well (i'm hoping) func VerifyJWTToken(secretKey string, tokenString string) (*jwt.Token, []byte, error) { var jwtKey = []byte(secretKey) var payload []byte claims := &Claims{} token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return jwtKey, nil }) if err != nil { return nil, payload, err } return token, claims.Payload, nil } But i'm having trouble converting the payload back to the ResponseBody struct - It seems to fail at the line err = binary.Read(bytes.NewReader(bodyBuffer), binary.LittleEndian, &requestData) with the below error msg":"Couldnt convert payload body to struct : binary.Read: invalid type *ResponseBody " Is there something i'm missing? A: You're using JSON to marshal your struct: requestBody, err := json.Marshal(requestParams)` So you should use JSON unmarshaling to get back the struct. Yet, you're using binary.Read() to read it: err = binary.Read(bytes.NewReader(payload), binary.LittleEndian, &requestData) Instead do it like this: err = json.Unmarshal(payload, &requestData)
{ "pile_set_name": "StackExchange" }
Q: Making passwords more secure? Hey Guys im thinking about something what i can do to improve the current password safeness. Most of you know rainbow tables which can decrypt "hacked" md5 hashes in seconds. My thought was, how can i make this more secure. What if the "hacker" who hacked got some md5 hashes has not the full md5 hash? For example, the password i choose "rabbit" md5 hash equals (a51e47f646375ab6bf5dd2c42d3e6181) Nearly every rainbow table in the internet can decrypt these md5 hash into the clear word "rabbit". But what if i parse only the first 10 signs into the database. And if the user sign in with its password it will be checked if the first 10 signs equals the 10 signs in the database. So, if the hacker got some hashes he could not revert any of them because none of these makes any sense.. Is this possible and really more secure? This is only an idea which had and i would really appreciate it for your comments. Thanks!!! A: I would recommend to follow Secure hash and salt for PHP passwords A: While this does make driveby rainbow table-based attacks less viable, it doesn't really add security. Once the attacker figures out you're using 'trunctated' MD5 hashes, your approach actually makes things easier for him or her - after all, s/he doesn't have to find the one single phrase with the correct hash, just one that shares the first 10 characters or so. This is almost a textbook example of security through obscurity, I'm sorry to say. It's good that you're thinking about ways to store passwords more securely - and that you're aware that using plain MD5 hashes is not a good idea - but this is the wrong approach.
{ "pile_set_name": "StackExchange" }
Q: Java: Possible to disable Ctrl-C in Java console application? As the subject states, is there a way to disable CTRL-C (and other signals) so that they don't terminate the application? A: EDIT2: this may also help: Capture SIGINT in Java This and this appear to be what you want. Ctrl-C and other command send "signals" to your program, and if you write code to "catch" catch those signals, you can change how your program reacts. Ideally, you would want ctrl-c to terminate the program, as it's what the user expects, so keep in mind that you should tell the user why it's not terminating if you change the program's response. Edit3: Cat's suggestion of a keylistener is your next best bet if you can't catch and dismiss the event yourself. Halway down the page is an example of how to do it for java in linux/Windows - it's not a portable thing. Essentially, your program will be handling keyboard events instead of the console sending the keybaord events to it. This means the command line is bypassed, and cannot read the ctrl-c call. I'd write code, but I'm at work now; Wednesdays are a long day for me. If you haven't gotten it by the time I get home, I'll take a look at writing some examples.
{ "pile_set_name": "StackExchange" }
Q: Cannot access pear.php.net from OSX Lion I am stumped by this issue. I have 2 separate Macs that cannot access pear.php.net at all by name or IP. Here are the symptoms and steps that I took to try to resolve/narrow down this issue. $ ping -c 4 pear.php.net PING euk1.php.net (5.77.39.20): 56 data bytes Request timeout for icmp_seq 0 Request timeout for icmp_seq 1 Request timeout for icmp_seq 2 --- euk1.php.net ping statistics --- 4 packets transmitted, 0 packets received, 100.0% packet loss $ ping -c 4 5.77.39.20 PING 5.77.39.20 (5.77.39.20): 56 data bytes ping: sendto: No route to host Request timeout for icmp_seq 0 ping: sendto: Host is down Request timeout for icmp_seq 1 ping: sendto: Host is down Request timeout for icmp_seq 2 --- 5.77.39.20 ping statistics --- 4 packets transmitted, 0 packets received, 100.0% packet loss From a Windows PC on the same network (I even used the same ethernet cable just to be sure) c:\>ping pear.php.net Pinging euk1.php.net [5.77.39.20] with 32 bytes of data: Reply from 5.77.39.20: bytes=32 time=102ms TTL=51 Reply from 5.77.39.20: bytes=32 time=102ms TTL=51 Reply from 5.77.39.20: bytes=32 time=100ms TTL=51 Reply from 5.77.39.20: bytes=32 time=102ms TTL=51 Ping statistics for 5.77.39.20: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 100ms, Maximum = 102ms, Average = 101ms Both machines are running OSX 10.7 Tried both wired and wifi, same result Tried one of the Macs on a different network, same result Tried with firewall on and off, same result Have not had this problem with any other site / IP Tried to open both pear.php.net and 5.77.39.20 in a browser, got 404 Edit: In response to Paul's comment $netstat -rn Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 192.168.0.1 UGSc 18 0 en1 5 link#8 UC 2 0 ham0 5.255.255.255 ff:ff:ff:ff:ff:ff UHLWbI 0 10 ham0 127 127.0.0.1 UCS 0 0 lo0 127.0.0.1 127.0.0.1 UH 3 152 lo0 169.254 link#5 UCS 0 0 en1 192.168.0 link#5 UCS 4 0 en1 192.168.0.1 0:1b:6c:69:19:8f UHLWIi 28 634 en1 1141 192.168.0.192 127.0.0.1 UHS 0 0 lo0 192.168.0.194 0:21:a0:50:4d:70 UHLWIi 0 498 en1 669 192.168.0.255 ff:ff:ff:ff:ff:ff UHLWbI 0 10 en1 Internet6: Destination Gateway Flags Netif Expire ::1 link#1 UHL lo0 2620:9b::/96 link#8 UC ham0 2620:9c::5f7:6deb 7a:7c:5:f7:6d:eb UHL lo0 fe80::%lo0/64 fe80::1%lo0 UcI lo0 fe80::1%lo0 link#1 UHLI lo0 fe80::%en0/64 link#4 UCI en0 fe80::205:ff:fee1:a1a2%en0 0:5:0:e1:a1:a2 UHLWIi en0 fe80::%en1/64 link#5 UCI en1 fe80::1240:d3ff:feaf:8974%en1 10:40:d3:af:89:74 UHLI lo0 fe80::%ham0/64 link#8 UCI ham0 fe80::7879:5ff:fec7:6deb%ham0 7a:79:5:c7:6d:eb UHLI lo0 ff01::%lo0/32 fe80::1%lo0 UmCI lo0 ff01::%en0/32 link#4 UmCI en0 ff01::%en1/32 link#5 UmCI en1 ff01::%ham0/32 link#8 UmCI ham0 ff02::%lo0/32 fe80::1%lo0 UmCI lo0 ff02::%en0/32 link#4 UmCI en0 ff02::%en1/32 link#5 UmCI en1 ff02::%ham0/32 link#8 UmCI ham0 A: You have a route for the 5.0.0.0/8 network there leading to the ham0 interface. This is the hamachi interface. When Hamachi started their service, they chose the 5.0.0.0/8 network as their pool of addresses to avoid conflicting with any existing ranges. However, hamachi were never allocated this range. In the past couple of months, RIPE (who are responsible for this range) have started selling blocks in the 5/8 network. This was inevitable with the quickly depleting numbers of ipv4 addresses, yet hamachi are still using this block. If you want to access services in this range, then you will need to uninstall hamachi - or at least disable it while accessing those blocks. You could also manually delete the route each time. The real fix will be for hamachi to purchase a block that they are entitled to use, or to switch to ipv6. A: An alternative will be to switch your Hamachi client to IPv6. I did it under Mountain Lion 10.8.1 (same issue, unable to access pear.php.net), and I can now access it without issues and at the same time keep my office and home computers still connected. To switch to IPv6, just go to "LogMeIn Hamachi > Preferences > Settings > Advanced settings > Peer connections > IP protocol mode" and switch to "IPv6 only". Reconnect again and try to access to pear.php.net. Using last Hamachi client version here, 2.1.0.322 for OSX
{ "pile_set_name": "StackExchange" }
Q: Complex Integration with Power Series Let $f(z)=\sum_{n=0}^{\infty}c_nz^n$ have radius of convergence $R>0.$ Use the fact that $$\sum\limits_{n=0}^{\infty}\int_\gamma c_n z^ndz=\int_\gamma \sum\limits_{n=0}^{\infty}c_nz^ndz=\int_\gamma f(z)dz$$ to show that $$c_k=\frac{1}{2\pi i}\int_\gamma \frac{f(z)}{z^{k+1}}dz \qquad(0<r<R)$$ where $\gamma$ is the circle of radius $r$ centred at the origin, traversed once in the positive direction. From the information given, I could construct a parametrisation $\gamma(t)=re^{it}$, then $\gamma '(t)=rie^{it}$. Using the identities gives, I could isolate the $c_k$ term by moving all other terms to the other side of the equality. Since $f(z)$ is in the final expression, I considered starting with $$\int_\gamma c_kz^kdz=\int_\gamma f(z)dz-\int_\gamma c_0dz-\cdots-\int_\gamma c_{k-1}z^{k-1}dz-\int_\gamma c_{k+1}z^{k+1}dz-\cdots-\int_\gamma c_nz^ndz$$ And I thought maybe the $\frac{1}{2\pi i}$ term came from using the parametrisation with $t\in[0,2\pi]$. But I'm not sure this is a good idea. I end up with a LHS looking like: $$c_k\left(\frac{r^2\left(e^{2i\pi (k+1)}-1\right)}{k+1}\right)$$ It's a little hopeful since the $z^{k+1}$ term could be of the form $re^{i(k+1)}$, but over all looking too messy. Especially since I can't think of a way to simplify the RHS either. What is the best way to approach this? A: You have $$ \frac{1}{2\pi i} \int_{\gamma} \frac{f(z)}{z^{k+1}} dz=\frac{1}{2\pi i} \int_{\gamma} \frac{\sum_{n=0}^{\infty} c_nz^n}{z^{k+1}} = \frac{1}{2\pi i} \sum_{n=0}^{\infty} \int_{\gamma} \frac{c_nz^n}{z^{k+1}}=\frac{1}{2\pi i} \sum_{n=0}^{\infty}c_n \int_{\gamma} z^{n-k-1} $$ and now refer to the result that $$ \int_{\gamma} z^m dz= \begin{cases} 2 \pi i & \text{if} \; m=-1\\ 0 & \text{otherwise} \end{cases} $$ So $$ \frac{1}{2\pi i} \int_{\gamma} \frac{f(z)}{z^{k+1}} dz=\frac{1}{2\pi i} \sum_{n=0}^{\infty}c_n \int_{\gamma} z^{n-k-1} = \frac{1}{2\pi i}\cdot 2\pi i\cdot c_k=c_k $$ as the integrals vanish unless $n=k$
{ "pile_set_name": "StackExchange" }
Q: Error after renaming main Activity after renaming my main class to "Main" and my main xml to "main" i could start my application. i keep getting this logcat: 08-28 21:46:27.563: D/AndroidRuntime(264): Shutting down VM 08-28 21:46:27.563: W/dalvikvm(264): threadid=3: thread exiting with uncaught exception (group=0x4001b188) 08-28 21:46:27.563: E/AndroidRuntime(264): Uncaught handler: thread main exiting due to uncaught exception 08-28 21:46:27.623: E/AndroidRuntime(264): java.lang.RuntimeException: Unable to start activity ComponentInfo{noc.support/noc.support.Main}: java.lang.NullPointerException 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.os.Handler.dispatchMessage(Handler.java:99) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.os.Looper.loop(Looper.java:123) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.ActivityThread.main(ActivityThread.java:4363) 08-28 21:46:27.623: E/AndroidRuntime(264): at java.lang.reflect.Method.invokeNative(Native Method) 08-28 21:46:27.623: E/AndroidRuntime(264): at java.lang.reflect.Method.invoke(Method.java:521) 08-28 21:46:27.623: E/AndroidRuntime(264): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 08-28 21:46:27.623: E/AndroidRuntime(264): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 08-28 21:46:27.623: E/AndroidRuntime(264): at dalvik.system.NativeStart.main(Native Method) 08-28 21:46:27.623: E/AndroidRuntime(264): Caused by: java.lang.NullPointerException 08-28 21:46:27.623: E/AndroidRuntime(264): at noc.support.Main.onCreate(Main.java:116) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 08-28 21:46:27.623: E/AndroidRuntime(264): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 08-28 21:46:27.623: E/AndroidRuntime(264): ... 11 more 08-28 21:46:27.653: I/dalvikvm(264): threadid=7: reacting to signal 3 08-28 21:46:27.663: I/dalvikvm(264): Wrote stack trace to '/data/anr/traces.txt' 08-28 21:47:07.853: I/Process(264): Sending signal. PID: 264 SIG: 9 manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="noc.support" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:debuggable="true"> <service android:name=".BootListnerService" android:label="Boot Service"> <intent-filter> <action android:name="noc.support.BootListnerService" /> </intent-filter> </service> <receiver android:name=".BootListnerServiceReceiver" android:enabled="true" android:exported="true" android:label="BootListnerServiceReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <activity android:name=".Main" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Register" android:label="Register"></activity> <activity android:name=".Settings" android:label="Settings"></activity> <activity android:name=".ServersStatus" android:label="Servers Status"></activity> </application> </manifest> and this is the main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="vertical" > <TextView android:id="@+id/emailLable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="40dp" android:text="Email:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_marginLeft="5dp"/> <EditText android:id="@+id/emailField" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:inputType="textEmailAddress" /> <TextView android:id="@+id/passwordLable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/editText1" android:layout_marginTop="36dp" android:text="Password:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_marginLeft="5dp"/> <EditText android:id="@+id/passwordField" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/> <CheckBox android:id="@+id/rememberEmailPasswordCheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Remember my email &amp; password" /> <CheckBox android:id="@+id/loginAutomaticallyCheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login automatically" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="5dp" android:paddingRight="5dp" android:layout_marginTop="40dp"> <Button android:id="@+id/addButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.05" android:text="Add" /> <Button android:id="@+id/refreshButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.86" android:text="Refresh" /> </LinearLayout> </LinearLayout> what am i doing wrong? does anyone have any ideas. i googled it but i couldn't find the fix. when i change "setContentView(R.layout.main);" to any other layout it works fin, but i need this class to start with main.xml A: i fixed it by creating a new project and copied all my files into that project but i didn't replace the main class or the layout instead i copied and pasted the inner code of the class of those two but kept the class name. this way the class name is correct.
{ "pile_set_name": "StackExchange" }
Q: How to deal with setup.py overwriting sub-package dependencies The problem I am facing is that setuptools overwrite the sub-package dependency requirements. Example: setup.py import os from setuptools import setup setup( name="test", version="0.1", author="myself", author_email="[email protected]", description="How to manage dependencies?", license="MIT", classifiers=[ "Development Status :: 3 - Alpha" ], zip_safe=False, install_requires=[ 'dependency-injector', ] ) Installation successful via python setup.py install Output: (venv) alex@ws:~$ pip freeze dependency-injector==3.14.12 six==1.12.0 test==0.1 If you use the following setup.py including six as dependency (because you need it in your package), then you hit problems, because dependency-injector also needs the dependency though they have defined a fixed version range. import os from setuptools import setup setup( name="test", version="0.1", author="myself", author_email="[email protected]", description="How to manage dependencies?", license="MIT", classifiers=[ "Development Status :: 3 - Alpha" ], zip_safe=False, install_requires=[ 'dependency-injector', 'six' ] ) Output: error: six 1.13.0 is installed but six<=1.12.0,>=1.7.0 is required by {'dependency-injector'} (venv) alex@ws:~$ pip freeze dependency-injector==3.14.12 six==1.13.0 test==0.1 For sure a working solution is just to repeat the same six version range which dependency-injector uses (see the requirements.txt file in their repo), though I would really like to avoid this duplicate definition of dependencies, because e.g. dependency-injector might upgrade the six version dependency and thus I need to also update my package. So I will always try to mimic their requirements which is bad practice. I think actually the only clean solution would be that setuptools builds up a dependency tree and and then uses the versions matching the requirements of all dependencies. Is this realistic? How can it be achieved or what is the recommended best-practice in such a case as described above? A: The TL;DR answer is that pip currently does not have a dependency solver. There is an ongoing issue on pip's issue tracker on just that topic: https://github.com/pypa/pip/issues/988 What they say is that currently pip's behavior is "first found wins", so your top-level six dependency is resolved before dependency-injector's six dependency, which is why you get the latest six version installed in the end. On the python setup.py install vs. pip install . question, there seems to be a subtle difference between the two commands. They don't use the same tools internally, and the recommended command is pip install . generally (sources: https://stackoverflow.com/a/15731459/9977650, https://github.com/pypa/setuptools/issues/960)
{ "pile_set_name": "StackExchange" }
Q: in jquery datepicker can add alt field with classname? hi I am using jquery ui datepicker in starting i set datepicker with following way $(".td-datepicker).datepicker(); class .td-datepicker apply on four input text box and their id are following #startdate #enddate #edit_startdate, #edit_enddate now i want to set alt field in all four input field how can i add by class because if i add by id then repetition of code occur like below $('#startdate').datepicker("option","altField","#alt_startdate"); $('#startdate').datepicker("option","altFormat","mm/dd/yy"); $('#enddate').datepicker("option","altField","#alt_enddate"); $('#enddate').datepicker("option","altFormat","mm/dd/yy"); $('#edit_startdate').datepicker("option","altField","#alt_edit_startdate"); $('#edit_startdate').datepicker("option","altFormat","mm/dd/yy"); $('#edit_enddate').datepicker("option","altField","#alt_edit_enddate"); $('#edit_enddate').datepicker("option","altFormat","mm/dd/yy"); and can i add multiple option in datepicker after initialization like for $('#edit_enddate').datepicker("option","altField","#alt_edit_enddate"); $('#edit_enddate').datepicker("option","altFormat","mm/dd/yy"); can i write code for above two line in one line . is this any way ? A: To change the altFormat on all of them, assuming they've the same format: $(".td-datepicker").datepicker("option", "altFormat", "mm/dd/yy"); For the multiple options at once (example): $(".td-datepicker").datepicker("option", { disabled: true, dateFormat: "dd/mm/yy" }); To solve your issue, based on the ids you're using: $(".td-datepicker").each(function (idx, el) { $(this).datepicker("option", "altField", "#alt_" + $(this).attr("id")); }); If you change your mind, yes, you can use classes instead. It's all on the API documentation: http://api.jqueryui.com/datepicker/
{ "pile_set_name": "StackExchange" }
Q: Undefined Javascript Error On Click not sure why I'm getting this error when I attempt to click on the button. Uncaught TypeError: Cannot read property 'on' of undefined JSFiddle: https://jsfiddle.net/mm5crd3b/ Thanks $(document).ready(function(){ (function() { var itemTracker = { // init init: function() { this.bindEvents(); }, // cacheDom cacheDom: { inputAdd: $('#inputAdd'), submitAdd: $('#submitItem') }, // item item: { text: this.inputAdd.value, }, // Bind Events bindEvents: function() { this.submitAdd.on("click", addItem); }, // Add item addItem: function() { console.log("test"); } // Remove item // Edit Item // Complete Item // Uncomplete Item }; itemTracker.init(); })(); }); A: You are accessing the property in a wrong way, bindEvents: function() { this.cacheDom.submitAdd.on("click", addItem); }, When seeing your code, I can tell cacheDom is an object which holds submitAdd as a property in it. Additionally, item: { text: this.inputAdd.value, }, This part of the code wont work as expected. You can write it as a getter to solve your problem. get itemText() { return this.cacheDom.inputAdd.value, },
{ "pile_set_name": "StackExchange" }
Q: Vue.js filters and testing I used vue-cli to create sample project vue init webpack my-test3, and opted for including both e2e and unit tests. Question 1: Based on documentation for template filters I tried to add new filter as such in main.js: import Vue from 'vue' import App from './App' /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App }, filters: { capitalize: function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } } }) And my App.vue: <template> <div id="app"> <img src="./assets/logo.png"> <hello></hello> <world></world> <div class="test-test">{{ 'tesT' | capitalize }}</div> </div> </template> <script> import Hello from './components/Hello' import World from './components/World' export default { name: 'app', components: { Hello, World } } </script> I get warning(error): [Vue warn]: Failed to resolve filter: capitalize (found in component <app>) If I modify main.js to register filter before initializing new Vue app, then it works without problem. import Vue from 'vue' import App from './App' Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) }) /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } }) Why one works and other not? Question 2: With example above that works Vue.filter(..., I added a test for World.vue component: <template> <div class="world"> <h1>{{ msg | capitalize }}</h1> <h2>{{ desc }}</h2> Items (<span>{{ items.length }}</span>) <ul v-for="item in items"> <li>{{ item }}</li> </ul> </div> </template> <script> export default { name: 'world', data () { return { msg: 'worldly App', desc: 'This is world description.', items: [ 'Mon', 'Wed', 'Fri', 'Sun' ] } } } </script> And World.spec.js: import Vue from 'vue' import World from 'src/components/World' Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) }) describe('World.vue', () => { it('should render correct title', () => { const vm = new Vue({ el: document.createElement('div'), render: (h) => h(World) }) expect(vm.$el.querySelector('.world h1').textContent) .to.equal('Worldly App') }) it('should render correct description', () => { const vm = new Vue({ el: document.createElement('div'), render: (w) => w(World) }) expect(vm.$el.querySelector('.world h2').textContent) .to.equal('This is world description.') }) }) For the above test to pass, I need to include Vue.filter(... definition for filter capitalize, otherwise tests would fail. So my question is, how to structure filters/components and initialize them, so testing is easier? I feel like I should not have to register filters in unit tests, that should be part of the component initialization. But if component is inheriting/using filter defined from main app, testing component will not work. Any suggestions, comments, reading materials? A: A good practice is create a filters folder and define your filters inside this folder in individual files and define all your filters globally if you want to have access to them in all of your components, eg: // capitalize.js export default function capitalize(value) { if (!value) return ''; value = value.toString().toLowerCase(); value = /\.\s/.test(value) ? value.split('. ') : [value]; value.forEach((part, index) => { let firstLetter = 0; part = part.trim(); firstLetter = part.split('').findIndex(letter => /[a-zA-Z]/.test(letter)); value[index] = part.split(''); value[index][firstLetter] = value[index][firstLetter].toUpperCase(); value[index] = value[index].join(''); }); return value.join('. ').trim(); } To test it successfully and if you use @vue/test-utils, to test your single file components, you can do that with createLocalVue, like this: // your-component.spec.js import { createLocalVue, shallowMount } from '@vue/test-utils'; import capitalize from '../path/to/your/filter/capitalize.js'; import YOUR_COMPONENT from '../path/to/your/component.vue'; describe('Describe YOUR_COMPONENT component', () => { const localVue = createLocalVue(); // this is the key line localVue.filter('capitalize', capitalize); const wrapper = shallowMount(YOUR_COMPONENT, { // here you can define the required data and mocks localVue, propsData: { yourProp: 'value of your prop', }, mocks: { // here you can define all your mocks // like translate function and others. }, }); it('passes the sanity check and creates a wrapper', () => { expect(wrapper.isVueInstance()).toBe(true); }); }); I hope to help you. Regards.
{ "pile_set_name": "StackExchange" }
Q: IOException: The process cannot access the file 'file path' because it is being used by another process I have some code and when it executes, it throws a IOException, saying that The process cannot access the file 'filename' because it is being used by another process What does this mean, and what can I do about it? A: What is the cause? The error message is pretty clear: you're trying to access a file, and it's not accessible because another process (or even the same process) is doing something with it (and it didn't allow any sharing). Debugging It may be pretty easy to solve (or pretty hard to understand), depending on your specific scenario. Let's see some. Your process is the only one to access that file You're sure the other process is your own process. If you know you open that file in another part of your program, then first of all you have to check that you properly close the file handle after each use. Here is an example of code with this bug: var stream = new FileStream(path, FileAccess.Read); var reader = new StreamReader(stream); // Read data from this file, when I'm done I don't need it any more File.Delete(path); // IOException: file is in use Fortunately FileStream implements IDisposable, so it's easy to wrap all your code inside a using statement: using (var stream = File.Open("myfile.txt", FileMode.Open)) { // Use stream } // Here stream is not accessible and it has been closed (also if // an exception is thrown and stack unrolled This pattern will also ensure that the file won't be left open in case of exceptions (it may be the reason the file is in use: something went wrong, and no one closed it; see this post for an example). If everything seems fine (you're sure you always close every file you open, even in case of exceptions) and you have multiple working threads, then you have two options: rework your code to serialize file access (not always doable and not always wanted) or apply a retry pattern. It's a pretty common pattern for I/O operations: you try to do something and in case of error you wait and try again (did you ask yourself why, for example, Windows Shell takes some time to inform you that a file is in use and cannot be deleted?). In C# it's pretty easy to implement (see also better examples about disk I/O, networking and database access). private const int NumberOfRetries = 3; private const int DelayOnRetry = 1000; for (int i=1; i <= NumberOfRetries; ++i) { try { // Do stuff with file break; // When done we can break loop } catch (IOException e) when (i <= NumberOfRetries) { // You may check error code to filter some exceptions, not every error // can be recovered. Thread.Sleep(DelayOnRetry); } } Please note a common error we see very often on StackOverflow: var stream = File.Open(path, FileOpen.Read); var content = File.ReadAllText(path); In this case ReadAllText() will fail because the file is in use (File.Open() in the line before). To open the file beforehand is not only unnecessary but also wrong. The same applies to all File functions that don't return a handle to the file you're working with: File.ReadAllText(), File.WriteAllText(), File.ReadAllLines(), File.WriteAllLines() and others (like File.AppendAllXyz() functions) will all open and close the file by themselves. Your process is not the only one to access that file If your process is not the only one to access that file, then interaction can be harder. A retry pattern will help (if the file shouldn't be open by anyone else but it is, then you need a utility like Process Explorer to check who is doing what). Ways to avoid When applicable, always use using statements to open files. As said in previous paragraph, it'll actively help you to avoid many common errors (see this post for an example on how not to use it). If possible, try to decide who owns access to a specific file and centralize access through a few well-known methods. If, for example, you have a data file where your program reads and writes, then you should box all I/O code inside a single class. It'll make debug easier (because you can always put a breakpoint there and see who is doing what) and also it'll be a synchronization point (if required) for multiple access. Don't forget I/O operations can always fail, a common example is this: if (File.Exists(path)) File.Delete(path); If someone deletes the file after File.Exists() but before File.Delete(), then it'll throw an IOException in a place where you may wrongly feel safe. Whenever it's possible, apply a retry pattern, and if you're using FileSystemWatcher, consider postponing action (because you'll get notified, but an application may still be working exclusively with that file). Advanced scenarios It's not always so easy, so you may need to share access with someone else. If, for example, you're reading from the beginning and writing to the end, you have at least two options. 1) share the same FileStream with proper synchronization functions (because it is not thread-safe). See this and this posts for an example. 2) use FileShare enumeration to instruct OS to allow other processes (or other parts of your own process) to access same file concurrently. using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read)) { } In this example I showed how to open a file for writing and share for reading; please note that when reading and writing overlaps, it results in undefined or invalid data. It's a situation that must be handled when reading. Also note that this doesn't make access to the stream thread-safe, so this object can't be shared with multiple threads unless access is synchronized somehow (see previous links). Other sharing options are available, and they open up more complex scenarios. Please refer to MSDN for more details. In general N processes can read from same file all together but only one should write, in a controlled scenario you may even enable concurrent writings but this can't be generalized in few text paragraphs inside this answer. Is it possible to unlock a file used by another process? It's not always safe and not so easy but yes, it's possible. A: Using FileShare fixed my issue of opening file even if it is opened by another process. using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { } A: Had an issue while uploading an image and couldn't delete it and found a solution. gl hf //C# .NET var image = Image.FromFile(filePath); image.Dispose(); // this removes all resources //later... File.Delete(filePath); //now works
{ "pile_set_name": "StackExchange" }
Q: Async/await execution order This is the program output: Program Begin 1 - Starting 2 - Task started A - Started something Program End B - Completed something 3 - Task completed with result: 123 Question: As far i understand when it comes to await process is going back to main context so in this case to Main and then go back to await when it's finished so "A - Started something" should be after "Program End". Why this one line was shown? From my understanding when it comes to away it should immediatly go back to main context. static void Main(string[] args) { Console.WriteLine("Program Begin"); DoAsAsync(); Console.WriteLine("Program End"); Console.ReadLine(); } static async void DoAsAsync() { Console.WriteLine("1 - Starting"); var t = Task.Factory.StartNew<int>(DoSomethingThatTakesTime); Console.WriteLine("2 - Task started"); var result = await t; Console.WriteLine("3 - Task completed with result: " + result); } static int DoSomethingThatTakesTime() { Console.WriteLine("A - Started something"); Thread.Sleep(1000); Console.WriteLine("B - Completed something"); return 123; } A: As far i understand when it comes to await process is going back to main context so in this case to Main and then go back to await when it's finished so "A - Started something" should be after "Program End". That is what that thread is doing; the main thread is returning to the Main method. However, StartNew will (in this case) execute its work on a thread pool thread, which runs independently from the main thread. So, you might see "A - Started something" before or after "Program End".
{ "pile_set_name": "StackExchange" }
Q: How can I compile dynamic code at runtime in the current assembly? I use VBCodeProvider to compile code, but it generates a new assembly, and also I need to add all references to assemblies I need to use. Is there a way to compile code in the current assembly? A: You cannot temper the current assembly. A couple of years ago, I have written an on the topic of dynamic compilation: http://emoreau.com/Entries/Articles/2011/07/Compiling-code-on-the-fly.aspx BTW, Roslyn is only available if you are using VS2015 (unless you are using the CTPs that were available for VS2013 but it is not a good idea for anything else then testing).
{ "pile_set_name": "StackExchange" }
Q: Finding extremums of Abs[complex function] We have a function same as f[x_]=Cos[x] Cos[2 x] + I Sin[x] Sin[2 x] The final objective is to find all extremums of Abs[f[x]] in [0,2 pi]. But in the first step there is a problem because Abs[x + I y] != Sqrt[x^2+y^2] except x and y be numeric. Also, in any trick Function same as: FindMaximum could not help for finding ALL of extremums. How can I find MAX and MIN of Abs[f[x]] with their values of x and f[x]? A: The problem can be completely solved symbolically using the standard methods. Here we go. The function in question is given by f[x_] := Cos[x] Cos[2 x] + I Sin[x] Sin[2 x] The square of the absolute value for real x is then fa[x_] = ComplexExpand[f[x]*Conjugate[f[x]]] // Simplify (* Out[94]= Cos[x]^2 (2 - 2 Cos[2 x] + Cos[4 x]) *) The extrema of Abs[f[x]] are in the same location as those of fa[x]. Looking for zeroes in the derivative gives eq = D[fa[x], x] == 0 // Simplify (* Out[98]= Cos[x] (4 Sin[x] - 3 Sin[3 x] + 3 Sin[5 x]) == 0 *) sol = Solve[eq && 0 <= x <= 2 \[Pi], x] (* Out[131]= {{x -> 0}, {x -> \[Pi]/2}, {x -> \[Pi]}, {x -> (3 \[Pi])/2}, {x -> 2 \[Pi]}, {x -> 2 \[Pi] - 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 1]]]}, {x -> 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 1]]]}, {x -> 2 \[Pi] - 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 2]]]}, {x -> 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 2]]]}, {x -> 2 \[Pi] - 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 3]]]}, {x -> 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 3]]]}, {x -> 2 \[Pi] - 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 4]]]}, {x -> 2 ArcTan[Sqrt[Root[5 - 76 #1 + 222 #1^2 - 76 #1^3 + 5 #1^4 &, 4]]]}} *) Length[sol] (* Out[106]= 13 *) Hence we have found 13 solutions. The first five are simple expressions. The others ones can be simplified, but I have found no dierect way of simplify the Root[] expressions. But I discovered by accident that the following works out fine: solving eq without the interval restrictions, chosing the appropriate integer parameters C[i] and and imposing the interval restriction afterwards gives sol1 = Solve[eq, x]; sol1x = Select[ Union[x /. sol1 /. C[1] -> 0, x /. sol1 /. C[1] -> 1], 0 <= # <= 2 \[Pi] &] (* Out[171]= {0, \[Pi]/2, \[Pi], (3 \[Pi])/2, 2 \[Pi], \[Pi] - ArcTan[Sqrt[(6 - Sqrt[6])/(6 + Sqrt[6])]], 2 \[Pi] - ArcTan[Sqrt[(6 - Sqrt[6])/(6 + Sqrt[6])]], ArcTan[Sqrt[(6 - Sqrt[6])/(6 + Sqrt[6])]], \[Pi] + ArcTan[Sqrt[(6 - Sqrt[6])/(6 + Sqrt[6])]], \[Pi] - ArcTan[Sqrt[(6 + Sqrt[6])/(6 - Sqrt[6])]], 2 \[Pi] - ArcTan[Sqrt[(6 + Sqrt[6])/(6 - Sqrt[6])]], ArcTan[Sqrt[(6 + Sqrt[6])/(6 - Sqrt[6])]], \[Pi] + ArcTan[Sqrt[(6 + Sqrt[6])/(6 - Sqrt[6])]]} *) We recover 13 Solutions which are now explicit expressions. Length[sol1x] (* Out[173]= 13 *) All are in the requested interval sol1x/(2 \[Pi]) // N (* Out[174]= {0., 0.25, 0.5, 0.75, 1., 0.408465, 0.908465, 0.0915349, 0.591535, 0.341535, 0.841535, 0.158465, 0.658465} *) Now here is the explicit solution of the problem: all extrema and their locations: txfa = Table[{sol1x[[i]], fa[sol1x[[i]]]}, {i, 1, Length[sol1x]}] // Simplify (* Out[165]= {{0, 1}, {\[Pi]/2, 0}, {\[Pi], 1}, {(3 \[Pi])/2, 0}, {2 \[Pi], 1}, {\[Pi] - ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]], 1/12 (6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]])}, {2 \[Pi] - ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]], 1/12 (6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]])}, {ArcTan[Sqrt[ 1/5 (7 - 2 Sqrt[6])]], 1/12 (6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]])}, {\[Pi] + ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]], 1/12 (6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 - 2 Sqrt[6])]]])}, {\[Pi] - ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]], -(1/ 12) (-6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]])}, {2 \[Pi] - ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]], -(1/ 12) (-6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]])}, {ArcTan[Sqrt[ 1/5 (7 + 2 Sqrt[6])]], -(1/ 12) (-6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]])}, {\[Pi] + ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]], -(1/ 12) (-6 + Sqrt[6]) (2 - 2 Cos[2 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]] + Cos[4 ArcTan[Sqrt[1/5 (7 + 2 Sqrt[6])]]])}} *) txfa // N // Sort (* Out[175]= {{0., 1.}, {0.575131, 0.363917}, {0.995665, 0.636083}, {1.5708, 0.}, {2.14593, 0.636083}, {2.56646, 0.363917}, {3.14159, 1.}, {3.71672, 0.363917}, {4.13726, 0.636083}, {4.71239, 0.}, {5.28752, 0.636083}, {5.70805, 0.363917}, {6.28319, 1.}} *) Finally, let's have a look at the function and its extrema p1 = Plot[fa[x], {x, 0, 2 \[Pi]}]; p2 = ListPlot[txfa, PlotStyle -> {RGBColor[1, 0, 0], PointSize[0.02]}]; Show[p1, p2] (* 150917_Plot_Extrema.jpg *) A: I sometimes have a similar problem and a rather "rough" workaround. First make a plot of the function - omitting the output: p = Plot[Norm@f[x], {x, 0, 2 \[Pi]}]; then extract the line segments data = Cases[p, Line[{x__}] :> x, \[Infinity]]; then find the peaks max = FindPeaks[#[[2]] & /@ data] finally plot the result(s): Show[p, Epilog -> {Red, PointSize[0.02], Point[data[[First /@ max]]]}] O.K. a bit "brute force" and not so elegant, but working. You´ll get this plot and can process the data further on.
{ "pile_set_name": "StackExchange" }
Q: Call different archive page based on post type Ok, I have quite a few CPT's on my latest project. Most of the CPT's are only used to display metabox content linking to pdfs, etc. I looked around and couldn't find quite what I was looking for, but thought I could setup a function that calls the standard archive.php template if the post type is "posts" and if not it could call the archive-cpt.php file. If anyone has seen something like that, or has set something like that up and wouldn't mind sharing their code, it would be appreciated. A: Take a look at the Template Hierarchy section of the Codex that concerns Custom Post types. archive-{post_type}.php - If the post type were product, WordPress would look for archive-product.php. archive.php index.php What you are describing is built in, down to the file naming pattern-- archive-cpt.php To load the same template for all CPT archives use: function not_post_archive_wpse_107931($template) { if (is_post_type_archive()) { $template = get_stylesheet_directory().'/archive-cpt.php'; } return $template; } add_filter('template_include','not_post_archive_wpse_107931'); That will hijack all CPT archives so I would be very careful with it. It could lead to great frustration if someone can't figure out why a CPT archive is not loading the expected template. Barely tested. Possibly buggy. Caveat emptor. No refunds.
{ "pile_set_name": "StackExchange" }
Q: Synonym for "academic year" when talking about primary/secondary schools not universities Academic years in my culture are specified using two-year format e.g. academic year 2014-2015 (which starts in September 2014 and ends in June 2015). The term "academic" bears, in my opinion, much of an academic context. Are there any alternative options to be used when referring to such a year in a primary or secondary education context? A: "School year" is also OK. But "academic year" is fine, even for elementary schools. Maybe "school year" can be used so that there is no objection even from those who think school has mainly some purpose other than academics. By the way, I don't think "academic" will suggest "academy" to most people.
{ "pile_set_name": "StackExchange" }
Q: Install SyliusWebBundle on existing symfony 2 project I already have a complete symfony 2.3 project and want to add cart and sale system on it with Sylius bundles. Sylius Cart Bundle and Sale Bundle use SyliusWebBundle and SyliusMoneyBundle. Sylius documents explain about installing a new Sylius project but not including Sylius to existing system. is there any way to install SyliusWebBundle and SyliusMoneyBundle on symfony 2 project? A: You can install any of the bundles to your project using composer, just like you would any other symfony2 bundles. You can find a list of the sylius bundles on the Packigist site. The web bundle can be installed to your current project by simply typing, in your projects root dir: composer require sylius/web-bundle you will be prompted to select the version. "dev-master" is probably what you want. Note: Depending on your setup the command you run might be php composer.phar require sylius/web-bundle If your not familiar with composer it's worth the time to look it up :). Money bundle: php composer.phar require sylius/money-bundle
{ "pile_set_name": "StackExchange" }