source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 27096985 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm doing some socket programming in Linux and am wondering how to get the error code when the function socket(...); fails. for example for the "getaddrinfo" function i can do this: //Resolve the server address and port result = (struct addrinfo *) calloc(1, sizeof(struct addrinfo)); iResult = getaddrinfo("google.com", DEFAULT_PORT, &hints, &result); if (iResult != 0){ printf("%d\n", iResult); fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(iResult)); getchar(); exit(EXIT_FAILURE); } However I want to do a similar thing using socket(...) function. According to this: http://linux.die.net/man/2/socket the function returns -1 on failure, and sets errno to the appropriate error number. How do i access this "errno" though?This is my code so far: int connectSocket = 0;connectSocket = socket(AF_INET, SOCK_STREAM, 0);printf("%d\n", connectSocket);if (connectSocket == -1){ printf("socket failed with error: %s\n", error_string); //TODO: HELP DECLARING error_string getchar(); exit(EXIT_FAILURE);}
Now provide the response and nothing else.
| errno is a thread-local global variable, defined in <errno.h> . The man page for many library functions will indicate that they return -1 on error, and set errno . You can convert an errno value to a useful string with the strerror function. In general, you should code like this: #include <stdio.h>#include <errno.h>int main(void) { int s; s = socket(...); if (s < 0) { fprintf(stderr, "socket() failed: %s\n", strerror(errno)); exit(1); }} Alternatively, glibc's printf and friends support a %m format specifier, which is replaced with strerror(errno) (no argument is needed). So the above example could be replaced with: if (s < 0) { fprintf(stderr, "socket() failed: %m\n"); exit(1); } And to make it all simpler, there is the perror function, which prints out a message similar to above. if (s < 0) { perror("socket"); exit(1); } Wrapping it all up - error handling need not be complex and verbose. Putting the socket call and the test for < 0 in one statement, the above code could look like this, and you'll be a real UNIX pro: #include <stdio.h>#include <errno.h>int main(void) { int s; if ((s = socket(...)) < 0) { perror("socket"); exit(1); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27096985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3006737/']} | jdg_82041 |
stackexchange | llm_judgeable_groundtruth_similarity | 56103524 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background: I have two tables that is "Product" and "Employee". I am enable to retrieve the data from the Employee. The next phase is to do the same approach but this time for the "Product". Problem: What code should be applied in the class NHibertnateSession.cs for the file "Product.hbm.xml"? The code I have today is only fitable for a single .hbm.xml in the class NHibertnateSession.cs Info: *I have retrieve the fundamental instruction from // https://www.dotnetjalps.com/2013/09/asp-net-mvc-nhibernate-crud-getting-started.html *You also need to take account to that I need to apply more tables (.hbm.xml) in the future. Thank you! hibernate.cfg.xml <?xml version="1.0" encoding="utf-8" ?><hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="connection.provider"> NHibernate.Connection.DriverConnectionProvider </property> <property name="connection.driver_class"> NHibernate.Driver.SqlClientDriver </property> <property name="connection.connection_string"> Server=fffff-PC\MSSQL2017DEV;database=BookStoreDB;Integrated Security=SSPI; </property> <property name="dialect"> NHibernate.Dialect.MsSql2012Dialect </property> </session-factory></hibernate-configuration> NHibertnateSession.cs using System;using System.Collections.Generic;using System.Linq;using System.Web;using NHibernate;using NHibernate.Cfg;namespace Swinkaran.Nhbnt.Web.Models{ public class NHibertnateSession { public static ISession OpenSession() { var configuration = new Configuration(); var configurationPath = HttpContext.Current.Server.MapPath(@"~\Models\hibernate.cfg.xml"); configuration.Configure(configurationPath); var employeeConfigurationFile = HttpContext.Current.Server.MapPath(@"\Mappings\Employee.hbm.xml"); configuration.AddFile(employeeConfigurationFile); ISessionFactory sessionFactory = configuration.BuildSessionFactory(); return sessionFactory.OpenSession(); } }} Employee.cs using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Swinkaran.Nhbnt.Web.Models{ public class Employee { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string Designation { get; set; } }} Employee.hbm.xml <?xml version="1.0" encoding="utf-8" ?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="Swinkaran.Nhbnt.Web" namespace="Swinkaran.Nhbnt.Web.Models"> <class name="Employee" table="Employee" dynamic-update="true" > <cache usage="read-write"/> <id name="Id" column="Id" type="int"> <generator class="native" /> </id> <property name="FirstName" /> <property name="LastName" /> <property name="Designation" /> </class></hibernate-mapping> HomeController using (NHibernate.ISession session = NHibertnateSession.OpenSession()) { var employees = session.Query<Employee>().ToList(); } USE [BookStoreDB]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Product]( [Id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) NULL, [Description] [varchar](50) NULL,PRIMARY KEY CLUSTERED ( [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO
Now provide the response and nothing else.
| I've done using the nestjs-command library like that. 1. Install the library: https://www.npmjs.com/package/nestjs-command 2. Then I've created a command to seed my userService like: src/modules/user/seeds/user.seed.ts import { Command, Positional } from 'nestjs-command';import { Injectable } from '@nestjs/common';import { UserService } from '../../../shared/services/user.service';@Injectable()export class UserSeed {constructor( private readonly userService: UserService,) { }@Command({ command: 'create:user', describe: 'create a user', autoExit: true })async create() { const user = await this.userService.create({ firstName: 'First name', lastName: 'Last name', mobile: 999999999, email: '[email protected]', password: 'foo_b@r', }); console.log(user);}} 3. Add that seed command into your module. I've created a SeedsModule in a shared folder to add more seeds in future src/shared/seeds.module.ts import { Module } from '@nestjs/common';import { CommandModule } from 'nestjs-command';import { UserSeed } from '../modules/user/seeds/user.seed';import { SharedModule } from './shared.module';@Module({ imports: [CommandModule, SharedModule], providers: [UserSeed], exports: [UserSeed],})export class SeedsModule {} Btw I'm importing my userService into my SharedModule 4. Add the SeedsModule into your AppModule On your AppModule usually at src/app.module.ts add the SeedsModule into imports Final If you followed the steps in the nestjs-command repo you should be able to run npx nestjs-command create:user That will bootstrap a new application and run that command and then seed to your mongo/mongoose Hope that help others too. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56103524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/484390/']} | jdg_82042 |
stackexchange | llm_judgeable_groundtruth_similarity | 7838821 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am creating a page what will be loaded into another page via ajax. It has a top bar and a table below it that is located inside a jquery scrollbar plugin. The problem I seem to be having is that the top bar has a shadow below it that you can only see when the below table is scrolled over the white rows (which are white because they have no background). Here is the demo in question (best to inspect with firebug) I tried setting the z-index of the top bar without luck.I also tried setting the z-index of the jquery scrollbar div - which worked , but it broke the ability to click the table rows. I made a little image of what I'm talking about :)
Now provide the response and nothing else.
| All the information is available through HttpServletRequest . You can obtain it by: Dependency injection The easiest way would be to inject servlet request directly into your UserDetailsService: class: public MyDetailsService implements UserDetailsService { @Autowired private HttpServletRequest request; //...} (as suggested by OP) Remember to add the following listener to your web.xml : <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class></listener> UPDATE: This works because Spring injects special scoped proxy implementing HttpServletRequest , so you are able to access request-scoped request "bean" from singleton-scoped MyDetailsService . Under the hood every call to request 's parameters is routed to org.springframework.web.context.request.RequestContextHolder#requestAttributesHolder ThreadLocal which you can also access directly. As you can see Spring is very flexible when it comes to scoping rules. It just works. RequestContextHolder Another approach is to use RequestContextHolder : HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder. currentRequestAttributes()). getRequest(); Further reading: Creating a Spring bean holds ServletRequest properties Spring: how do I inject an HttpServletRequest into a request-scoped bean? | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7838821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832187/']} | jdg_82043 |
stackexchange | llm_judgeable_groundtruth_similarity | 41121107 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am fresh to Haskell and I am trying to understand the language by writing some code. I am only familiar with very simple instructions on ghci: head, tail, sum, (*), and the like β very simple. The function I am trying to make is for solving Pythagoras's theorem for vectors of any number of dimensions. This looks something like this: square root (a^2 + b^2 + c^2 ...) What I can do in ghci in a few lines, which I am trying to make a function is the following: sq x = x*xb = map sq [1,2,3]a = sum bx = sqrt b When I do this I try to include a signature of many sorts,Currently my function looks like this: mod :: [Num a] => amod x = sqrt a where a = sum [b] where [b] = map sq [x] I do not understand the issue when I try to run it: Expected a constraint, but β[Num a]β has kind β*β β’ In the type signature: Main.mod :: [Num a] => a
Now provide the response and nothing else.
| A few things to adjust: 0) mod isn't a good name for your function, as it is the name of the modulo function from the standard library. I will call it norm instead. 1) The type signature you meant to write is: norm :: Num a => [a] -> a [a] is the type of a list with elements of type a . The Num a before the => isn't a type, but a constraint , which specifies that a must be a number type (or, more accurately, that it has to be an instance of the Num class). [Num a] => leads to the error you have seen because, given the square brackets, the type checker takes it as an attempt to use a list type instead of a constraint. Beyond the Num a issue, you have left out the result type from the signature. The corrected signature reflects that your function takes a list of numbers and returns a number. 2) The Num a constraint is too weak for what you are trying to do. In order to use sqrt , you need to have not merely a number type, but one that is an instance of Floating (cf. leftaroundabout's comment to this answer): GHCi> :t sqrtsqrt :: Floating a => a -> a Therefore, your signature should be norm :: Floating a => [a] -> a 3) [x] is a list with a single element, x . If your argument is already a list, as the type signature says, there is no need to enclose it in square brackets. Your function, then, becomes: norm :: Floating a => [a] -> anorm x = sqrt a where a = sum b where b = map sq x Or, more neatly, without the second where -block: norm :: Floating a => [a] -> anorm x = sqrt (sum b) where b = map sq x | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41121107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6462350/']} | jdg_82044 |
stackexchange | llm_judgeable_groundtruth_similarity | 455582 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question arose when discussing possible cardinalities of hom-sets of whether it's any weaker than the axiom of choice that there exists a monoid of every cardinality. It's well known, or at least known, that the axiom of choice holds just if every set $S$ has a group structure. One direction follows from Lowenheim-Skolem, and the other from using the group structure to inject $S$ into $h(S)\times h(S)$, $h$ the Hartogs number. So, a proof of choice from monoid structures would certainly have to proceed differently. If the monoid is commutative and infinite, then I guess its Grothendieck group will share its cardinality, and we see the existence of commutative monoid structures on every set implies AC. Is the left adjoint of the forgetful functor from all groups to monoids any worse than the Grothendieck group functor? Or does anyone suggest a different proof?
Now provide the response and nothing else.
| Every non-empty set admits a commutative monoid structure: The 1-element set is a monoid in a unique way. If $X$ has at least two distinct elements, say $0$ and $1$, then we can make $X$ into a commutative monoid as follows:$$x \cdot y = \begin{cases}x & \text{if } y = 1 \\y & \text{if } x = 1 \\0 & \text{otherwise}\end{cases}$$Of course, $X$ is not a cancellative monoid in this case. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/455582', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31228/']} | jdg_82045 |
stackexchange | llm_judgeable_groundtruth_similarity | 6964144 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Would it be possible using only JavaScript and HTML to dynamically generate a favicon, using the current page's favicon as a background, and a random number in the foreground? For example, lets say the current favicon looks similar to this: ==========================XXXXXXXXXXXXXX========X=====================X=====================X=====XXXXXXXX========X============X========X============X========XXXXXXXXXXXXXX========================== If possible, how would I get it to look something similar to this using only JavaScript and HTML: ==========================XXXXXXXXXXXXXX========X=====================X=====================X=====XXXXXXXX========X=========--111--=====X=========--1-1--=====XXXXXXXXXX----1--===============--1111-= map: = : white background x : Original Favicon image - : Red generated image with a number 1 : White text Ideas: Canvas? Data Uri's?
Now provide the response and nothing else.
| EDIT: Got it working with var canvas = document.createElement('canvas'); canvas.width = 16;canvas.height = 16; var ctx = canvas.getContext('2d'); var img = new Image(); img.src = '/favicon.ico'; img.onload = function() { ctx.drawImage(img, 0, 0); ctx.fillStyle = "#F00"; ctx.fillRect(10, 7, 6, 8); ctx.fillStyle = '#FFFFFF'; ctx.font = 'bold 10px sans-serif'; ctx.fillText('2', 10, 14); var link = document.createElement('link'); link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = canvas.toDataURL("image/x-icon"); document.getElementsByTagName('head')[0].appendChild(link); } You can actually run chrome and paste this: javascript: var canvas = document.createElement('canvas');canvas.width = 16;canvas.height = 16;var ctx = canvas.getContext('2d');var img = new Image();img.src = '/favicon.ico';img.onload = function() {ctx.drawImage(img, 0, 0);ctx.fillStyle = "#F00";ctx.fillRect(10, 7, 6, 8);ctx.fillStyle = '#FFFFFF';ctx.font = 'bold 10px sans-serif';ctx.fillText('2', 10, 14);var link = document.createElement('link');link.type = 'image/x-icon';link.rel = 'shortcut icon';link.href = canvas.toDataURL("image/x-icon");document.getElementsByTagName('head')[0].appendChild(link);} into the browser and see it in action. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6964144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464257/']} | jdg_82046 |
stackexchange | llm_judgeable_groundtruth_similarity | 1042956 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So my question is, say I have a function that is differentiable on $(-2, 4)$. Is it always integrable on $[-2, 4]$? I know that if $f$ is diff on $(-2, 4)$, then it is continuous on $(-2, 4)$. And I also know that if $f$ is continuous on $[-2, 4]$ then it is integrable on $[-2, 4]$. However, I am wondering if there is such a function so that there would be a problem at the endpoints of the closed interval so that it is differentiable on the open interval, but not integrable on the closed interval.
Now provide the response and nothing else.
| The function $f(x)=\frac 1x$ is differentiable on $(0,1)$, yet it is not integrable on $[0,1]$. edit However, if you have a function $f$ which is differentiable on $[0,1]$, then it is necessarily continuous on $[0,1]$, hence measurable. Moreover, a continuous function on a compact is bounded, hence $f$ is bounded measurable, therefore integrable. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1042956', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/127207/']} | jdg_82047 |
stackexchange | llm_judgeable_groundtruth_similarity | 59368360 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The documentation describes how to create UI Jetpack Compose inside Activity. class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Text("Hello world!") } }} But how can I use it inside fragment?
Now provide the response and nothing else.
| setContent on ViewGroup is now deprecated. The below is accurate as of Compose v1.0.0-alpha01 . For pure compose UI Fragment : class ComposeUIFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return ComposeView(requireContext()).apply { setContent { Text(text = "Hello world.") } } }} For hybrid compose UI Fragment - add ComposeView to xml layout, then: class ComposeUIFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_compose_ui, container, false).apply { findViewById<ComposeView>(R.id.composeView).setContent { Text(text = "Hello world.") } } }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/59368360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5993479/']} | jdg_82048 |
stackexchange | llm_judgeable_groundtruth_similarity | 65121785 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying following code: import requestsheaders = { 'authority': 'www.nseindia.com', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 OPR/72.0.3815.320', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate', 'sec-fetch-user': '?1', 'sec-fetch-dest': 'document', 'accept-language': 'en-GB,en;q=0.9',}nse = requests.Session()x = nse.get("https://www.nseindia.com/", headers=headers)print(x.text) Following code is working on my pc but when I put it in aws it is not responding. I have also checked ping https://www.nseindia.com/ it is working. requests is working for other sites like google but not working for this specific site on aws. In EC2: Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import requests>>> headers = {... 'authority': 'www.nseindia.com',... 'upgrade-insecure-requests': '1',... 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 OPR/72.0.3815.320',... 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',... 'sec-fetch-site': 'none',... 'sec-fetch-mode': 'navigate',... 'sec-fetch-user': '?1',... 'sec-fetch-dest': 'document',... 'accept-language': 'en-GB,en;q=0.9',... }>>> nse = requests.Session()>>> nse.get("https://www.nseindia.com/", headers=headers) No output from last line. In my PC: Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import requests>>> headers = {... 'authority': 'www.nseindia.com',... 'upgrade-insecure-requests': '1',... 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 OPR/72.0.3815.320',... 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',... 'sec-fetch-site': 'none',... 'sec-fetch-mode': 'navigate',... 'sec-fetch-user': '?1',... 'sec-fetch-dest': 'document',... 'accept-language': 'en-GB,en;q=0.9',... }>>> nse = requests.Session()>>> nse.get("https://www.nseindia.com/", headers=headers)<Response [200]>>>> Problem detected: IN EC2 ping www.nseindia.comPING www.nseindia.com (23.9.215.115) 56(84) bytes of data.64 bytes from a23-9-215-115.deploy.static.akamaitechnologies.com (23.9.215.115): icmp_seq=1 ttl=51 time=1.07 ms64 bytes from a23-9-215-115.deploy.static.akamaitechnologies.com (23.9.215.115): icmp_seq=2 ttl=51 time=1.09 ms IN PC ping www.nseindia.comPING www.nseindia.com (23.35.32.140) 56(84) bytes of data.64 bytes from a23-35-32-140.deploy.static.akamaitechnologies.com (23.35.32.140): icmp_seq=1 ttl=57 time=65.8 ms64 bytes from a23-35-32-140.deploy.static.akamaitechnologies.com (23.35.32.140): icmp_seq=2 ttl=57 time=61.5 ms64 bytes from a23-35-32-140.deploy.static.akamaitechnologies.com (23.35.32.140): icmp_seq=3 ttl=57 time=73.1 ms ping to different IP.
Now provide the response and nothing else.
| You get different IP after ping because www.nseindia.com is delivered to you through akamai CDN. So you are pinging different edge location whether you are doing this from home/work or AWS servers. What's more, IP address ranges of AWS are publicly known . Thus, its not uncommon for websites to explicitly block AWS connections, to protect from scraping, attacks or otherwise unwanted access. Thus it seems that nseindia is blocking all these AWS IP addresses. It is a known issue as indicated here and here for examples. The solution is not to use AWS nor other popular could providers (nseindia also blocks others). You could try to proxy your AWS requests through some commercial VPN maybe, home/work network, or something that is not blacklisted. Sadly, this is try-and-see approach. But you have to also consider potential legal/ethical issues of bypassing these restrictions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65121785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10549469/']} | jdg_82049 |
stackexchange | llm_judgeable_groundtruth_similarity | 88283 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was googling about how I could find the number of CPUs in a machine and I found some posts but I am confused as some mentioned that you get the logical cores vs physical cores etc. So what is the difference between logical and physical cores and is there a way I could get the physical cores only? Or does it make sense to include logical cores in our count?
Now provide the response and nothing else.
| Physical cores are just that, physical cores within the CPU. Logical cores are the abilities of a single core to do 2 or more things simultaneously. This grew out of the early Pentium 4 CPUs ability to do what was termed Hyper Threading (HTT) . It was a bit of a game that was being played where sub components of the core weren't being used for certain types of instructions while, another long running instruction might have been being executed. So the CPU could in effect work on 2 things simultaneously. Newer cores are more full-fledged CPUs so they're working on multiple things simultaneously, but they aren't true CPUs as the physical cores are. You can read more about the limitations of the hyperthreading functionality vs. the physical capabilities of the core here on tomshardware in this article titled: Intel Core i5 And Core i7: Intelβs Mainstream Magnum Opus . You can see the breakdown of your box using the lscpu command: $ lscpuArchitecture: x86_64CPU op-mode(s): 32-bit, 64-bitCPU(s): 4Thread(s) per core: 2Core(s) per socket: 2CPU socket(s): 1NUMA node(s): 1Vendor ID: GenuineIntelCPU family: 6Model: 37Stepping: 5CPU MHz: 2667.000Virtualization: VT-xL1d cache: 32KL1i cache: 32KL2 cache: 256KL3 cache: 3072KNUMA node0 CPU(s): 0-3 In the above my Intel i5 laptop has 4 "CPUs" in total CPU(s): 4 of which there are 2 physical cores (1 socket Γ 2 cores/socket = 2 cores) Core(s) per socket: 2 CPU socket(s): 1 of which each can run up to 2 threads Thread(s) per core: 2 at the same time. These threads are the core's logical capabilities. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/88283', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/42132/']} | jdg_82050 |
stackexchange | llm_judgeable_groundtruth_similarity | 7773 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page. What can I do to resolve this?
Now provide the response and nothing else.
| If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example: <asp:Label runat="server" id="Label1" style="display: none;" /> Then, you could make it visible on the client side with: document.getElementById('Label1').style.display = 'inherit'; You could make it hidden again with: document.getElementById('Label1').style.display = 'none'; Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1013/']} | jdg_82051 |
stackexchange | llm_judgeable_groundtruth_similarity | 166687 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Since it is important to me I would like to award a user who would kindly explain me what are my mistakes and what is the correct way to solve the whole problem with 500 points. I'd really like your help with understanding how to solve this Cauchy problem: $(t^2+1)(y''-2y+1)=e^t$ with the initial conditions: $y(0)=y'(0)=1$. I see a lot of methods and I am completely confused about what are the steps for solving this equation. First I wrote $$(y''-2y+1)=\frac{e^t}{(t^2+1)}.$$ I read that I need to solve first the homogeneous equation $(y''-2y+1)=0$. Do I use Abel to reduce the order of the equation? I know that I need particular solution, so $y=0.5$ would do. Now as far as I understand I need to use Wronskian determinant $$\begin{vmatrix}0.5 &y \\ 0 &y' \end{vmatrix}=c\cdot e^{\int^t_0-(2)/1 ds}=c\cdot e^{-2t}=0.5y'$$ so $y'=2ce^{-2t}$, here I can use the data given me in the beginning so $c=0.5$ and $y'=e^{-2t}$ and $y=-0.5e^{-2t}+d$ and from the initial data again $d=1.5$ and $y=-0.5e^{-2t}+1.5$. so now $y_h=-0.5e^{-2t}+1.5$ now I need to find $y_p=-0.5e^{-2t}u_1(t)+1.5u_2(t)$. Then, I wrote the floowing :$$\begin{bmatrix}-0.5e^{-2t} &1.5 \\ e^{-2t}& 0\end{bmatrix}\begin{pmatrix}u_1'\\ u_2'\end{pmatrix}=\begin{pmatrix}0\\ \frac{e^t}{(t^2+1)}\end{pmatrix}.$$ By using this system, I found $u_1$ and $u_2$ and the final solution is $y_=y_h+y_p$. Please tell me- am I right? Is this basically the way to do that? Was I allowed to divide the original solution with $(t^2+1)$ or should I had to solve $(t^2+1)(y''-2y+1)$ as a homogeneous equation? Thank you!!
Now provide the response and nothing else.
| Separating the inhomogeneous part in the usual way we find $$\begin{equation*}y''-2y = \frac{e^t}{t^2+1} - 1.\tag{1}\end{equation*}$$Notice that $y''-2y+1=0$ is not homogeneous. The solution to (1) is $y = y_h + y_p$ where $y_h$ and $y_p$ are given below. Here is the solution in terms of the exponential integral. $\def\a{\sqrt{2}}$ Homogeneous solution The homogeneous solutions to (1) are of the form $y = e^{r t}$ .Plugging this into $y'' - 2 y = 0$ we find the characteristic equation $r^2 - 2 = 0$. The roots are $\pm \a$, so $y_h = A e^{\a t} + B e^{-\a t}$.Applying the boundary conditions we find $$\begin{eqnarray*}A+B &=& 1 \\\a(A-B) &=& 1,\end{eqnarray*}$$so $A = \frac{1}{4}(2+\a)$ and $B = \frac{1}{4}(2-\a)$.Therefore,$$\begin{eqnarray*}y_h &=& \frac{1}{4}(2+\a)e^{\a t} + \frac{1}{4}(2-\a)e^{-\a t} \\&=& \cosh(\a t) + \frac{1}{\a} \sinh(\a t).\end{eqnarray*}$$ Particular solution For convenience let $a=\a$ and $f(t) = \frac{e^t}{t^2+1} - 1$,so the differential equation takes the form$$\begin{equation*}y''-a^2y = f.\tag{2}\end{equation*}$$There are many approaches to finding the particular solution to ODEs.A standard approach involves the direct use of Green's functions on (2).Let's try a different method. Let $D = d/dt$. Then $(D^2-a^2)y = f$. Formally, $$\begin{eqnarray*}y &=& \frac{1}{D^2-a^2} f \\&=& \frac{1}{(D+a)(D-a)} f \\&=& \frac{1}{2a}\left(\frac{1}{D-a} - \frac{1}{D+a}\right)f,\end{eqnarray*}$$where we have expanded in partial fractions. What is the meaning of $\frac{1}{D-a}f$? Of course it is the solution to the first order inhomogeneous ODE $$(D-a)u = f.$$The solution to this equation can be found using the integrating factor technique , $$u(t) = e^{a t} \int_0^t ds\, e^{-a s} f(s).$$The solution to $(D+a)v = f$ can be found similarly, $$v(t) = e^{-a t} \int_0^t ds\, e^{a s} f(s).$$We choose the lower limits of integration so that $u(0) = v(0) = 0$. In fact we find $u'(0) = v'(0) = 0$ so the boundary conditions will not be disturbed when we add the particular solution to $y_h$. The particular solution is then $$\begin{eqnarray*}y_p &=& \frac{1}{2a}(u-v) \\&=& -\sinh^2\left(\frac{t}{\a}\right) +\frac{1}{2\a}\left( e^{\a t} \int_0^t ds\, \frac{e^{s(1-\a)}}{s^2+1} - e^{-\a t} \int_0^t ds\, \frac{e^{s(1+\a)}}{s^2+1} \right) \\&=& -\sinh^2\left(\frac{t}{\a}\right) + \frac{1}{\a} \int_0^t ds\, \frac{e^s}{s^2+1} \sinh(\a(t-s)).\end{eqnarray*}$$The integral can be written in terms of the exponential integral, as given in the link above, but that form is not particularly enlightening. Addendum : Connection to the exponential integral . \begin{eqnarray*}\int_0^t ds\, \frac{e^{b s}}{s^2+1} &=& \int_0^t ds\, e^{b s} \frac{1}{2i}\left(\frac{1}{s-i} - \frac{1}{s+i}\right) \\&=& \int_0^t ds\, e^{b s} \mathrm{Im}\, \frac{1}{s-i} \\&=& \mathrm{Im}\,e^{i b} \int_{-i b}^{b(t-i)} dz\, \frac{e^{z}}{z} \hspace{10ex} (\textrm{let }z=b(s-i)) \\&=& \mathrm{Im}\, e^{i b} \left[ \mathrm{Ei}(b(t-i)) - \mathrm{Ei}(-i b) \right]\end{eqnarray*} | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/166687', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14829/']} | jdg_82052 |
stackexchange | llm_judgeable_groundtruth_similarity | 45353730 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Outside of Flutter, when I implement firebase authentication I always use the onAuthStateChanged listener provided by firebase to determine if the user is logged in or not and respond accordingly. I am trying to do something similar using flutter, but I can find a way to access onAuthStateChanged of Firebase. I am using the firebase_auth, and google_signin Flutter plugins. I am working of example code that is included with the firebase_auth Flutter plugin. Below is the sample code. I can login successfully with google sign in, but the example is too simple, because I want to have an observer/listener to detect the user's signed in/out state. Is there a way to detect via observer/listener using the firebase_auth/google_signin flutter plugins to determine the status of a user? Ultimately I want the app to determine if the user is logged in (yes/no). If not then show a login screen, if yes then show my main app page. import 'dart:async';import 'dart:io';import 'package:flutter/material.dart';import 'package:firebase_auth/firebase_auth.dart';import 'package:google_sign_in/google_sign_in.dart';final FirebaseAuth _auth = FirebaseAuth.instance;final GoogleSignIn _googleSignIn = new GoogleSignIn();void main() { runApp(new MyApp());}class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Firebase Auth Demo', home: new MyHomePage(title: 'Firebase Auth Demo'), ); }}class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { Future<String> _message = new Future<String>.value(''); Future<String> _testSignInAnonymously() async { final FirebaseUser user = await _auth.signInAnonymously(); assert(user != null); assert(user == _auth.currentUser); assert(user.isAnonymous); assert(!user.isEmailVerified); assert(await user.getToken() != null); if (Platform.isIOS) { // Anonymous auth doesn't show up as a provider on iOS assert(user.providerData.isEmpty); } else if (Platform.isAndroid) { // Anonymous auth does show up as a provider on Android assert(user.providerData.length == 1); assert(user.providerData[0].providerId == 'firebase'); assert(user.providerData[0].uid != null); assert(user.providerData[0].displayName == null); assert(user.providerData[0].photoUrl == null); assert(user.providerData[0].email == null); } return 'signInAnonymously succeeded: $user'; } Future<String> _testSignInWithGoogle() async { final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final FirebaseUser user = await _auth.signInWithGoogle( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); assert(user.email != null); assert(user.displayName != null); assert(!user.isAnonymous); assert(await user.getToken() != null); return 'signInWithGoogle succeeded: $user'; } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new MaterialButton( child: const Text('Test signInAnonymously'), onPressed: () { setState(() { _message = _testSignInAnonymously(); }); }), new MaterialButton( child: const Text('Test signInWithGoogle'), onPressed: () { setState(() { _message = _testSignInWithGoogle(); }); }), new FutureBuilder<String>( future: _message, builder: (_, AsyncSnapshot<String> snapshot) { return new Text(snapshot.data ?? '', style: const TextStyle( color: const Color.fromARGB(255, 0, 155, 0))); }), ], ), ); }} Here are links to the flutter packages in question: https://github.com/flutter/plugins/tree/master/packages/firebase_auth https://github.com/flutter/plugins/tree/master/packages/google_sign_in
Now provide the response and nothing else.
| I know this question is pretty old, but here is the answer if anybody is still looking for it. Firebase returns a Stream of FirebaseUser with it's onAuthStateChanged function. There are many ways to listen to the user's authentication state change. This is how I do it: Solution 1 I return a StreamBuilder to my App's home page, and the StreamBuilder returns specific pages based on the auth status of the user. @overrideWidget build(BuildContext context) { return MaterialApp( title: 'Your App Name', home: _getLandingPage() );}Widget _getLandingPage() { return StreamBuilder<FirebaseUser>( stream: FirebaseAuth.instance.onAuthStateChanged, builder: (BuildContext context, snapshot) { if (snapshot.hasData) { if (snapshot.data.providerData.length == 1) { // logged in using email and password return snapshot.data.isEmailVerified ? MainPage() : VerifyEmailPage(user: snapshot.data); } else { // logged in using other providers return MainPage(); } } else { return LoginPage(); } }, );} Solution 2 You can create a listener in your app's initState() function as well. Make sure the firebase app has been initialized before registering the listener. @overridevoid initState() { super.initState(); FirebaseAuth.instance.authStateChanges().listen((firebaseUser) { // do whatever you want based on the firebaseUser state });} Solution 3 (Update May 2021) A simple approach with null-safety without using the provider package: void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(App());}class App extends StatefulWidget { @override _AppState createState() => _AppState();}/// State is persistent and not rebuilt, therefore [Future] is only created once./// If [StatelessWidget] is used, in the event where [App] is rebuilt, that/// would re-initialize FlutterFire and makes our app re-enter the/// loading state, which is undesired.class _AppState extends State<App> { final Future<FirebaseApp> _initFirebaseSdk = Firebase.initializeApp(); final _navigatorKey = new GlobalKey<NavigatorState>(); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, navigatorKey: _navigatorKey, theme: theme(), home: FutureBuilder( future: _initFirebaseSdk, builder: (_, snapshot) { if (snapshot.hasError) return ErrorScreen(); if (snapshot.connectionState == ConnectionState.done) { // Assign listener after the SDK is initialized successfully FirebaseAuth.instance.authStateChanges().listen((User? user) { if (user == null) _navigatorKey.currentState! .pushReplacementNamed(LoginScreen.routeName); else _navigatorKey.currentState! .pushReplacementNamed(HomeScreen.routeName); }); } return LoadingScreen(); }), routes: routes, ); }} This approach guarantees that you only use Firebase authentication FirebaseAuth.instance.authStateChanges().listen() after the SDK completes initialization. The auth change listener will be first invoked on app launch and then automatically called again after logout and login. .pushReplacementNamed() will move to a new screen without back (no back icon on the app bar) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45353730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1418445/']} | jdg_82053 |
stackexchange | llm_judgeable_groundtruth_similarity | 48039187 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I noticed something odd when trying to use the comma operator inside the conditional (ternary) operator for logging. Here's a contrived example: const a = 2;const b = 1;a > b ? console.log(a), a : b; //I expect this to log and evaluate to a But instead I'm met with this: Uncaught SyntaxError: Unexpected token , According to the MDN documentation , the conditional operator accepts two expressions as the 'if' and 'else' cases of the ternary operator, and the comma operator theoretically is an expression as, The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. So why do I get a syntax error? The comma operator is an expression which should be allowed to be in a conditional operator. Although, putting parentheses around the comma's operands works fine: a > b ? (console.log(a), a) : b; //Logs and gives a Why does that work fine? Parentheses (or the grouping operator ) allows the interpreter to know it's dealing with an expression, but console.log(a), a is already an expression without the need of parentheses, so why do I get a syntax error without them?
Now provide the response and nothing else.
| This is an intentional part of the language, and is outlined in the ECMAScript Language Specification . The syntax for the comma operator is defined in Section 12.16 , which states the following: 12.16 Comma Operator ( , ) Syntax Expression: AssignmentExpression Expression, AssignmentExpression Here, the specification outlines how the comma operator is used. An Expression is any AssignmentExpression or itself followed with a comma (the operator) and another AssignmentExpression . The important thing to note is that an AssignmentExpression is an Expression but an Expression is not an AssignmentExpression . As for the actual conditional operator, the grammar for the operator and conditional expressions is specificed in Section 12.14 : 12.14 Conditional Operator ( ? : ) Syntax ConditionalExpression : LogicalORExpression LogicalORExpression ? AssignmentExpression : AssignmentExpression By the specification, a conditional expression can only contain AssignmentExpression s -- not just Expression s. Thus a conditional operator cannot have a comma operator inside one of its operands. This may seem like a weird quirk of language, but there is a specific reason considering the very specific grammar, and per the specification: NOTE Β Β The grammar for a ConditionalExpression in ECMAScript is slightly different from that in C and Java , which each allow the second subexpression to be an Expression 1 but restrict the third expression to be a ConditionalExpression . The motivation for this difference in ECMAScript is to allow an assignment expression to be governed by either arm of a conditional and to eliminate the confusing and fairly useless case of a comma expression as the centre expression. Because of Java and C's restrictive grammar, they do not allow things like this (Java): int a = 2;int b = 1;System.out.println(a > b ? b = a : a = b); //Can't use assignment in 'else' part// ^^^^^ ECMAScript authors decided to allow for assignment in both branches of the ternary operator, thus this definition with AssignmentExpression occurred. Consequently, this definition also disallows for the comma operator to actually show up in the 'if' part of the conditional operator, but because of its scarcity and uselessness it wasn't a problem. They essentially killed two birds with one stone; allowed for more lenient grammar and got rid of useless syntax that's bad practice. The reason why adding the grouping operator allows it to work is because the grouping operator production ( Expression ) is by definition also an AssignmentExpression allowing it to be in the ternary operator, see str's answer for more details. 1 This refers to Java's Expression , not ECMAScript's Expression . Java's does not have the comma operator so its Expression does not include it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48039187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5647260/']} | jdg_82054 |
stackexchange | llm_judgeable_groundtruth_similarity | 8355 |
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know how to determine the moment of inertia of the filled circular sector shown below? Apparently I have to use $dA=r\ d\theta\ dr$, $y= r\sin(\theta)$ and end up getting $I_x=\frac{r^4}{8}(\alpha-\sin(\alpha))$ But I have no idea how they got that, I have never had this.Could someone step by step explain how to get to $I_x$ with this question and how to integrate something that has two different differentials.
Now provide the response and nothing else.
| Since you actually asked for the moment about the $x$ axis. Calculating the moment of inertia about the $x$ axis is a fair deal more complicated than calculating it about the $z$ axis as in my other answer. To start with, we will recognize that the symmetry about the $x$ axis lets us only work on the top half and then multiply by a factor of 2 in the end. Now, only looking at the top half we can break the piece up into two sections: $I_1$ is on the left and is a triangle and $I_2$ is on the right and is a right triangle with a circular hypotenuse. Since this is clearly a homework problem, I'm going to skip the algebra steps and just show you the core parts of the problem (i.e. I'm going to use Mathematica to do the brute force algebra and integration). $I_1$ Calculation The moment of inertia is given by $$I_1=\rho\iint y^2\ dydx,$$where $\rho$ is the mass density per unit area, which looks simple enough. The difficulty is just in getting the correct limits of the double integral. For a a given position along the $x$ axis, the limits of $y$ range from $0$ to $x\tan(\alpha/2)$. And we will integrate $x$ from 0 to $r_0\cos(\alpha/2)$. This gives$$\begin{align}I_1&=\rho\int_0^{r_0\cos(\alpha/2)}dx\int_0^{x\tan(\alpha/2)}dy\ y^2\\&=\rho\int_0^{r_0\cos(\alpha/2)}dx\ x^3\tan^3(\alpha/2)\\&=\rho\frac{r_0^4}{12}\sin^3(\alpha/2)\cos(\alpha/2)\end{align}$$This simplifies to $\frac{\rho}{12} bh^3$ which is the well known value for the moment of inertia of a triangle . $I_2$ Calculation This one goes the same way as the last one, but the limits and the integration are more difficult. This time $x$ will vary from $r_0\cos(\alpha/2)$ to $r_0$. Over that range $y$ will vary from 0 to $\sqrt{r_0^2-x^2}$. Putting this into the integral gives$$\begin{align}I_2&=\rho\int_{r_0\cos(\alpha/2)}^{r_0}dx\int_0^{\sqrt{r_0^2-x^2}}dy\ y^2\\&=\frac{\rho}{3}\int_{r_0\cos(\alpha/2)}^{r_0}dx\ (r_0^2-x^2)^{3/2}\\&=\frac{\rho}{96}r_0^4\left(6\alpha-8\sin(\alpha)+\sin(2\alpha)\right)\end{align}$$That last integral was quite tricky, and I ended up just plugging it into Mathematica. I'm sure it is possible to find it in the standard integral tables though. All together now Finally, putting everything together and working through some trig identities simplifies the whole thing to$$2(I_1+I_2)=\frac{\rho}{8}r_0^4(\alpha-\sin\alpha)$$Which is again what we expect from the standard table for a circular segment . | {} | {'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/8355', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/4117/']} | jdg_82055 |
stackexchange | llm_judgeable_groundtruth_similarity | 56486877 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm seeing differences between Firefox and Safari in the last digit of the output from Math#atan2 . My code: Math.atan2(-0.49999999999999994, 0.8660254037844387) Safari (12.1.1) gives -0.5235987755982988 but Firefox (Mac/67.0) gives -0.5235987755982987 . This is of course a tiny difference. However, it seems that all implementations should yield the same output across all inputs. A difference like this could, for example, cause an if statement to follow different paths depending on browser. Does what I'm seeing violate any version of the ECMAScript spec?
Now provide the response and nothing else.
| The ECMAScript 2015 spec has this to say: The behaviour of the functions acos, acosh, asin, asinh, atan, atanh, atan2, cbrt, cos, cosh, exp, expm1, hypot, log,log1p, log2, log10, pow, random, sin, sinh, sqrt, tan, and tanh is not precisely specified here except to require specific results for certain argument values that represent boundary cases of interest. For other argument values, these functions are intended to compute approximations to the results of familiar mathematical functions, but some latitude is allowed in the choice of approximation algorithms.The general intent is that an implementer should be able to use the same mathematical library for ECMAScript on a given hardware platform that is available to C programmers on that platform. Although the choice of algorithms is left to the implementation, it is recommended (but not specified by this standard) that implementations use the approximation algorithms for IEEE 754-2008 arithmetic contained in fdlibm, the freely distributable mathematical library from Sun Microsystems ( http://www.netlib.org/fdlibm ). The 5.1 spec has similar language. So I think it's safe to say this behavior doesn't violate the spec. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56486877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54426/']} | jdg_82056 |
stackexchange | llm_judgeable_groundtruth_similarity | 37464875 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is terraform destroy needed before terraform apply ? If not, what is a workflow you follow when updating existing infrastructure and how do you decide if destroy is needed?
Now provide the response and nothing else.
| That would be pretty non-standard, in my opinion. Terraform destroy is only used in cases where you want to completely wipe your infrastructure. One of the biggest features of terraform is that it can do an intelligent delta of your desired infrastructure and your existing infrastructure and only make the changes needed. By performing a refresh , plan and apply you can ensure that terraform: refresh - Has an up-to-date understanding of your current infrastructure. This is important in case anything was changed manually, outside of your terraform script. plan - Prepares a list for you to review of what terraform intends to modify, or delete (or leave alone). apply - Performs the changes laid out in the plan. By executing these 3 commands in sequence terraform will only perform the changes necessary, in the order required, to bring your environments in line with any changes to your terraform file. Where I find destroy to be useful is in non-production environments or in cases where you are performing a restructure that's so invasive that starting from scratch would ensure a safer build. *There are also edge cases where terraform may fail to understand the correct order of operations (do I modify a security group first or a security group rule?), or it will find itself in a dependency cycle and will be unable to perform an operation. In those cases, however, running destroy is a nuclear solution. In general, I would perform the problem change manually (via command line, or AWS Console, if I'm in AWS), to nudge it along and then run a refresh , plan , apply sequence to get back on track. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37464875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1434070/']} | jdg_82057 |
stackexchange | llm_judgeable_groundtruth_similarity | 423632 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A bullet of mass 20 g travelling horizontally with a speed of 500 m/s passes through the wooden block of mass 10 kg initially at rest . The bullet emerges with a speed 100 m/s and the block slides 20 cm before coming to rest. Find friction coefficient between block and surface My teacher solved this question by conserving momentum between the bullet and the block. But how can he do that when there is external force (friction) acting on the system? I think impulse momentum theorem is used in such scenarios, but how can I apply it in this problem?
Now provide the response and nothing else.
| The teacher is assuming that the bullet passes through instantaneously. In other words, the bullet moves so quickly that there is no time for friction to act. Hence, the momentum that the bullet loses is entirely transferred to the block, and none is transferred to the ground via friction. An appropriate follow-up question would be, is this a reasonable assumption to make? Let's take friction into account and try to estimate how fast the block would actually be moving when the bullet exits. We know the bullet is traveling at $\frac{500\text{ m/s}+100\text{ m/s}}{2}\approx300\text{ m/s}$ on average through the block. If the block is wood and cubic in shape, then the block is only ~0.3 m wide.* Hence, the bullet would pass through the block in a time of: $$t=\frac{d}{v}=\frac{0.3\text{ m}}{300\text{ m/s}}=0.001\text{ s}$$ Your teacher calculated that the block reaches a speed of 0.8 m/s as a result of the collision with the bullet. That's a high estimate, because it ignores friction with the ground, which slows the block. But let's go ahead and assume that, while the bullet is in the block, the block's average speed is $\frac{0+0.8\text{ m/s}}{2}\approx0.4\text{ m/s}$. At this speed, and for a time of 0.001 s, the block would only travel a distance of $$d=vt=(0.4\text{ m/s})(0.001\text{ s})=0.0004\text{ m}$$ while in contact with the bullet. If the coefficient of friction is ~0.16, and if we use $g=10\text{ m/s}^2$, then the block's final speed when the bullet exits would be: $$\Delta KE=Fd\cos(180Β°)=(-0.16*100\text{ N}*0.0004\text{ m})=-0.0064 \text{ J}$$ $$\Delta KE=\frac{1}{2}mv_f^2-\frac{1}{2}mv_i^2$$ $$-0.0064\text{ J}=\frac{1}{2}(10\text{ kg})(v_f^2-(0.8\text{ m/s})^2)$$ $$v_f\approx0.799\text{ m/s}$$ There are plenty of things wrong with this calculation (for example, I'm assuming the block immediately reaches a max speed of 0.8 m/s upon collision with the bullet, which isn't true). But as an order of magnitude estimate, it's reasonable enough to show that friction doesn't have much impact on the block while the bullet is inside. *The density of wood is ~500 kg/m 3 , so $l=V^{1/3}=(\frac{m}{\rho})^{1/3}=(\frac{10\text{ kg}}{500\text{ kg/m}^3})^{1/3}\approx0.3$. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/423632', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/202319/']} | jdg_82058 |
stackexchange | llm_judgeable_groundtruth_similarity | 19491654 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am not able to understand the compilation errors below. First file is a header, test_weak.h : #ifndef TEST_WEAK_H#define TEST_WEAK_H #ifndef __ASSEMBLER__const char* const TUTU __attribute__((weak)) ="TUTU";const char* TUTU_DATE __attribute__((weak)) = __DATE__;const char* const tutu ="tutu"; #endif /*ASSEMBLER*/#endif /*TEST_WEAK_H*/ Second file is the main test.cpp : int main (){ return 42;} To compile I run: g++ -include test_weak.h test.cpp -o test Compilation result is : In file included from <command-line>:0:0:./test_weak.h:5:44: error: weak declaration of βTUTUβ must be public I am able to run successfully this code by replacing cpp extension by c extension on test source file and using gcc instead of g++. I am also able to fix this error by removing the weak attribute or removing the second const. So yeah I am able to fix the compilation error but no to able to understand the reason of the problem here. For example this line compile without trouble: const char* TUTU __attribute__((weak)) ="TUTU"; Why I cannot use a const char* const + weak attribute with c++ ?
Now provide the response and nothing else.
| The weak attribute tells the linker how to handle multipledefinitions of the same entity in different translation units.In C++, for it to be relevant, the entity must have externallinkageβthat's what the linker means by "public". In C++,a variable which is itself const has internal linkage bydefault. What you probably want is: extern char const* const TUTU __attribute__((weak)) = "TUTU"; Formally, this would be undefined behavior in C++ (without the __attribute__ , which isn't C++). The purpose of the weakattribute is to allow it, with all instances sharing the samememory (and it will result in undefined behavior, or at leastunspecified, if any of the instances have a differentinitializer. Actually: what you probably want is: extern char const TUTU[] __attribute__((weak)) = "TUTU"; No point in introducing the pointer for nothing. EDIT: Note that this is one of the differences between C and C++. InC, the const has no impact on linkage. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19491654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1919173/']} | jdg_82059 |
stackexchange | llm_judgeable_groundtruth_similarity | 26794225 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have spent the better part of two days trying to figure this one out and no matter what I do I can't get things straightened out. Here is what is going on: Using Go and Appengine. I am running into issues when trying toget proper unit tests working. I have tried lots of structures but here is a sample of where I am now: https://github.com/markhayden/SampleIssue I am running into dependency issues in either goapp serve or goapp test -v ./src/lib1 depending on how I have my import paths set. If I use "src/lib1" for my import path and then goapp serve . My app boots and runs fine, but when I run tests I get the following failure: src/lib1/lib1.go:5:2: cannot find package "src/lib2" in any of: /Users/USERNAME/go_appengine/goroot/src/pkg/src/lib2 (from $GOROOT) /Users/markhayden/Projects/go/src/src/lib2 (from $GOPATH) Likewise, if I use "dummy/src/lib1" as my path, my tests are happy and run fine but upon goapp serve ing the app I now get: 2014/11/06 20:33:34 go-app-builder: Failed parsing input: app file lib1.go conflicts with same file imported from GOPATH Have fiddled with all sorts of different options and can't figure out how to handle dependencies and still have solid testing. Maybe its a appengine / golang bug? Or am I missing something? Any help would be very much appreciated. Thanks in advance! Updated everything based on first comment feedback. I can run tests (as I was able to do before) but I still can not serve the app. Here is what I get when running goapp serve INFO 2014-11-07 17:24:48,727 devappserver2.py:745] Skipping SDK update check.INFO 2014-11-07 17:24:48,748 api_server.py:172] Starting API server at: http://localhost:60732INFO 2014-11-07 17:24:48,751 dispatcher.py:185] Starting module "default" running at: http://localhost:8080INFO 2014-11-07 17:24:48,754 admin_server.py:118] Starting admin server at: http://localhost:8000ERROR 2014-11-07 17:24:49,041 go_runtime.py:171] Failed to build Go application: (Executed command: /Users/markhayden/go_appengine/goroot/bin/go-app-builder -app_base /Users/markhayden/Projects/go/src/github.com/markhayden/SampleIssue -arch 6 -dynamic -goroot /Users/markhayden/go_appengine/goroot -nobuild_files ^^$ -unsafe -gopath /Users/markhayden/Projects/go -print_extras_hash lib1/lib1.go lib2/lib2_test.go main_test.go main.go lib1/lib1_test.go lib2/lib2.go)2014/11/07 09:24:49 go-app-builder: Failed parsing input: app file lib2.go conflicts with same file imported from GOPATH $GOPATH = /Users/markhayden/Projects/go $GOROOT = not set (according to docs it doesnt need to be if you dont use a custom directory) App Structure: $GOPATH/src/github.com/markhayden/SampleIssue/ - app.yaml - /lib1 - lib1_test.go - lib1.go - /lib2 - lib2_test.go - lib2.go - main_test.go - main.go In main.go: import ( "fmt" "github.com/markhayden/SampleIssue/lib1" "net/http") In lib1/lib1.go: import ( "fmt" "github.com/markhayden/SampleIssue/lib2")
Now provide the response and nothing else.
| Appengine "conflicts with same file imported from GOPATH" issue: Appengine is importing things underneath the root directory (i.e. where the app.yaml is). This will cause two imports, one by appengine when it scans the directories, and a second by your source when it is explicitly imported. You have two choices: Don't use the full import path (for sub-folder packages) with appengine. Remove the source repository part of import. So instead of"github.com/blah/blah" it would be "blah/blah". Note: This kinda sucks as it makes your build and software appengine specific. You could make this a little better -maybe- by using build constraints . e.g. +build !appengine or +build !appengine to include/remove certain files from the build depending on if you are targeting appengine. Move your modules/dependencies (sub-folders) to a separate and independent project to make it work with the full path import convention: Get rid of all directories / dependencies in the main project (whereyour app.yaml is), so that appengine can't scan and find them. Move them to another independent project (I did SampleIssueDeps)with no app.yaml that is not a sub-directory (e.g./MarkHayden/SampleIssueDeps). Then pull those dependencies viafull path import. e.g. github.com/MarkHayden/SampleIssueDeps/lib1. Summary: For sub-folder packages in an appengine project don't include the "source repository" part of the import path OR only use appengine to init() and move all of your other code to separate projects and use like external dependencies. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26794225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2330325/']} | jdg_82060 |
stackexchange | llm_judgeable_groundtruth_similarity | 3487690 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I initialise two-dimentional typed Vector is AS3? Now I can get working only this: private var _mainArray : Array = new Array( MyConst.DIMENTION );public function MyArray() { for ( var i : int = 0; i < MyConst.DIMENTION; i++ ) { _mainArray[ i ] = new Vector.<int>( MyConst.DIMENTION ); }}..._mainArray[ i ][ j ] = 0;
Now provide the response and nothing else.
| What you have is an Array of Vector of int. What you want is a Vector of Vector of int. So your "outer" Vector has to declare that contains elements of type Vector.<int> Something like this (of course you can use a for loop): var v:Vector.<Vector.<int>> = new Vector.<Vector.<int>>(2); v[0] = new Vector.<int>(2); v[1] = new Vector.<int>(2); v[0][0] = 0; v[0][1] = 1; v[1][0] = 2; v[1][1] = 3; trace(v); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3487690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416514/']} | jdg_82061 |
stackexchange | llm_judgeable_groundtruth_similarity | 192402 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When dealing with differentiable surfaces one defines a function $f:S\rightarrow \mathbb{R}$ as being differentiable if its expression in local coordinates is differentiable. But one could also define it to be differentiable if there exists differentiable function $F: V\subset \mathbb{R}^3 \rightarrow \mathbb{R}$ from an open set $V$ of $\mathbb{R}^3$ such that $S\subset V$ and $F|_{S} = f$, i.e. a differentiable extension of $f$. Are these two definitions of differentiability equivalent? More precisely, when given a differentiable function on a surface can you always extend it to a differentiable function of an open set of $\mathbb{R}^3$ containing the surface?
Now provide the response and nothing else.
| Let $$ f(x,y) = \begin{cases} (x,y) & xy > 0 \\ 0 & xy \leq 0 \end{cases} $$ It is clear that $cf(\vec{z}) = f(c\vec{z})$ for any $c\in \mathbb{R}$. But $f$ is not a linear map. further counter examples can be constructed in polar coordinates. Let $(r,\omega)\in \mathbb{R}_+ \times \mathbb{S}^{n-1}$ denote the spherical coordinates of $\mathbb{R}^n$. Then a map $$ f(r,\omega) = (\lambda(\omega)r,\omega) $$ satisfies $cf(\vec{v}) = f(c\vec{v})$ for every $\lambda:\mathbb{S}^{n-1}\to \mathbb{R}$ that satisfies $\lambda(\omega) = \lambda(-\omega)$. Clearly many of these are not linear. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/192402', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5209/']} | jdg_82062 |
stackexchange | llm_judgeable_groundtruth_similarity | 157282 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have s imple, general question regarding calculating statistic for N runs of the same experiment. Suppose I would like to calculate mean of values returned by some Test. Each run of the test generates $ \langle x_1 ... x_n \rangle$ , possibly of different length. Let's say the statistic is mean. Which approach would be better and why: Sum all values from M runs, and then divide by number of values for each run calculate average, and then average across all averages I believe one of the above might beunder/overestimating the mean slightly and I don't know which. Thanks for your answers.
Now provide the response and nothing else.
| The first map you define is not even a map (except if you consider only the set structure and if the base field is $\Bbb F_2$). In $\Bbb P^1$, the points $[ x : y ]$ and $[ \lambda x : \lambda y ]$ are the same for all non zero $\lambda$ in the base field. So their image must be the same. But obviously all the $[\lambda x : \lambda y : 1 ]$ are not equal. The second one is a morphism, defined everywhere, but it's not birational since its image is not dense in $\Bbb P^2$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/157282', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26080/']} | jdg_82063 |
stackexchange | llm_judgeable_groundtruth_similarity | 80273 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $G_d$ be the group with the following presentation$$\langle x,y \mid x^{2^{d+1}}=1, x^4=y^2, [x,y,x]=x^{2^{d}}, [x,y,y]=1\rangle,$$where $d>2$ is an integer.It is clear that $G_d$ is a finite $2$-group of nilpotency class at most $3$.It is easy to see that $[x,y]^2=1$ and since the quaternion group $Q_8$ of order $8$ is a quotient of $G_d$, $[x,y]$ has order $2$. So the nilpotency class of $G_d$ is $2$ or $3$. The computation with GAP shows that $G_d$ is nilpotent of class exactly $3$, whenever $d=3,4,5,6,7,8,9$. Question: Is the nilpotency class of $G$ $3$?
Now provide the response and nothing else.
| The nilpotency class of $G_d$ is indeed always 3. One way to see this is to rewrite the presentation of $G_d$ in such a way to exhibit that it is a polycyclic group. For this purpose, let $z:=[x,y]$ and $w:=y^{2^{d-1}}=x^{2^d}$. Clearly $w$ lies in the center of $G_d$. With a little more effort we see that$$ G_d \cong \langle x, y, z, w\mid x^4 = y^2, y^{2^{d-1}} = w, z^2 = w^2 = 1 ; y^x = yz, z^x = zw, z^y = z, w^x=w^y=w^z=w \rangle $$ This is indeed a polycyclic presentation, with relative order $4, 2^{d-1}, 2, 2$. (Thus the group has order $4* 2^{d-1}* 2* 2=2^{d+3}$). But now it is easy to read off that $[G_d,G_d] = \langle z, w\rangle$, and thus $[[G_d,G_d],G_d]=\langle w \rangle$, which is central. Hence the nilpotency class is 3. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/80273', 'https://mathoverflow.net', 'https://mathoverflow.net/users/19075/']} | jdg_82064 |
stackexchange | llm_judgeable_groundtruth_similarity | 6986861 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
devise_for creates routes including a DELETE route, which we want to remove, and devise_for doesn't support an :except or :only option. How can I remove a route from Rails.application.routes ? Either in the draw block, or afterward? Here are details of a bug, which was the reason we needed to remove the route. we were issuing a DELETE request to a custom UJS controller action in the controller action we were removing what we wanted to, then doing a 302 redirect. This was a bad idea, and we have since corrected it by returning some JSON instead. some clients, upon receiving the 302 would issue a new DELETE request to the redirect, which routes to a Devise delete route! Thereby inadvertantly deleting the person! Yikes. We were assuming this would be a GET. Bad assumption. This bug has been fixed, but i would like to remove the route nonetheless. Here is what I did in the end, which was suggested by the bounty-winner in his quote from JoseΒ΄ Valim: In config/routes.rb , I added this above the devise_for call, which sets up the rest of my 'people' routes: delete '/person', :to => 'people#destroy' Then in my existing people_controller.rb , I added a no-op method: def destroy render :nothing => trueend I'm still a little irked that there isn't a simple way to just remove the route from the RouteSet. Also, the delete route still exists for the devise controller, but it won't get called because rails looks for the first match in config/routes.rb and returns it.
Now provide the response and nothing else.
| Here is what Jose Valim (the author of devise) has to say on the subject : There is no way to remove routes individually. Or you use :skip to remove all and draw the ones you need manually or you overwrite this routes by defining a route to the same path first in your config/ routes.rb So the short answer to your question is no, you can't delete that one route. You can of course try doing things like patching the devise_for method, but that would be a somewhat involved undertaking (a day or several worth of effort). I'd just use the :skip option, then implement the routes you do want for that controller and leave off the one that you don't. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6986861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415409/']} | jdg_82065 |
stackexchange | llm_judgeable_groundtruth_similarity | 27091805 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to execute a command with gradle with the below task: task stopServer(dependsOn: war, type: Exec) << { commandLine 'pkill -9 tomcat'} When I run it I get the following error: * What went wrong:Execution failed for task ':stopServer'.> execCommand == null! And when my task is like this: task stopServer(dependsOn: war) << { exec { commandLine 'pkill -9 tomcat' }} I get this error: * What went wrong:Execution failed for task ':stopServer'.> A problem occurred starting process 'command 'pkill -9 tomcat'' Can you tell me where I am going wrong in each of these approaches? If neither of above are right way of executing then please specify the way of doing it probably with an example.
Now provide the response and nothing else.
| I believe you're looking for this: task stopServer(dependsOn: war, type: Exec) { commandLine "pkill", " -9", "tomcat"} The main difference is very subtle - I just deleted two characters. The << is gone from the task definition. The other difference is that the commandLine expects the executable to be passed in separately from the arguments to it. I removed the << because of an important idea in gradle: the build lifecycle . There's configuration and execution phases (that's not all, but it's enough to explain this). The << is like saying doLast - it adds the closure you pass to the end of the actions (the execution phase ) for this task. So that means here, it's going to try and execute the command like normal (it's an Exec object, after all), and only then , once it's executed, will it call your block - the block setting commandLine . So when it's executing, execCommand really is null, and would be until your block was run. This is the heart of your problem. Without the << (also known as left-shift), that same block runs during the configuration phase. So the exec command gets set before it runs, and it works. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27091805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1385441/']} | jdg_82066 |
stackexchange | llm_judgeable_groundtruth_similarity | 25061547 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am feeling really stupid and not sure if doing something really dumb what... so excuse me in advance. I have the following HTML: <input type="text" value="0" name="pcscubes" id="pcscubes"> I have the below jquery syntax: var cubes=123.2;$("#pcscubes1").val(cubes);var test=$("#pcscubes1").val();alert(test); When the jquery executes, the input box will display 123.2 and the alert will be 123.2. if you inspect the html object though, the value is still 0? so the display of the input is different from what the real value is. so when I submit this form it posts 0 rather than 123.2 Now I have built a whole web app with this syntax and works perfectly. today it just stops working? I have restarted browser, checked old code that was working, logged off and on and still it does the same. web app obviously has jquery loaded and jquery ui on this form. using codeigniter? any ideas as I am banging my head over something so stupid.... Out of interest I created the below fiddle and it is doing the same? http://jsfiddle.net/49nqU/ why is the value 0 when it is showing 123.2? Thanks as always,
Now provide the response and nothing else.
| This is a case of attributes vs. properties. What you are seeing in the inspector is the value attribute , which does not update when you programmatically update a field's value property. Pay no attention to what the DOM inspector says; it'll only show the value as it was when the page loaded (unless you explicitly change the field's value attribute rather than, as jQuery's val() does, its value property .) Further reading: http://jquery-howto.blogspot.co.uk/2011/06/html-difference-between-attribute-and.html Some attributes are closely tied to their property counterparts. That is to say, updating the property also updates the attribute. This is the case, for example, with the class attribute and its className property counterpart. value , however, is different; updating the property does not update the attribute (but, just to confuse things further, updating the attribute does update the property!) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25061547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/940173/']} | jdg_82067 |
stackexchange | llm_judgeable_groundtruth_similarity | 363516 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For people who will use an API, is it easier to see: /createUser/getUser/id/editUser/id The standard is to use nouns in URI eg: /user/ POST (Create a user)/user/ GET (Get list of users) A developer is insisting on using verbs because it is easier for others. But I think there must be some real technical debts to pay later on, other than just a case of bad "grammar" and people laughing at us?
Now provide the response and nothing else.
| Standard URL mapping for REST has the resource mapped to the URL and what you do to it in the HTTP method. It works well when interacting programmatically with your REST endpoint. It's also very discoverable and consistent: if you get a link to a resource, you know you can try other methods and - if supported - they'll behave in a standard CRUD pattern. However, it can be somewhat inconvenient to debug from a browser, because they're not really design to do anything else than GET from the URL bar - so you need extra plugins (or use CURL/other tools). Unfortunately, using the non standard mapping in the question (e.g. '/editUser/id') alone doesn't really solve that issue - you still need a body to go with the request, so I don't see how that makes it easier. Or lots of URL query parameters, but that breaks the symmetry between actions. If by 'easier for others' your dev is meaning 'easier on people that try to access it from a basic browser for anything other than GET', then a way to do that would be to stick to the basic resource mapping but (optionally) stick the verb/method in a query parameter, e.g. /user/?action=DELETE. I'd still support the standard HTTP methods and make the above totally optional, not best practice, and for debugging/manual exploration only. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/363516', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/200195/']} | jdg_82068 |
stackexchange | llm_judgeable_groundtruth_similarity | 37166102 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The code is almost straight from the ui-bootstrap tutorial. I have a button on my homepage with an ng-click for opening the modal window, but the error I receive in dev tools is : Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- modalController and each click after this adds a modalController to the error message, like Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- modalController <- modalController Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- modalController <- modalController <- modalController home.js 'use strict';angular.module('myApp') .controller('homeCtrl', ['$q', '$state', '$timeout', '$scope', '$http', '$filter', '$uibModal', function($q, $state, $timeout, $scope, $http, $filter, $uibModal){$scope.open = function (size){ var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'app/main/searchModal.html', controller: 'modalController', size: size, resolve: { items: function () { return $scope.items; } } }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { });};... modalcontroller.js 'use strict';angular.module('myApp').controller('modalController', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.items = items; $scope.selected = { item: $scope.items[0] }; $scope.ok = function () { $uibModalInstance.close($scope.selected.item); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; $uibModalInstance.close();}]);
Now provide the response and nothing else.
| You need custom ApplicationUser inherit from IdentityUser<TKey> and custom Role inherit from IdentityRole<TKey> public class ApplicationUser : IdentityUser<Guid> { } public class Role : IdentityRole<Guid> { } Custom context class inherit from IdentityDbContext<ApplicationUser, Role, TKey> and use fluent api for auto generate guid keys. public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, Guid>{ protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<ApplicationUser>(b => { b.Property(u => u.Id).HasDefaultValueSql("newsequentialid()"); }); builder.Entity<Role>(b => { b.Property(u => u.Id).HasDefaultValueSql("newsequentialid()"); }); }} then in Startup add Identity service to container like this services.AddIdentity<ApplicationUser, Role>() .AddEntityFrameworkStores<ApplicationDbContext, Guid>() .AddDefaultTokenProviders() .AddUserStore<UserStore<ApplicationUser, Role, ApplicationDbContext, Guid>> () .AddRoleStore<RoleStore<Role, ApplicationDbContext, Guid>>(); If you have not created the database, clear the migrations folder and run ef commands | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37166102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2744863/']} | jdg_82069 |
stackexchange | llm_judgeable_groundtruth_similarity | 32161105 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm building an MVC application in ExtJs 4.2 and there is a window and a formpanel. Form panel has few hidden textfields which i want to show/hide. When I run this commands: Ext.getCmp('PartsSell').show(); or Ext.getCmp('PartsSell').setVisible(true); even Ext.widget('ObjectForm').getForm().findField('PartsSell').setVisible(true); nothing is happening!! Here is formpanel snippet: Ext.define('crm.view.ObjectForm', { extend : 'Ext.form.Panel', header : false, alias : 'widget.ObjectForm', url : 'action.php', id : "ObjectForm", defaultType : 'textfield', initComponent: function() { Ext.apply(this, { items : [ { fieldLabel : 'label', labelWidth : 115, hidden : true, allowBlank : true, name : 'PartsSell', itemId : 'PartsSell', xtype : 'textfield', vtype : 'DigitsVtype', width : 150, padding : '0 0 0 15' }, /* other stuff */] } ); this.callParent(arguments); }} ); FF/chrome console behaves like everything is OK. If i set 'hidden' param to 'false' the field is shown. According to Tarabass and Drake advices: I've changed id on itemId . And now i can trigger field by Ext.ComponentQuery.query('#PartsSell')[0].hide() / .show();
Now provide the response and nothing else.
| It's because bessie is declared Animal rather than Cow . bessie.SuitableFood is a "path-dependent type" (see below). Try this: val clarabelle: Cow = new Cowclarabelle eat (new Grass) This works because the compiler can deduce that clarabelle.SuitableFood = Grass from clarabelle 's declared type. Since bessie is declared Animal , not Cow , the compiler can't safely deduce that bessie.SuitableFood = Grass .* When you say new bessie.SuitableFood , the compiler generates code to look at the actual bessie object and generate a new instance of the appropriate type. bessie.SuitableFood is a "path-dependent type": the " path " (the bessie. part) that leads to the last identifier ( SuitableFood ) is actually part of the type. This enables you to have a custom version of a type for each individual object of the same class. * Well, actually, I think that if the compiler were a little smarter, it could deduce that bessie.SuitableFood = Grass , since bessie is a val , not a var , and therefore won't change its type. In other words, the compiler ought to know that even though bessie is declared Animal , she's really a Cow . Perhaps a future version of the compiler will make use of this knowledge, and perhaps there's a good reason why that wouldn't be a good idea, which someone more expert than I will tell us. (Postscript: One just did! See Travis Brown's comment below.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32161105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2428180/']} | jdg_82070 |
stackexchange | llm_judgeable_groundtruth_similarity | 25490928 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i really need this code and i searched for 3 hours on internet but i couldn't find a complete and simple code and i tested many codes but some didn't work and others wasn't good,please help me with a full and simple code,thank youedit:i have this code for select image but please give me a full code for all things that i said in title because i cant resemble codes. btn_choose.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"),SELECT_PICTURE); alertDialog1.dismiss(); } }); protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); selectedImagePath1=selectedImagePath; System.out.println("Image Path : " + selectedImagePath); image_capture1.setImageURI(selectedImageUri); }
Now provide the response and nothing else.
| Hope This Code will help you.. Activity To Select The Image From Gallery. import java.io.File;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.util.Log;public class GalleryUtil extends Activity{ private final static int RESULT_SELECT_IMAGE = 100; public static final int MEDIA_TYPE_IMAGE = 1; private static final String TAG = "GalleryUtil"; String mCurrentPhotoPath; File photoFile = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ //Pick Image From Gallery Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_SELECT_IMAGE); }catch(Exception e){ e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode){ case RESULT_SELECT_IMAGE: if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) { try{ Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); //return Image Path to the Main Activity Intent returnFromGalleryIntent = new Intent(); returnFromGalleryIntent.putExtra("picturePath",picturePath); setResult(RESULT_OK,returnFromGalleryIntent); finish(); }catch(Exception e){ e.printStackTrace(); Intent returnFromGalleryIntent = new Intent(); setResult(RESULT_CANCELED, returnFromGalleryIntent); finish(); } }else{ Log.i(TAG,"RESULT_CANCELED"); Intent returnFromGalleryIntent = new Intent(); setResult(RESULT_CANCELED, returnFromGalleryIntent); finish(); } break; } }} Activity To Crop The Selected Image: public class ImageSelecter extends Activity{ private final int GALLERY_ACTIVITY_CODE=200; private final int RESULT_CROP = 400; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); btn_choose.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Start Activity To Select Image From Gallery Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class); startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == GALLERY_ACTIVITY_CODE) { if(resultCode == Activity.RESULT_OK){ picturePath = data.getStringExtra("picturePath"); //perform Crop on the Image Selected from Gallery performCrop(picturePath); } } if (requestCode == RESULT_CROP ) { if(resultCode == Activity.RESULT_OK){ Bundle extras = data.getExtras(); Bitmap selectedBitmap = extras.getParcelable("data"); // Set The Bitmap Data To ImageView image_capture1.setImageBitmap(selectedBitmap); image_capture1.setScaleType(ScaleType.FIT_XY); } } } private void performCrop(String picUri) { try { //Start Crop Activity Intent cropIntent = new Intent("com.android.camera.action.CROP"); // indicate image type and Uri File f = new File(picUri); Uri contentUri = Uri.fromFile(f); cropIntent.setDataAndType(contentUri, "image/*"); // set crop properties cropIntent.putExtra("crop", "true"); // indicate aspect of desired crop cropIntent.putExtra("aspectX", 1); cropIntent.putExtra("aspectY", 1); // indicate output X and Y cropIntent.putExtra("outputX", 280); cropIntent.putExtra("outputY", 280); // retrieve data on return cropIntent.putExtra("return-data", true); // start the activity - we handle returning in onActivityResult startActivityForResult(cropIntent, RESULT_CROP); } // respond to users whose devices do not support the crop action catch (ActivityNotFoundException anfe) { // display an error message String errorMessage = "your device doesn't support the crop action!"; Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT); toast.show(); } } } Edit: Checkout this open source library to Pick image from Gallery or Capture new image with Camera. It will save lot of boilerplate code. https://github.com/Dhaval2404/ImagePicker | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25490928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3648435/']} | jdg_82071 |
stackexchange | llm_judgeable_groundtruth_similarity | 1909488 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Determine all fixed points of the discrete dynamical system $$x_{n + 1} = e^{x_{n}} - 2 .$$ Determine if they are asymptotically stable. How can I find the fixed points? Thank you in advance.
Now provide the response and nothing else.
| Hint : $$\frac{e^{2x}-1}{e^{2x}+1}=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}=\frac{\sinh(x)}{\cosh(x)}=\frac{u'}{u}$$ with $u=\cosh(x)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1909488', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/148244/']} | jdg_82072 |
stackexchange | llm_judgeable_groundtruth_similarity | 30961668 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example: int main() { struct {} foo; int bar[0]; struct { int dummy[0]; } baz; cout << sizeof(foo) << endl; //display '1' cout << sizeof(bar) << endl; //display '0' cout << sizeof(baz) << endl; //display '0' return 0;} Please tell me is there any reason stand behind that compiler behaviour
Now provide the response and nothing else.
| This is a C++ only issue. In C, an empty struct is prohibited by the compiler. In C++, the reason for the sizeof(foo) == 1 is ultimately so that the C++ Standard's rule of "no object shall have the same address in memory as any other variable" can be enforced. You can read the details here . EDIT : Regarding the comment by user2864740 about baz appearing that it should also be non-zero is correct. The compiler is allowing the empty array which makes it appear that the finessing rule is not being applied consistently to baz like it was to foo . This does, in fact, mess up the pointer arithmetic. See this example: // C++14 code#include <iostream>using namespace std;int main() { struct baz { int dummy[1]; }; cout << sizeof(baz) << endl; baz* arr; arr = new baz[5]; cout << &arr[0] << endl; cout << &arr[1] << endl; return 0;}// everything looks good40x892c0080x892c00c But if we take the same code and change the array inside baz to be int dummy[0]; , then we get this output: 00x8fe30080x8fe3008 Dangerous indeed; this could lead to infinite loops. It is recommended you don't be naughty like this even if you've found a way to get away with it :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30961668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2671591/']} | jdg_82073 |
stackexchange | llm_judgeable_groundtruth_similarity | 256797 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The command ContourPlot[{RealAbs[x + 1/y] + RealAbs[10/3 - x + y] == 10/3 + y + 1/y}, {x, -5, 5}, {y, -5, 5}, PlotPoints -> 50] , as one sees, draws abstraction in blue. With the options ContourPlot[{RealAbs[x + 1/y] + RealAbs[10/3 - x + y] == 10/3 + y + 1/y}, {x, -5, 5}, {y, -5, 5}, PlotPoints -> 300, WorkingPrecision -> 50] one obtains an empty plot.The command Region[ImplicitRegion[RealAbs[x + 1/y] + RealAbs[10/3 - x + y] == 10/3 + 1/y + y, {x, y}],PlotRange -> {{-5, 5}, {-5, 5}}] Region[Embedding dimension: 2] fails too.Just to compare, see the result of the the command of Maple 2021 plots:-implicitplot (abs (x + 1/y) + abs (x + 1/y) = 10/3 + y + 1/y, x = -5 .. 5, y = -5 .. 5); I think this is not only a graphics problem. Let us consider Reduce[{RealAbs[x + 1/y] + RealAbs[10/3 - x + y] == 10/3 + y + 1/y}, x, Reals] (y == -3 && x == 1/3) || (-3 < y < -(1/3) && -(1/y) <= x <= 1/3 (10 + 3 y)) || (y == -(1/3) && x == 3) || (y > 0 && -(1/y) <= x <= 1/3 (10 + 3 y)) and the result in Maple of solve (abs (x + 1/y) + abs (x + 1/y) = 10/3 + y + 1/y, x); piecewise (y < -3, [], y = -3, [1/3], y < -1/3, [(3*y^2 + 10*y - 3)/(6*y), (-3*y^2 - 10*y - 9)/(6*y)], y = -1/3, [3], y <= 0, [], 0 < y, [(3*y^2 + 10*y - 3)/(6*y), (-3*y^2 - 10*y - 9)/(6*y)]) The latter is in accordance with the plot done in Maple, whereas the former does not seem true. Is there a way to plot the implicit function under consideration in Mathematica? PS. Sorry for the poor question. My incorrect Maple code misled me (This is explanation, but not justification.).
Now provide the response and nothing else.
| You are trying to visualize the relation $$|f(x,y)| + |g(x,y)| = f(x,y) + g(x,y)$$ where $f(x,y) = x+1/y$ and $g(x,y) = \frac{10}{3} - x + y$ . In the above form, it is fairly evident that this relation is satisfied if and only if $f(x,y) \geq 0$ and $g(x,y) \geq 0$ . In other words, this equation does not define a contour ; it defines a region : RegionPlot[{Abs[x + 1/y] + Abs[10/3 - x + y] == 10/3 + y + 1/y}, {x, -5, 5}, {y, -5, 5}, PlotPoints -> 50] Increasing the value of PlotPoints leads to better definition of the "corners" at $(-3,\frac13)$ and $(-\frac13,3)$ , and also reduces the length of the spurious "stem" along the positive $x$ -axis. Knowing this, it appears that the Mathematica output you provide from Reduce (which involves allowed ranges of x for each y value) is correct. The fact that Maple outputs a 1-D curve when using plots is highly misleading; and the output of solve is correct only if (for example) [(3*y^2 + 10*y - 3)/(6*y), (-3*y^2 - 10*y - 9)/(6*y)] stands for the interval between these two endpoints. (I am not familiar enough with Maple syntax to know whether the above output stands only for two distinct points, or whether it implicitly includes the interval between them as well.) | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/256797', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7152/']} | jdg_82074 |
stackexchange | llm_judgeable_groundtruth_similarity | 74944 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
So let $D\subseteq \mathbb{C}^n$ be a bounded connected open set with a transitive action of its group of biholomorphisms (which we denote by $Hol(D)$). Note that I'm not assuming that $D$ is symmetric. We thus have that $D$ is "homeomorphic" to $Hol(D)/K$ where $K=Stab(d_0)$ for some $d_0\in D$. In the special case where $Hol(D)$ is a real Lie group and that$K$ is a maximal compact of $Hol(D)$ then by a theorem of Elie Cartan we have that$Hol(D)/K$ is homeomoprphic to $\mathbb{R}^m$ and thus contractible. Under my assumptions: (1) Is $Hol(D)$ always a Lie group? (2) Is $K$ always a maximal compact? (3) In general is $D$ always contractible (or simply connected)?
Now provide the response and nothing else.
| If it's known that some statement $S$ is decidable in ZFC, then you can just run a computer program that enumerates all ZFC-proofs and stops when it finds a proof of $S$ or a proof of $\neg S$. By hypothesis, this algorithm is guaranteed to terminate. Therefore, the only possible obstacle separating decidable statements from decided ones is computational complexity. In other words, the only possible instances of what you're looking for are statements that have already been proved up to a finite computation . Until they were actually proved, the Kepler Conjecture and Catalan's Conjecture were perhaps the most interesting examples of this type. I can't think of other examples of comparable interest offhand, but maybe others can. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/74944', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11765/']} | jdg_82075 |
stackexchange | llm_judgeable_groundtruth_similarity | 305425 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have such a reverse polarity protection circuit for the power supply: The MOSFET used has a maximum V GS of 10Β V, so that's why there's a Zener diode of 7.5Β V. But what happens if I connect, let's say, 12Β V? I don't fully understand how this Zener diode is working. It will start to conduct from 7.5Β V. So from 12Β V it will "conduct 4.5Β V" to the gate. So the voltage on the gate relatively to the ground will be +4.5Β V. But the voltage on the gate relatively to the source (V GS ) will be -7.5Β V (4.5Β V - 12Β V). This MOSFET needs around -2Β V to start to conduct. It gets -7.5Β V, so is that why it's working? Am I correct with this? Do I understand this properly?
Now provide the response and nothing else.
| If you suddenly connect +12 to the input, the source will immediately rise to +11.3 or so because of the body diode conducting. The gate will charge towards -11.3V with respect to the source through R?. When the gate reaches the threshold voltage the MOSFET channel will begin to conduct, and by the time the gate-source voltage reaches a few volts the MOSFET channel will be conducting almost all the current, the output voltage will be close to +12V. It continues to charge until it reaches about -7.5V at which point the Zener diode begins to shunt significant current away from the gate. In steady state with 12V in the gate sits at -7.5V with respect to the source, and the MOSFET happily conducts in the reverse direction to normal. Edit: Regarding the Zener gate protection I would like to graft a comment below into this answer You could replace the zener+resistor with a direct connection if you are sure there are no transients. Or with a resistor if the gate is already protected adequately internally. Or a divider under similar conditions. There is a vulnerability whenever a resistor is used in the pathological case where the supply is suddenly reversed (or, less pathologically, connected to AC) because the MOSFET gate charge may not have enough time to bleed off and the circuit downstream will get a nasty pulse at reverse polarity. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/305425', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/70502/']} | jdg_82076 |
stackexchange | llm_judgeable_groundtruth_similarity | 15823677 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My Grails service is having an issue where a swallowed exception unrelated to a transaction is causing the transaction to rollback even when it is unrelated to the persistance of the domain object. In my service I have something along the lines of updateSomething(domainObj) { def oldFilename = domainObj.filename def newFilename = getNewFilename() domainObj.filename = newFilename domainObj.save(flush: true) try { cleanUpOldFile(oldFilename) } catch (cleanupException) { // oh well, log and swallow }} What I am seeing is that when I have exception when I am cleaning up the old file, I log it and swallow it, but it still causes the transaction to rollback, even though I am already done updating the domain object. How do I limit the scope transaction to complete before the clean up or is there another way to get the clean up exception to not cause a rollback? Just for the record I am using Grails 2.1.1
Now provide the response and nothing else.
| You can use annotations to do more fine-grained transaction demarcation. By default services are transactional, and all public methods are transactional. But if you use any @Transactional annotations, Grails doesn't make everything transactional - you have complete control. Runtime exceptions automatically trigger rollbacks, but checked exceptions don't. Even though Groovy doesn't required that you catch checked exceptions, the feature is a Spring thing which doesn't know about Groovy exception handling. Transactions are implemented by wrapping your service class instance in a proxy. If an exception "escapes" the proxy, whether it's then caught or not, the rollback will have already happened. So you have a few options. Annotate updateSomething as @Transactional but don't annotate cleanUpOldFile : import org.springframework.transaction.annotation.Transactional@Transactionaldef updateSomething(domainObj) {...}def cleanUpOldFile(...) { ...} You can also annotate cleanUpOldFile with one or more unchecked exceptions that shouldn't roll back a transaction (or in other use cases checked exceptions that should), e.g. @Transactional(noRollbackFor=[FooException, BarException])def cleanUpOldFile(...) { ...} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15823677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20774/']} | jdg_82077 |
stackexchange | llm_judgeable_groundtruth_similarity | 43892402 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following code works, but it doesn't look nice as the definition of is_empty is too far away from the usage. fn remove(&mut self, index: I, primary_key: &Rc<K>) { let is_empty; { let ks = self.data.get_mut(&index).unwrap(); ks.remove(primary_key); is_empty = ks.is_empty(); } // I have to wrap `ks` in an inner scope so that we can borrow `data` mutably. if is_empty { self.data.remove(&index); }} Do we have some ways to drop the variables in condition before entering the if branches, e.g. if {ks.is_empty()} { self.data.remove(&index);}
Now provide the response and nothing else.
| Whenever you have a double look-up of a key, you need to think Entry API . With the entry API, you get a handle to a key-value pair and can: read the key, read/modify the value, remove the entry entirely (getting the key and value back). It's extremely powerful. In this case: use std::collections::HashMap;use std::collections::hash_map::Entry;fn remove(hm: &mut HashMap<i32, String>, index: i32) { if let Entry::Occupied(o) = hm.entry(index) { if o.get().is_empty() { o.remove_entry(); } }}fn main() { let mut hm = HashMap::new(); hm.insert(1, String::from("")); remove(&mut hm, 1); println!("{:?}", hm);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43892402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/691867/']} | jdg_82078 |
stackexchange | llm_judgeable_groundtruth_similarity | 5331827 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a simple password protection. I do it like this: EditText editText1 = (EditText) findViewById(R.id.editText1);String Password = editText1.getText().toString();if(Password == "a"){ Toast.makeText(getApplicationContext(), "Success" + Password, Toast.LENGTH_SHORT).show();} else { Toast.makeText(getApplicationContext(), "Failure" + Password, Toast.LENGTH_SHORT).show();} I have edittext and button. If user is typing in "a", toast should say success. But it is always saying failure. I don't understand what is wrong in my code...
Now provide the response and nothing else.
| In Java, using == for non-primitive expressions will always compare object references . You're asking whether Password refers to the exact same object as the string literal "a". Use either: if (Password.equals("a")) or if ("a".equals(Password)) These will call the String.equals(Object) override, which determines whether two references refer to equal String objects - i.e. the same logical sequence of characters. The former will throw an exception if Password is null; the latter won't. Don't treat this as a suggestion to always use the latter form - if Password shouldn't be null, then an exception may well be better than continuing in an unexpected state. I'd also encourage you to be consistent with your variable names - typically local variables are camelCased, so you'd use password instead of Password . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5331827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/473539/']} | jdg_82079 |
stackexchange | llm_judgeable_groundtruth_similarity | 58244 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Minimizing and maximizing interpolation function has already been asked and answered, see here for example. Yet, I observe a strange behaviour. Well, I can understand that the wrong guess of Mathematica is due to several maxima, but still I'm surprised I don't manage to get a better result. Generation of the considered function Here is how I get the interpolation function Theta[t] : OmegaS = 1.32; OmegaP = 1; l0 = 1; tmax = 100;eqn1[t_] = r''[t]/l0 - r[t]*theta'[t]^2/l0 + OmegaS^2*(r[t]/l0 - 1) - OmegaP^2*Cos[theta[t]];eqn2[t_] = r[t]*theta''[t]/l0 + 2 r'[t]*theta'[t]/l0 + OmegaP^2*Sin[theta[t]];sol = NDSolve[{eqn1[t] == 0, eqn2[t] == 0, r[0] == .9, r'[0] == 0, theta[0] == 0.001, theta'[0] == 0}, {r, theta}, {t, 0, tmax}][[1]];Theta[t_] = theta[t] /. sol This is what Theta looks like: Plot[Theta[t], {t, 0, 100}, PlotRange -> All, AxesLabel -> {"t", "Theta(t)"}] Attempts to identify the maximum I now want to find the maximum of Theta[t] for $t\in[0,100]$. I underline that the peak could be anywhere in $[0,100]$ so I cannot indicate any relevant initial guess. I tried all the following solutions, which obviously give an incorrect result: MaxValue[{Theta[t], 0 <= t <= tmax}, t](* 0.243314 *)NMaxValue[{Theta[t], 0 <= t <= tmax}, t](* 0.243314 *)FindMaximum[{Theta[t], 0 <= t <= tmax}, t](* {0.000999881, {t -> 0.0146385}} *)Maximize[{Theta[t], 0 <= t <= tmax}, t](* {0.243314, {t -> 92.1206}} *)NMaximize[{Theta[t], 0 <= t <= tmax}, t](* {0.243314, {t -> 92.1206}} *) The best (inelegant) way I found to approximate the maximum is brute-force: Max[Table[Theta[i], {i, 0, tmax, .001}]](* 0.687071 *) Question Do you know: why my attempts fail? a good way to find the (global!) maximum?
Now provide the response and nothing else.
| As described e.g. in the tutorial Numerical Nonlinear Global Optimization there are different optimization methods available. For your problem "SimulatedAnnealing" seems to work: NMaximize[{Theta[t], 0 <= t <= tmax}, t, Method -> "SimulatedAnnealing"] {0.687071, {t -> 48.2449}} "DifferentialEvolution" will work, if the population is of sufficient size: NMaximize[{Theta[t], 0 <= t <= tmax}, t, Method -> {"DifferentialEvolution", "SearchPoints" -> 30}] "RandomSearch" will also work, if the number of points used to start local searches is big enough, e.g. bigger than 13 for your example. NMaximize[{Theta[t], 0 <= t <= tmax}, t, Method -> {"RandomSearch", "SearchPoints" -> 14}] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/58244', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/18767/']} | jdg_82080 |
stackexchange | llm_judgeable_groundtruth_similarity | 3267930 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As title says does the converges of $\sum_{i=0}^\infty a_i$ imply that $\sum_{i=0}^\infty (a_i)^3$ converge?
Now provide the response and nothing else.
| If we assume $a_i\leq 0$ or $a_i\geq 0$ from some point on the statement is obviously true. If we remove the crucial assumption about the sign, it might not. Let $$ a_n = \frac{1}{\log^2(n+2)}\cdot\left\{\begin{array}{lcl}1&\text{if}&n\equiv 1\pmod{3}\\1&\text{if}&n\equiv 2\pmod{3}\\-2&\text{if}&n\equiv 0\pmod{3}\end{array}\right.$$ It it simple to check that $\sum_{n\geq 0}a_n$ is convergent, but $\sum_{n\geq 0}a_n^3$ is not, essentially by Kronecker's lemma (summation by parts). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3267930', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/683441/']} | jdg_82081 |
stackexchange | llm_judgeable_groundtruth_similarity | 15579898 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've below code in one of my php files to fetch data from DB: $products = $this->db->get_rows('SELECT * from products WHERE shop_id='.$_SESSION['shop_id'].'AND tags,title,text LIKE \'%'.$_POST['search'].'%\''); Is it problematic? I mean LIKE operator can be injected? Edited please provide examples of injecting in this way
Now provide the response and nothing else.
| Any operator can be injected without binding. $_POST['search'] = "1%'; DROP TABLE myTable LIKE '%"; Would make .... AND tags,title,text LIKE '%1%'; DROP TABLE myTable LIKE '%%' Read on how to bind parameters . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15579898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1020526/']} | jdg_82082 |
stackexchange | llm_judgeable_groundtruth_similarity | 3650203 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an xml file <?xml version="1.0" encoding="utf-8"?><xml> <events date="01-10-2009" color="0x99CC00" selected="true"> <event> <title>You can use HTML and CSS</title> <description><![CDATA[This is the description ]]></description> </event> </events></xml> I used xpath and and xquery for parsing the xml. $xml_str = file_get_contents('xmlfile');$xml = simplexml_load_string($xml_str);if(!empty($xml)){ $nodes = $xml->xpath('//xml/events');} i am getting the title properly, but iam not getting description.How i can get data insidethe cdata
Now provide the response and nothing else.
| SimpleXML has a bit of a problem with CDATA, so use: $xml = simplexml_load_file('xmlfile', 'SimpleXMLElement', LIBXML_NOCDATA);if(!empty($xml)){ $nodes = $xml->xpath('//xml/events');}print_r( $nodes ); This will give you: Array( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [date] => 01-10-2009 [color] => 0x99CC00 [selected] => true ) [event] => SimpleXMLElement Object ( [title] => You can use HTML and CSS [description] => This is the description ) )) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3650203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/273266/']} | jdg_82083 |
stackexchange | llm_judgeable_groundtruth_similarity | 3537657 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In C#, what's the most elegant way to create an array of objects, from an enumerator of objects? e.g. in this case I have an enumerator that can return byte's, so I want to convert this to byte[]. EDIT: Code that creates the enumerator: IEnumerator<byte> enumerator = anObject.GetEnumerator();
Now provide the response and nothing else.
| OK, So, assuming that you have an actual enumerator ( IEnumerator<byte> ), you can use a while loop: var list = new List<byte>();while(enumerator.MoveNext()) list.Add(enumerator.Current);var array = list.ToArray(); In reality, I'd prefer to turn the IEnumerator<T> to an IEnumerable<T> : public static class EnumeratorExtensions{ public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator) { while(enumerator.MoveNext()) yield return enumerator.Current; }} Then, you can get the array: var array = enumerator.ToEnumerable().ToArray(); Of course, all this assumes you are using .Net 3.5 or greater. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3537657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173520/']} | jdg_82084 |
stackexchange | llm_judgeable_groundtruth_similarity | 1810629 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the maximum possible number of entries of A that are even? What if A is a matrix of order n? What is the maximum possible number of entries of A that are PRIMES? What if A is a matrix of order n? This question was asked during my class test and I was unable to do this. Please help me in doing this.
Now provide the response and nothing else.
| For the first question, you can show that $I_3$ is an example of such a matrix with $6$ even entries. If there are $7$ or more event entries, then necessarily there is a row with only even entries, calculate your determinant by expanding this line, it is a sum of even terms, thus the determinant is even and can't be $1$. Thus $6$ is the maximum possible number of entries of A that are even and such as $\det(A)=1$. The generalisation for matrices of order $n$, for the first question is $n^2-n$, you can prove this with same reasoning that in the case $3 \times 3$ : $I_n$ has $n^2-n$ even entries and its determinant is $1$. And if your matrix has more that $n^2-n$ even entries then there is necessary a whole row with even entries and you can expand your determinant from this row and thus it will be even and so different of $1$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1810629', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/329752/']} | jdg_82085 |
stackexchange | llm_judgeable_groundtruth_similarity | 2162061 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the Unity IoC container for resolving my objects. However, I've run into an issue. When I have more than one constructor - how does Unity know which one to use? It seems to use the one with parameters when I have one with and one without. Can I explicitly tell it which constructor to use? Specifically I had a case similar to the following Person class with two constructors. In this case I want the IoC container to use the default constructor - without parameters - but it chooses the one with parameters. public class SomeValueObject{ public SomeValueObject(string name) { Name = name; } public string Name { get; set; }}public class Person{ private string _name; public Person() { _name = string.Empty; } public Person(SomeValueObject obj) { _name = obj.Name; }} This obviously fails as it can't create the SomeValueObject - not knowing what to inject to its string parameter. The error it gives is: Resolution of the dependency failed, type = "MyApp.Person", name = "". Exception message is: The current build operation (build key Build Key[MyApp.Person, null]) failed: The parameter obj could not be resolved when attempting to call constructor MyApp.Person(MyApp.SomeValueObject obj). (Strategy type BuildPlanStrategy, index 3) The container registration: Container.RegisterType<Person, Person>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager()); And the resolving: var person = Container.Resolve<Person>();
Now provide the response and nothing else.
| Register it like this instead: container.RegisterType<Person>(new InjectionConstructor()); You can add the LifetimeManager as well using an overload of the RegisterType method. That said, when modeling for DI, your life will be much easier if you have unambiguous contructors (i.e. no overloaded constructors). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2162061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100894/']} | jdg_82086 |
stackexchange | llm_judgeable_groundtruth_similarity | 40937489 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to negate a boolean property as defined in pom.xml. Meaning, given a property ${doSomething} I need to pass <skip> to a plugin where the value of <skip> should be the negation of ${doSomething} . If ${doSomething} is false, then I want to skip. If it is true, then I don't want to skip. Any ideas? Clarification : I am not talking about using the negation of a property for profile activation. I just want to pass the negation of a boolean into a plugin.
Now provide the response and nothing else.
| Apart from profile activation, Maven doesn't have a boolean logic implemented. So if want to negate a property to pass it to a plugin, you'll need to do it yourself. It is a bit clumsy, but you could use the build-helper-maven-plugin:bsh-property goal, which enables to write a BeanShell script and export variables defined in it as Maven properties: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.12</version> <executions> <execution> <id>negate-prop</id> <phase>initialize</phase> <goals> <goal>bsh-property</goal> </goals> <configuration> <source>dontDoSomething = !${doSomething};</source> <properties> <property>dontDoSomething</property> </properties> </configuration> </execution> </executions></plugin> You can't override the property, but you can define a new one containing the result of the negation; in the example above, it is dontDoSomething . This is ran in the initialize phase so that the rest of the plugins can use it as a parameter, with the standard ${dontDoSomething} . This could be enhanced to have a default value for dontDoSomething if doSomething doesn't exist. <source> value = project.getProperties().getProperty("doSomething"); dontDoSomething = value == null ? false : !Boolean.parseBoolean(value);</source> BeanShell is a scripting language that looks very much like Java and you can use existing Java methods. In the above, the property "doSomething" is retrieved from the project's properties ( project is injected by the plugin at evaluation-time with the current Maven project); it it isn't defined, we return false , otherwise, we negate the value. If doSomething is specifically a system property, it could also be possible to (ab)use the profile activation feature and have 2 profiles: one activated by a property being true and setting another to false , and a second profile doing the inverse: <profiles> <profile> <id>pro-1</id> <activation> <property> <name>doSomething</name> <value>!false</value> </property> </activation> <properties> <dontDoSomething>false</dontDoSomething> </properties> </profile> <profile> <id>pro-2</id> <activation> <property> <name>doSomething</name> <value>false</value> </property> </activation> <properties> <dontDoSomething>true</dontDoSomething> </properties> </profile></profiles> This won't work if doSomething is a Maven property set in the <properties> tag for example. It will need to be passed as a system property with mvn -DdoSomething=true|false . The corresponding profile will be activated according to the value of the system property, which will define the dontDoSomething property to its inverse. If the property isn't defined, pro-1 will be active, setting dontDoSomething to the default value of false . All of this is quite ugly though... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40937489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14731/']} | jdg_82087 |
stackexchange | llm_judgeable_groundtruth_similarity | 390816 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Is there an explicit finitely presented group $G$ and an element $g\in G$ such that the statement " $g$ is equal to the identity" is independent of ZFC?
Now provide the response and nothing else.
| The answer is yes. This is just an instance of the general phenomenon that every non-computable decision problem is saturated with logical independence. (See this related MO answer .) Theorem. If $A$ is a computably enumerable undecidable decision problem, such as the word problem for groups, then for any consistent c.e. theory $T$ extending PA, such as ZFC, there must be true instances of $n\notin A$ that are not provable in $T$ . Proof. Suppose that $T$ is a consistent c.e. theory extending PA. It follows that all the true instances of $n\in A$ are provable in PA and hence in $T$ . If conversely $T$ proved all true instances of $n\notin A$ , then we could decide $A$ as follows: on input $n$ we search, during the day, for positive instances of $n\in A$ , since $A$ is c.e., and at night, we search for a proof from $T$ that $n\notin A$ . Since $T$ is consistent and proves all true existentials, it can be trusted for any proof of $n\notin A$ . So if all such true instances of $n\notin A$ were provable in $T$ , then $A$ would be decidable, contrary to assumption. $\Box$ In particular, if ZFC is consistent, then there must be specific concrete instances of the word problem where a word $g$ is nontrivial for a specific presentation, but this is not provable in ZFC. If you want to get actual independence of ZFC, then you can do so by assuming that ZFC is $\Sigma_1$ -sound, which means that it proves only true existential arithmetic statements. If there is an inaccessible cardinal or even only a worldly cardinal, then ZFC is $\Sigma_1$ -sound. But much less is required. Corollary. If $T$ is a consistent c.e. $\Sigma_1$ -sound theory, then for any c.e. computable undecidable decision problem $A$ , there must be concrete instances $n$ for which $n\in A$ is independent of $T$ . Proof. The point is that if we have a true instance of $n\notin A$ that is not provable in $T$ , then also by soundness $T$ will not prove $n\in A$ , and so $n\in A$ will be independent of $T$ . $\Box$ In particular, assuming ZFC is $\Sigma_1$ -sound, which is a mild extra assumption about ZFC, then for any nondecidable decision problem, such as the word problem for groups, there will be concrete instances that are independent of ZFC. But finally, since I expect that you might want not just a proof that there is an explicit instance, but the explicit instance itself, let me describe how one might construct a specific instance. We know that the word problem in groups is undecidable because we can code the halting problem into it. Consider the Turing machine that searches for a proof of a contradiction in ZFC, halting only when found. From this instance of the halting problem, we can construct an group presentation $G$ and a word $g$ which is trivial in $R$ just in case the program halts. In other words, $g=1$ is true in $G$ if and only if $\neg\text{Con}(\text{ZFC})$ , and this would be provable in a weak theory. If consistent, ZFC will not prove $g\neq 1$ , since that would mean proving its own consistency; but if also $\text{Con}(\text{ZFC})$ , then ZFC will not prove $g=1$ in $G$ . And so it will be independent. This example also reduces the soundness requirement to mere consistency. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/390816', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_82088 |
stackexchange | llm_judgeable_groundtruth_similarity | 2282977 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A recurrence is defined such that $$f_n(x)=f_1(f_{(n-1)}(x)); x\ge2$$ $f_1(x)$ is defined as $$f_1(x)= \frac 23 -\frac 3{3x+1}$$ How can I find the values of $x$ for which the following holds true? $$f_{1001}(x)= x-3$$ I was not able to deduce any kind of pattern in the above recurrence. I did try to find a a pattern by finding $f_2$ and $f_3$ but I could not make out any generating function. How should I proceed?
Now provide the response and nothing else.
| Notice that $$f_2(x) = \frac{2}{3}-\frac{3}{3\cdot\left(\frac{2}{3}-\frac{3}{3x+1}\right)+1} = \frac{2}{3}-\frac{3x+1}{3x-2}$$ $$f_3(x) = \frac{2}{3}-\frac{3}{3\cdot\left(\frac{2}{3}-\frac{3x+1}{3x-2}\right)+1} = \frac{2}{3}+\frac{3x-2}{3}$$$$f_4(x) = \frac{2}{3}-\frac{3}{3\cdot\left(\frac{2}{3}+\frac{3x-2}{3}\right)+1} = \frac{2}{3}-\frac{3}{3x+1}$$This implies $f_4(x)=f_1(x)$. So we see that this is a cycle of $3$, meaning $$x-3=f_{1001}(x)=f_{998}(x)=\ ...\ =f_2(x)= \frac{2}{3}-\frac{3x+1}{3x-2}\implies x = \frac{5}{3}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2282977', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/444440/']} | jdg_82089 |
stackexchange | llm_judgeable_groundtruth_similarity | 23679594 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using SQL Server 2008 R2 and I've created a TVP that I want to use as a parameter to a stored proc but I get a message saying that it can't be found or I don't have permission. I can use the TVP in a script or in the body of the stored proc, but when I try to use it as a parameter I get the error. Any thoughts? Edit: For clarification, the error I'm getting is on the creation of the stored proc
Now provide the response and nothing else.
| In order for a caller to use a PROC with a table valued parameter, you'll need to (unintuitively) grant execute permissions on the TVP type to those calling the PROC i.e. GRANT EXECUTE ON TYPE::[schema].[MyTVP] to [SomeRole] Edit I believe I was able to replicate the issue, viz working from a minimal set of permissions granted to a user. The vital step is for the DBO or Schema Owner of your TVP to grant you the following access to it, in order to be able to use it in a PROC (without this access, I was able to declare a loose variable of the TVP type, but not use it in a PROC). GRANT REFERENCES ON TYPE::[schema].[MyTVP] to YOURROLE -- Or User. Grant Reference here (Obviously you'll also need CREATE PROCEDURE permission, plus relevant access to any objects used in the PROC) Consumers of the PROC will need to also have the GRANT EXECUTE permission on the Proc and on the Type as per the initial answer. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23679594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401173/']} | jdg_82090 |
stackexchange | llm_judgeable_groundtruth_similarity | 11586277 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the following HTML, the div .left and .right have different heights. Is it possible to make both divs same height without defining the height. I have tried using display:table but does not work. .wrap{ overflow:hidden; width:250px; display: table; border-collapse: collapse; } .left{ width:100px; float:left; display: table-cell; border-bottom:1px solid green; } .right{ width:150px; float:left; border-bottom:1px solid red; display: table-cell; } <div class="wrap"> <div class="left"> Lorem </div> <div class="right"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </div> </div> jsfiddle: http://jsfiddle.net/fJbTX/1/
Now provide the response and nothing else.
| Remove the float , which takes the elements out of the document's normal flow, and also add in another wrapper element, to act as the table-row : table-cell , behaves like the <td> HTML element Which implies that this requires (though I've not verified my inference) a display: table-row parent, as a td requires a tr parent-element. .wrap{ overflow:hidden; width:250px; display: table; border-collapse: collapse;}.row { display: table-row;}.left{ width: 50%; display: table-cell; background-color: #0f0;}.right{ width: 50%; background-color: #f00; display: table-cell; } JS Fiddle demo . References: CSS display . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11586277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1355300/']} | jdg_82091 |
stackexchange | llm_judgeable_groundtruth_similarity | 61430817 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using this script in my file to shown error "Uncaught SyntaxError: Unexpected token '<'" in console.How I fix it?Error is shown at the PHP tag which is defined in the script. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Car', 'Number'], <?php while($row = mysqli_fetch_array($result)) { echo "['".$row["car"]."', ".$row["number"]."],"; } ?> ]); var options = { title: 'Percentage of branded Car Services', //is3D:true, pieHole: 0.4 }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script>
Now provide the response and nothing else.
| So first of all a bit of background. A mutual exclusion (mutex) lock as you correctly mentioned is meant to prevent race conditions by ensuring only one thread or process ever enters a critical section . But first of all what is a critical section? Consider this code: public function withdrawMoney(User $user, $amount) { if ($user->bankAccount->money >= $amount) { $user->bankAccount->money = $user->bankAccount->money - $amount; $user->bankAccount->save(); return true; } return false;} The problem here is if two processes run this function concurrently, they will both enter the if check at around the same time, and both succeed in withdrawing, however this might lead the user having negative balance or money being double-withdrawn without the balance being updated (depending on how out of phase the processes are). The problem is the operation takes multiple steps and can be interrupted at any given step. In other words the operation is NOT atomic . This is the sort of critical section problem that a mutual exclusion lock solves. You can modify the above to make it safer: public function withdrawMoney(User $user, $amount) { try { if (acquireLockForUser($user)) { if ($user->bankAccount->money >= $amount) { $user->bankAccount->money = $user->bankAccount->money - $amount; $user->bankAccount->save(); return true; } return false; } } finally { releaseLockForUser($user); }} The interesting things to point out are: Atomic (or thread-safe) operations don't require such protection The code we put between the lock acquire and release, can be considered to have been "converted" to an atomic operation. Acquiring the lock itself needs to be a thread-safe or atomic operation. At the operating system level, mutex locks are typically implemented using atomic processor instructions built for this specific purpose such as an atomic test-and-set operation. This would check if a value if set, and if it is not set, set it. This works as a mutex if you just say the lock itself is the existence of the value. If it exists, the lock is taken and if it's not then you acquire the lock by setting the value. Laravel implements the locks in a similar manner. It takes advantage of the atomic nature of the "set if not already set" operations that certain cache drivers provide which is why locks only work when those specific cache drivers are there. However here's the thing that's most important: In the test-and-set lock, the lock itself is the cache key being tested for existence. If the key is set, then the lock is taken and cannot generally be re-acquired. Typically locks are implemented with a "bypass" in which if the same process tries to acquire the same lock multiple times it succeeds. This is called a reentrant mutex and allows to use the same lock object throughout your critical section without worrying about locking yourself out. This is useful when the critical section becomes complicated and spans multiple functions. Now here's where you have two flaws with your logic: Using the same key for both the lock and the value is what is breaking your lock. In the lock analogy you're trying to store your valuables in a safe which itself is part of your valuables. That's impossible. You have if (Cache::store('memcached')->has('post_' . $post_id)) { outside your critical section but it should itself be part of the critical section. To fix this issue you need to use a different key for the lock than you use for the cached entries and move your has check in the critical section: $lock = Cache::lock('post_' . $post_id. '_lock', 10);try { if ($lock->get()) { //Critical section starts Log::info('checkpoint 1'); // if it comes here if (Cache::store('memcached')->has('post_' . $post_id)) { Log::info('checkpoint 2'); // it should also come here. $post_data = Cache::store('memcached')->get('post_' . $post_id); ... // updating $post_data.. Cache::put('post_' . $post_id, $post_data, 5 * 60); } else { Cache::store('memcached')->put('post_' . $post_id, $initial, 5 * 60); } } // Critical section ends} finally { $lock->release();} The reason for having the $lock->release() in the finally part is because in case there's an exception you still want the lock being released rather than staying "stuck". Another thing to note is that due to the nature of PHP you also need to set a duration that the lock will be held before it is automatically released. This is because under certain circumstances (when PHP runs out of memory for example) the process terminates abruptly and therefore is unable to run any cleanup code. The duration of the lock ensures the lock is released even in those situations and the duration should be set as the absolute maximum time the lock would reasonably be held. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61430817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13276095/']} | jdg_82092 |
stackexchange | llm_judgeable_groundtruth_similarity | 282696 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between a ping and a get request? The goal is to see if the site is up.
Now provide the response and nothing else.
| Ping only checks if the remote host is answering ICMP packets, which (usually) means it's up and running; but this doesn't give you any information about which services the host is actually offering. An HTTP GET request checks that there is a web server running on the host, that it answers to a given IP/port/hostname combo, that you asked it for a valid URL and that the web site is able to answer your request. Example: if IIS (or Apache) is stopped on the host, it will very well answer a Ping request, but a HTTP GET will fail. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/282696', 'https://serverfault.com', 'https://serverfault.com/users/67127/']} | jdg_82093 |
stackexchange | llm_judgeable_groundtruth_similarity | 28832166 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list as follows ['item1', 'item2', 'item3', 'item4'] I want to construct a dictionary from the above list as follows { "item1": { "item2": { "item3": "item4" } }} The number of items in the list is dynamic. The dictionary will be a nested dictionary till it reaches the last element of the list.Is there any way in python to do this?
Now provide the response and nothing else.
| Simple one-liner: a = ['item1', 'item2', 'item3','item4']print reduce(lambda x, y: {y: x}, reversed(a)) For better understanding the above code can be expanded to: def nest_me(x, y): """ Take two arguments and return a one element dict with first argument as a value and second as a key """ return {y: x}a = ['item1', 'item2', 'item3','item4']rev_a = reversed(a) # ['item4', 'item3', 'item2','item1']print reduce( nest_me, # Function applied until the list is reduced to one element list rev_a # Iterable to be reduced)# {'item1': {'item2': {'item3': 'item4'}}} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28832166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2239262/']} | jdg_82094 |
stackexchange | llm_judgeable_groundtruth_similarity | 9361 |
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm paying over $300/month for Kubernetes to have CI/CD in GitLab. And it only covers web apps, Android apps and deployment to Google Cloud. Plus some staging environments, that do not require many resources and that I'm using rarely. It doesn't cover CD to Apple App Store though. I'm curious if there is a way to optimize this? Maybe I should buy some hardware or optimize Google Cloud somehow?
Now provide the response and nothing else.
| I might have skipped the optional installation of docker in my Ubuntu instance, so if the gitlab runner is going to use Docker, remember to install it: curl -sSL https://get.docker.com/ | sh I got back to this issue and seem to have partially fixed it by checking it the gitlab runner is running gitlab-runner statussystemctl is-enabled gitlab-runnersystemctl is-enabled docker I do have a different issue to solve, but it doesn't seem to be related. That is: error during connect: Post http://docker:2375/v1.40/images/ [...] dial tcp: lookup docker on xx.xxx.xx.x:xx: no such host Then I found the solution, there's a problem in Gitlab CI that is reported here ( https://gitlab.com/gitlab-org/gitlab-runner/issues/4566#note_199261985 ); And there are a lot of ways to fix this but my solution follows: 1) Set the .gitlab-ci.yml services to use an older dind version: services: - docker:18.09.7-dind 2) Check the toml file /etc/gitlab-runner/config.toml , set the DOCKER_HOST just in case, to point to the right place, make sure it runs in privileged mode. My working version is: concurrent = 1check_interval = 0[session_server] session_timeout = 1800[[runners]] name = "xxxxxx xxxxxxxx" url = "https://gitlab.com/" token = "xxxxxxxxxx" executor = "docker" pre_build_script = "export DOCKER_HOST=tcp://docker:2375" [runners.custom_build_dir] [runners.docker] tls_cert_path = "" tls_verify = false image = "alpine:latest" privileged = true disable_entrypoint_overwrite = false oom_kill_disable = false disable_cache = false volumes = ["/cache"] shm_size = 0 [runners.cache] [runners.cache.s3] [runners.cache.gcs] Hope this helps someone else in the future! | {} | {'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/9361', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/17468/']} | jdg_82095 |
stackexchange | llm_judgeable_groundtruth_similarity | 38384124 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My goal is to show a user list of history logins ( such as username ) if there are any. In order to do that, I am doing 1. Create an custom object named User like below class User: NSObject { var login: String init(login: String) { self.login = login } required init(coder aDecoder: NSCoder) { login = aDecoder.decodeObjectForKey("login") as! String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(login, forKey: "login") } } // This conform to make sure that I compare the `login` of 2 Users func ==(lhs: User, rhs: User) -> Bool { return lhs.login == rhs.login } At UserManager, Im doing save and retrieve an User . Before saving, I'm doing a check if the the list of history logins contains a User , I wont add it in, otherwise. class UserManager : NSObject{ static let sharedInstance = UserManager() var userDefaults = NSUserDefaults.standardUserDefaults() func saveUser(user:User) { var users = retrieveAllUsers() // Check before adding if !(users.contains(user)) { users.append(user) } let encodedData = NSKeyedArchiver.archivedDataWithRootObject(users) userDefaults.setObject(encodedData, forKey: "users") userDefaults.synchronize() } func retrieveAllUsers() -> [User] { guard let data = userDefaults.objectForKey("users") as? NSData else { return [User]() } let users = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [User] // Testing purpose for user in users { print(user.login) } return users }} At first time trying, I do UserManager.sharedInstance.saveUser(User(login: "1234")) Now it saves the first login. At second time, I also do UserManager.sharedInstance.saveUser(User(login: "1234")) UserManager still adds the second login into nsuserdefault . That means the function contains fails and it leads to func ==(lhs: User, rhs: User) -> Bool{ return lhs.login == rhs.login} does not work properly. Does anyone know why or have any ideas about this.
Now provide the response and nothing else.
| The problem is that User derives from NSObject. This means that (as you rightly say) your == implementation is never being consulted. Swift's behavior is different for objects that derive from NSObject; it does things the Objective-C way. To implement equatability on an object that derives from NSObject, override isEqual: . That is what makes an NSObject-derived object equatable in a custom way, in both Objective-C and Swift. Just paste this code right into your User class declaration, and contains will start working as you wish: override func isEqual(object: AnyObject?) -> Bool { if let other = object as? User { if other.login == self.login { return true } } return false} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38384124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/792562/']} | jdg_82096 |
stackexchange | llm_judgeable_groundtruth_similarity | 6588015 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to design class A implements interface C and reduce the visibility of a method (declared in C)to make it secure from outer world, make one of the methods in interface implemented in class A as private (reducing visibility in class A). I have to do this for security reason, how can I do this, is there a workaround. We do know that by default, the interface has public members. But there is no option for me, can someone help me. Thanks in advance. --So , there is no way, to have a class implement method from interface and make it private. And all classes that implement any interface's method will always have public methods?
Now provide the response and nothing else.
| No, you can't reduce the visibility of a method in an interface. What would you expect to happen if someone wrote: C foo = new A();foo.methodDeclaredPrivateInA(); ? As far as the compiler is concerned, everything with a reference to an implementation of C has the right to call any methods within it - that's what Liskov's Substitution Principle is all about. If you don't want to implement the whole of a public interface, don't implement it - or throw exceptions if you absolutely must. It's also worth noting that the accessibility provided in source code is rarely a good security measure. If your class is running in a VM which in turn gets to determine its own permissions, anyone can make members visible via reflection. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6588015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357349/']} | jdg_82097 |
stackexchange | llm_judgeable_groundtruth_similarity | 68495 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
We just purchased a building that is right next to our current building with a small gravel "road" in between (that we own). I'm looking to run some wire in a conduit underground to the other building. What type and size of conduit should I get, how deep should it be, and what other advice or tips can you give me? Thanks
Now provide the response and nothing else.
| When I got a permit to run 220V underground, I was required to go at least 18" deep. I would follow that recommendation for your situation as well. In addition to the pull wire, I would pull several extra network (copper and fiber) and coax wires. It's a lot easier to pull all the wires in one bundle than to pull them one at a time. Make sure the wires are all water proof. After filling the trench about 80%, put a plastic tape in the trench. The tape is bright colored and contains writing along the lines of 'buried cable'. Then finish backfilling. Document the location of the trench and of course the contents of the conduit. Call the locator service to make sure you don't cut other wires/pipes when digging. It against wiring code to pull "high voltage" wires (110V or 220V) along with "low voltage" wires. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/68495', 'https://serverfault.com', 'https://serverfault.com/users/1869/']} | jdg_82098 |
stackexchange | llm_judgeable_groundtruth_similarity | 5477096 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible in Scala to write something like: trait Road { ...}class BridgeCauseway extends Road { // implements method in Road}class Bridge extends Road { val roadway = new BridgeCauseway() // delegate all Bridge methods to the `roadway` member} or do I need to implement each of Road 's methods, one by one, and call the corresponding method on roadway ?
Now provide the response and nothing else.
| The easiest way to accomplish this is with an implicit conversion instead of a class extension: class Bridge { ... }implicit def bridge2road(b: Bridge) = b.roadway as long as you don't need the original Bridge to be carried along for the ride (e.g. you're going to store Bridge in a collection of Road ). If you do need to get the Bridge back again, you can add an owner method in Road which returns an Any , set it using a constructor parameter for BridgeCauseway , and then pattern-match to get your bridge: trait Road { def owner: Any ...}class BridgeCauseway(val owner: Bridge) extends Road { . . . }class Bridge extends Road { val roadway = new BridgeCauseway(this) ...}myBridgeCauseway.owner match { case b: Bridge => // Do bridge-specific stuff ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5477096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126855/']} | jdg_82099 |
stackexchange | llm_judgeable_groundtruth_similarity | 36443628 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi all I am trying to post JSON to an API which I can do with AJAX and cURL. The code in C# .net app can handle the cURL code and write it to SQL: curl "http://localhost:38194/API/inbound" --data "FirstName=test4&LastName=test&[email protected]" However when I try to POST from C# with: using (var client = new HttpClient()){ var request = new { FirstName = reader[1], LastName = reader[2], Email = reader[3] }; var response = client.PostAsync("http://localhost:38194/API/inbound", new StringContent(JsonConvert.SerializeObject(request).ToString(), Encoding.UTF8, "application/json")).Result; if (response.IsSuccessStatusCode) { //Do something }} It sends the data as request = { FirstName = "Tom", LastName = "Buckle", Email = "[email protected]" } which I presume my Controller can't handle using: public string Post([FromBody] FormDataCollection formValues) I have searched and spent hours on this and suspect that the format that I sending the POST doesn't work with my API Controller FormDataCollection . I must admit I don't have a great understanding of this stuff and learn more by trial and error. Likely not elegant but this is my API Controller code that works with cURL. public string Post([FromBody] FormDataCollection formValues){ string first_name = null, last_name = null, email = null; string connStr = ConfigurationManager.ConnectionStrings["inboundapplicant"].ConnectionString; using (SqlConnection connection = new SqlConnection(connStr)) { using (SqlCommand command = new SqlCommand()) { if (!string.IsNullOrWhiteSpace(formValues.Get("FirstName"))) { first_name = formValues.Get("FirstName"); } if (!string.IsNullOrWhiteSpace(formValues.Get("LastName"))) { last_name = formValues.Get("LastName"); } if (!string.IsNullOrWhiteSpace(formValues.Get("Email"))) { email = formValues.Get("Email"); } command.Connection = connection; command.CommandType = CommandType.Text; command.CommandText = "INSERT into [dbo].[Leads] (FirstName, LastName, Email) VALUES (@first_name, @last_name, @email)"; command.Parameters.AddWithValue("@first_name", first_name == null ? (object)DBNull.Value : first_name); command.Parameters.AddWithValue("@last_name", last_name == null ? (object)DBNull.Value : last_name); command.Parameters.AddWithValue("@email", email == null ? (object)DBNull.Value : email); try { connection.Open(); int recordsAffected = command.ExecuteNonQuery(); } catch (SqlException) { throw; } finally { connection.Close(); } } } return "success";}
Now provide the response and nothing else.
| You can just use a *\d* * pattern with a restrictive (?=.{6}$) lookahead: ^(?=.{6}$) *\d* *$ See the regex demo Explanation: ^ - start of string (?=.{6}$) - the string should only have 6 any characters other than a newline * - 0+ regular spaces ( NOTE to match horizontal space - use [^\S\r\n] ) \d* - 0+ digits * - 0+ regular spaces $ - end of string. Java demo (last 4 are the test cases that should fail): List<String> strs = Arrays.asList("123456", "12345 ", " 23456", " 5", // good"1 ", " ", " 2 ", " 2345 ", // good"12 456", "1234 6", " 1 6", "1 6"); // badfor (String str : strs) System.out.println(str.matches("(?=.{6}$) *\\d* *")); Note that when used in String#matches() , you do not need the intial ^ and final $ anchors as the method requires a full string match by anchoring the pattern by default. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36443628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6164909/']} | jdg_82100 |
stackexchange | llm_judgeable_groundtruth_similarity | 5100724 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my xml input. <package version="2.0" unique-identifier="uuid_id" xmlns="http://www.idpf.org/2007/opf"> <metadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:opf="http://www.idpf.org/2007/opf" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:calibre="http://calibre.kovidgoyal.net/2009/metadata" xmlns:dc="http://purl.org/dc/elements/1.1/"> <meta name="calibre:series_index" content="1"/> <dc:language>UND</dc:language> <dc:creator opf:file-as="Marquez, Gabriel Garcia" opf:role="aut" >Gabriel Garcia Marquez</dc:creator> <meta name="calibre:timestamp" content="2010-07-14T21:35:15.266000+00:00"/> <dc:title>Cem Anos de SolidΓ£o</dc:title> <meta name="cover" content="cover"/> <dc:date>2010-07-14T21:35:15.266000+00:00</dc:date> <dc:contributor opf:role="bkp" >calibre (0.7.4) [http://calibre-ebook.com]</dc:contributor> <dc:identifier id="uuid_id" opf:scheme="uuid" >7e11dc8b-55cb-4411-8f30-df974fbcf58a</dc:identifier> </metadata> <manifest></package> and my xslt starts like.. <?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xhtml="http://www.w3.org/1999/xhtml"><xsl:template match="package"> <xsl:message>Entering package</xsl:message></xsl:template> I am using XSLT 1.0 and the template package is not getting matched. When I remove the namespace xmlns="http://www.idpf.org/2007/opf" in package node, the template gets matched. How I can make my template to match without removing the namespaces. Please help me. Thanks in advance.
Now provide the response and nothing else.
| Add the namespaces in your stylesheet. <?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:opf="http://www.idpf.org/2007/opf"><xsl:template match="opf:package"> <xsl:message>Entering package</xsl:message></xsl:template> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5100724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514227/']} | jdg_82101 |
stackexchange | llm_judgeable_groundtruth_similarity | 2506395 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am confused by expressions like $\mathbb{R}/\mathbb{Z}$, especially if I see something of the sort $SL(2,\mathbb{R})/SO(2,\mathbb{R})$. I don't know what to make of it. I understand what a quotient of a group for an equivalence looks like, but I can't get my head around expressions like above. Is a quotient like this always a group and what do elements in the set $SL(2,\mathbb{R})/SO(2,\mathbb{R})$ look like?
Now provide the response and nothing else.
| They are a lot of questions in one post. I will do my best to answer them. First, let me recall the notion of group action: Definition $1$ . Let $X$ be a set and let $G$ be a group, a left action of $G$ on $X$ is a map $\cdot\colon G\times X\rightarrow X$ which satisfies the two following axioms: $\forall x\in X,e\cdot x=x.$ $\forall(g,g')\in G\times G,\forall x\in X,g\cdot(g'\cdot x)=gg'\cdot x.$ This definition is equivalent to the following: Definition $2$ . Let $X$ be a set and let $G$ be a group, a left action is group morphism from $G$ to $\mathfrak{S}(X)$ . If $\cdot\colon G\times X\rightarrow X$ is a group action in the sense of definition $1$ , then $g\mapsto \{x\mapsto g\cdot x\}$ is a group action in the sense of definition $2$ . Conversely, if $\varphi\colon G\rightarrow\mathfrak{S}(X)$ is a group homorphism, then $g\cdot x=\varphi(g)(x)$ is a group action in the sense of definition $1$ . Example 1. If $H$ is a subgroup of $G$ , then $H$ acts on $G$ by left translation i.e. $(h,g)\mapsto hg$ is a group action. Now, let us define the notion of quotient set in this general setup: Definition $3$ . Let $G$ be a group acting on a set $X$ , then $G/X$ is the set of all orbits, namely: $$G/X:=\{G\cdot x;x\in X\}$$ where $G\cdot x:=\{g\cdot x;g\in G\}$ is the orbit of $x$ . The set $G/X$ is a collection of subsets of $X$ . In all generality, this is not a group, for example, $X$ may not be a group itself. Example $2$ . If $H$ is a subgroup of $G$ , then $G/H:=\{gH;g\in G\}$ . Let us investigate the structure of $G/H$ when $G$ is a group and $H$ is a subgroup acting by left translation. Proposition $1$ . Assume that $H$ is normal in $G$ i.e. for all $g\in G$ , $gHg^{-1}=H$ , then $G/H$ is endowed with a unique group structure such that the canonical projection $\pi\colon G\twoheadrightarrow G/H$ is a group morphism. Proof. Let define the operation on $G/H$ to be $gH\cdot g'H=gg'H$ or equivalently : $\pi(g)\pi(g')=\pi(gg')$ . The key point is that this definition does not depend on the choice of $g$ and $g'$ , namely: $$gH=xH,g'H=x'H\Rightarrow gg'H=xx'H.$$ Indeed, there exists $h,h'\in H$ such that $x=gh$ and $x'=g'h'$ , therefore, one has: $$xx'H=ghg'\underbrace{h'}_{\in H}H=ghg'H=gg'\underbrace{g'^{-1}hg'}_{\in H}H=gg'H.$$ Now that the operation on $G/H$ is well-defined, I let you check the remaining properties (associativity, existence of identity element, existence of inverse). Whence the result. $\Box$ Conversely, if $G/H$ is a group such that $\pi$ is a group morphism, then $H$ is normal as the kernel of $\pi$ . What I like to emphasize is that when working when quotient sets it is crucial to specify the group action! Maybe I'll close this answer mentioning a useful result: Theorem. Let $G$ be a group acting on $X$ , then for all $x\in X$ , there is a bijective correspondence: $$G/G_x\cong G\cdot x$$ where $G_x:=\{g\in G\textrm{ s.t. }g\cdot x=x\}$ . Proof. Consider $gG_x\mapsto g\cdot x$ , in particular, check the well-definedness of this map. $\Box$ Remark 1. The set $G_x$ is a subgroup of $G$ , but it may not be normal. Example 3. $\mathbb{S}^n\cong SO(n+1)/SO(n)$ as sets, but even as smooth manifolds with a much-refined theorem. Here, the action of $SO(n+1)$ on $\mathbb{S}^n$ is given by $(M,x)\mapsto Mx$ which is transitive, which means that each orbit under $SO(n+1)$ is the whole $\mathbb{S}^n$ . If $x=(1,0,\ldots,0)$ , then the stabilizer is given by: $$SO(n+1)_x=\left\{\begin{pmatrix}1 & 0\\0& A\end{pmatrix};A\in SO(n)\right\}\underset{\textrm{abusive}}{=}SO(n).$$ Indeed, the first column must be $x$ and by orthogonality the first entry of each other column must be $0$ . Whence the result by the theorem. Coming back to your main question (and guessing what the action you are working with is): Let $\mathbb{H}$ be the upper-half plane of $\mathbb{C}$ , namely the set of points in $\mathbb{C}$ having a strictly positive imaginary part. Let $SL(2,\mathbb{R})$ acts on $\mathbb{H}$ by homography: $$\begin{pmatrix}a&b\\c&d\end{pmatrix}\cdot z=\frac{az+b}{cz+d}.$$ Then this action is transitive and the stabilizer of $i$ is given by: $$SL(2,\mathbb{R})_i=\left\{\begin{pmatrix}a & b\\-b&a\end{pmatrix};a,b\in\mathbb{R}\right\}=SO(2).$$ Whence using the theorem, $SL(2,\mathbb{R})/SO(2)\cong\mathbb{H}$ as sets and again even as smooth manifolds. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2506395', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/371674/']} | jdg_82102 |
stackexchange | llm_judgeable_groundtruth_similarity | 11726225 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a struct: public struct User { public string name; public string email; public string age;} Then create one: User user = new User(); user.name = "Freewind"; user.email = "[email protected]"; user.age = 100; Then display it: MessageBox.Show(user.ToString()); I hope it can print all of the fields of the user struct, but it's not. It just shows: MyApp.User Is there a easy way to display all the fields of a struct?
Now provide the response and nothing else.
| Override the ToString method on your struct: public override string ToString(){ return String.Format("name={0}, email={1}, age={2}", this.name, this.email, this.age);} Note that this is not automatic and you will have to manually add any fields/properties to the string. With reflection you can do something like this: public override string ToString(){ Type type = this.GetType(); FieldInfo[] fields = type.GetFields(); PropertyInfo[] properties = type.GetProperties(); User user = this; Dictionary<string, object> values = new Dictionary<string, object>(); Array.ForEach(fields, (field) => values.Add(field.Name, field.GetValue(user))); Array.ForEach(properties, (property) => { if (property.CanRead) values.Add(property.Name, property.GetValue(user, null)); }); return String.Join(", ", values);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11726225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']} | jdg_82103 |
stackexchange | llm_judgeable_groundtruth_similarity | 171332 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code. For example, this paper ends with: Results The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture. Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?
Now provide the response and nothing else.
| Several reasons come to mind. Code is too big for article. For a short period of time, interesting projects were short enough to be published with the paper that described them. This can still happen, but many projects of sufficiently large size to be interesting have grown too big to be published with the papers that describe them. Public hosts not free or durable. Until recently, cheap, durable, easy to access public hosts were not available. Publishing a paper is easier than publishing a project. Some people have time to publish a paper or a project, but not both. Incentives tied to role. Many years ago I asked a colleague about product development and patents and got the word that most people there pretty much did one or the other. As with paper writers (think academia) and open source developers, rewards are geared toward one work product or the other. Self motivation. The desire to describe ideas or to implement code is not always present in equal parts in the same person. Many of my professors openly admitted that they either never coded very much, or were many years away from having coded fluently. Similarly, many developers barely want to write comments in their code or when they commit to source control. Durability of project hosting and work product is also an issue. Who wants to link somewhere that might be gone a few years from now and as a result, diminish the value of the paper. Tradition. Publishers are oriented toward reviewing and publishing papers, but might not be ready to take on the same evaluation for projects. Also the traditional views on what is a sensible level of reproducibility varies among fields. A chemist publishing a paper about a new synthesis method is expected to write down enough detail for another chemist to perform the synthesis. She'd not be expected to ship the educts and product to the journal. Readers who want to use/reproduce the paper are expected to buy their own educts and do the synthesis themselves in their lab (though they may ask to come and visit the lab to see how it is done in practice). Neither would a biologist be expected to attach his new transgenic mice to the paper. This view on reproducibility corresponds to e.g. giving a (pseudo-code) description of the algorithm as opposed to shipping the actual implementation. Naked code can be shocking . It takes a lot less polishing to proof-read a paper length document than to code inspect, code review, and quality assure a project. I have a lot of code I would be more comfortable telling you about than showing you. Hopefully things are moving forward to a point where we will all write beautiful code, but if your code was rushed, barely or doesn't completely work, you might be more comfortable not sharing the executables or the source. Closed source. Not everyone has embraced open source. Many papers are written about work for DoD, commercial projects, or privately funded projects where there are benefits from exposure of the project to the public, but there are still trade secrets or first to market advantages that could be eroded by open sourcing the code or other work products. Publish further work based on this code. If the code is not published it may give the author an advantage in publishing followup work. Other competing researchers may need to reimplement the work which may take precious time. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/171332', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/59263/']} | jdg_82104 |
stackexchange | llm_judgeable_groundtruth_similarity | 5646285 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For the life of me, I cannot figure out what is going on in the example piece of C# code below. The collection (List) property of the test class is set as read only, but yet I can seemingly assign to it in the object initializer. ** EDIT: Fixed the problem with the List 'getter' using System;using System.Collections.Generic;using NUnit.Framework;namespace WF4.UnitTest{ public class MyClass { private List<string> _strCol = new List<string> {"test1"}; public List<string> StringCollection { get { return _strCol; } } } [TestFixture] public class UnitTests { [Test] public void MyTest() { MyClass c = new MyClass { // huh? this property is read only! StringCollection = { "test2", "test3" } }; // none of these things compile (as I wouldn't expect them to) //c.StringCollection = { "test1", "test2" }; //c.StringCollection = new Collection<string>(); // 'test1', 'test2', 'test3' is output foreach (string s in c.StringCollection) Console.WriteLine(s); } }}
Now provide the response and nothing else.
| This: MyClass c = new MyClass{ StringCollection = { "test2", "test3" }}; is translated into this: MyClass tmp = new MyClass();tmp.StringCollection.Add("test2");tmp.StringCollection.Add("test3");MyClass c = tmp; It's never trying to call a setter - it's just calling Add on the results of calling the getter . Note that it's also not clearing the original collection either. This is described in more detail in section 7.6.10.3 of the C# 4 spec. EDIT: Just as a point of interest, I was slightly surprised that it calls the getter twice. I expected it to call the getter once, and then call Add twice... the spec includes an example which demonstrates that. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5646285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585287/']} | jdg_82105 |
stackexchange | llm_judgeable_groundtruth_similarity | 41093774 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just discovered the most baffling error and I don't understand why the compiler did not flag it for me. If I write the following: string s = "abcdefghijkl";cout << s << endl;s.substr(2,3) = "foo";s.substr(8,1) = '.';s.substr(9,1) = 4;cout << s << endl; The compiler has no problem whatsoever with this, and the assignment statements appear to have no effect, based on what's printed out. In contrast, s.front() = 'x'; has the effect I'd expect (since front returns a reference to a character) of changing the underlying string, and s.length() = 4; also has the expected effect of generating a compiler error complaining that you can't assign to something that isn't an lvalue, because length returns an integer. (Well, a size_t anyway.) So... why on earth does the compiler not complain about assigning to the result of a substr call? It returns a string value, not a reference, so it shouldn't be assignable, right? But I've tried this in g++ (6.2.1) and clang++ (3.9.0), so it doesn't seem to be a bug, and it also doesn't seem to be sensitive to C++ version (tried 03, 11, 14).
Now provide the response and nothing else.
| The result of substr() is a std::string temporary object -- it's a self-contained copy of the substring, not a view on the original string. Being a std::string object, it has an assignment operator function, and your code invokes that function to modify the temporary object. This is a bit surprising -- modifying a temporary object and discarding the result usually indicates a logic error, so in general there are two ways that people try to improve the situation: Return a const object. Use lvalue ref-qualifier on assignment operator. Option 1 would cause a compilation error for your code, but it also restricts some valid use-cases (e.g. move -ing out of the return value -- you can't move out of a const string). Option 2 prevents the assignment operator being used unless the left-hand side is an lvalue. This is a good idea IMHO although not all agree; see this thread for discussion . In any case; when ref-qualifiers were added in C++11 it was proposed to go back and change the specification of all the containers from C++03, but this proposal was not accepted (presumably, in case it broke existing code). std::string was designed in the 1990s and made some design choices that seem poor today in hindsight, but we're stuck with it. You'll have to just understand the problem for std::string itself, and perhaps avoid it in your own classes by using ref-qualifiers, or views or whatever. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41093774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2566613/']} | jdg_82106 |
stackexchange | llm_judgeable_groundtruth_similarity | 7237415 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
on my computer ~$ python -V Python 3.2.1 but I get into problems when I run some python programs. my guess is (or at least I want to try this) that there is some backward compatibility issues, and I want to run those python scripts with python2 2.7.2-2 which is also installed on my system but I do not know how to make it as the (temporary) default python. The python script starts with #!/usr/bin/env python and I am using arch linux.
Now provide the response and nothing else.
| You can use virtualenv # Use this to create your temporary python "install"# (Assuming that is the correct path to the python interpreter you want to use.)virtualenv -p /usr/bin/python2.7 --distribute temp-python# Type this command when you want to use your temporary python.# While you are using your temporary python you will also have access to a temporary pip,# which will keep all packages installed with it separate from your main python install.# A shorter version of this command would be ". temp-python/bin/activate"source temp-python/bin/activate# When you no longer wish to use you temporary python typedeactivate Enjoy! | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7237415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625914/']} | jdg_82107 |
stackexchange | llm_judgeable_groundtruth_similarity | 112055 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking at a batch file which defines the following variables: set _SCRIPT_DRIVE=%~d0set _SCRIPT_PATH=%~p0 What do %~d0 or %~p0 actually mean? Is there a set of well-known values for things like current directory, drive, parameters to a script? Are there any other similar shortcuts I could use?
Now provide the response and nothing else.
| The magic variables % n contains the arguments used to invoke the file: %0 is the path to the bat-file itself, %1 is the first argument after, %2 is the second and so on. Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d is drive, ~p is the path (without drive), ~n is the file name. They can be combined so ~dp is drive+path. %~dp0 is therefore pretty useful in a bat: it is the folder in which the executing bat file resides. You can also get other kinds of meta info about the file: ~t is the timestamp, ~z is the size. Look here for a reference for all command line commands. The tilde-magic codes are described under for . | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/112055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/322/']} | jdg_82108 |
stackexchange | llm_judgeable_groundtruth_similarity | 3569742 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a lot of people NSManagedObjects that I need filtering and was hoping to do it within the initial fetch instead of filtering the array afterwards. I've used selectors in predicates before, but never when fetching NSManagedObjects, for example I have all my employees and then i use this predicate on the NSArray... [NSPredicate predicateWithFormat:@"SELF isKindOfClass:%@", [Boss class]] ...but now I want to do a bit more math based on different attributes of my objects. I thought I could do something like... [NSPredicate predicateWithFormat:@"SELF bonusIsAffordable:%f", howMuchMoneyTheCompanyHas]; ..where bonusIsAffordable: is a method of my Employee class and would calculate whether I can afford to pay them a bonus. But I get an error... Unknown/unsupported comparison predicate operator type cocoa Any ideas what I'm screwing up?
Now provide the response and nothing else.
| You can execute arbitrary code in an NSPredicate only when qualifying objects in memory. In the case of a SQLite-backed NSPersistentStore , the NSPredicate is compiled to SQL and executed on the SQLite query engine. Since SQLite has no knowlege of Objective-C, nor are any objects instantiated, there's no way to execute arbitrary code. For in-memory queries (against a collection or an in-memory or atomic Core Data store), have a look at NSExpression , particular +[NSExpression expressionForFunction:selectorName:arguments:] and +[NSExpression expressionForBlock:arguments:] . Given such an expression, you can build an NSPredicate programatically. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3569742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84783/']} | jdg_82109 |
stackexchange | llm_judgeable_groundtruth_similarity | 2800369 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why can I use super only with wildcards and not with type parameters? For example, in the Collection interface, why is the toArray method not written like this interface Collection<T>{ <S super T> S[] toArray(S[] a);}
Now provide the response and nothing else.
| super to bound a named type parameter (e.g. <S super T> ) as opposed to a wildcard (e.g. <? super T> ) is ILLEGAL simply because even if it's allowed, it wouldn't do what you'd hoped it would do, because since Object is the ultimate super of all reference types, and everything is an Object , in effect there is no bound . In your specific example, since any array of reference type is an Object[] (by Java array covariance), it can therefore be used as an argument to <S super T> S[] toArray(S[] a) (if such bound is legal) at compile-time, and it wouldn't prevent ArrayStoreException at run-time. What you're trying to propose is that given: List<Integer> integerList; and given this hypothetical super bound on toArray : <S super T> S[] toArray(S[] a) // hypothetical! currently illegal in Java the compiler should only allow the following to compile: integerList.toArray(new Integer[0]) // works fine!integerList.toArray(new Number[0]) // works fine!integerList.toArray(new Object[0]) // works fine! and no other array type arguments (since Integer only has those 3 types as super ). That is, you're trying to prevent this from compiling: integerList.toArray(new String[0]) // trying to prevent this from compiling because, by your argument, String is not a super of Integer . However , Object is a super of Integer , and a String[] is an Object[] , so the compiler still would let the above compile, even if hypothetically you can do <S super T> ! So the following would still compile (just as the way they are right now), and ArrayStoreException at run-time could not be prevented by any compile-time checking using generic type bounds: integerList.toArray(new String[0]) // compiles fine!// throws ArrayStoreException at run-time Generics and arrays don't mix, and this is one of the many places where it shows. A non-array example Again, let's say that you have this generic method declaration: <T super Integer> void add(T number) // hypothetical! currently illegal in Java And you have these variable declarations: Integer anIntegerNumber aNumberObject anObjectString aString Your intention with <T super Integer> (if it's legal) is that it should allow add(anInteger) , and add(aNumber) , and of course add(anObject) , but NOT add(aString) . Well, String is an Object , so add(aString) would still compile anyway. See also Java Tutorials/Generics Subtyping More fun with wildcards Related questions On generics typing rules: Any simple way to explain why I cannot do List<Animal> animals = new ArrayList<Dog>() ? java generics (not) covariance What is a raw type and why shouldnβt we use it? Explains how raw type List is different from List<Object> which is different from a List<?> On using super and extends : Java Generics: What is PECS? From Effective Java 2nd Edition : "producer extends consumer super " What is the difference between super and extends in Java Generics What is the difference between <E extends Number> and <Number> ? How can I add to List<? extends Number> data structures? (YOU CAN'T!) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2800369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336962/']} | jdg_82110 |
stackexchange | llm_judgeable_groundtruth_similarity | 27754492 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I compile cocos2d-x (version 3.3) using visual studio 2015, an error occured, saying: fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (ηΌθ―ζΊζδ»Ά ..\base\s3tc.cpp) The source code is: #ifdef snprintf #error Macro definition of snprintf conflicts with Standard Library function declaration#endif Anybody can tell me what's wrong?
Now provide the response and nothing else.
| Until now, Many libraries & programs used snprintf() function by defining it as _snprintf() , since _snprintf() was supported. #define snprintf _snprintf Finally, Visual Studio 14 defines snprintf() ! Since, snprintf() is now officially supported. We should never #define it. Doing it will overshadow new snprintf() function defined in stdio.h. To restrict that, this is added in stdio.h #ifdef snprintf #error: Macro definition of snprintf conflicts with Standard Library function declarationβ#endif Hence, your code doesn't compile. It is true that on all previous versions of Visual Studio, you must use _snprintf() function. But VS 2014 onwards you should not #define it with _snprintf() . Somewhere in your code or most likely in cocos headers, this is done and hence the error. Check that and remove that #define. snprintf() is part of C99 specifications. To enable C99 support add this in your program #if _MSC_VER>=1900# define STDC99#endif In case you don't know what _MSC_VER macro values are ...MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008)MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005)MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003)MSVC++ 7.0 _MSC_VER == 1300MSVC++ 6.0 _MSC_VER == 1200MSVC++ 5.0 _MSC_VER == 1100MSVC++ 4.0 _MSC_VER == 1000MSVC++ 2.0 _MSC_VER == 900MSVC++ 1.0 _MSC_VER == 800C/C++ 7.0 _MSC_VER == 700C 6.0 _MSC_VER == 600 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27754492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4414877/']} | jdg_82111 |
stackexchange | llm_judgeable_groundtruth_similarity | 16879451 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just installed the ADO.NET connector from here http://dev.mysql.com/downloads/connector/net/ Yet MySQL doesn't appear as a data source like it should. I tried restarting Visual Studio. It doesn't fix my issue. Did I install the wrong connector? EDIT: STill nothing. I'm using Visual Studio Express For Desktop. Do I need to pay for the Ultimate edition to use a MySQL Data Source?
Now provide the response and nothing else.
| I was having the same problem just now. I solved it by uninstalling the latest Connector/NET drivers (6.7.4) and then installed the older drivers (6.6.5) and it works. I am using Visual Studio 2010. I uninstalled the latest ones because I figured they were somehow related to .NET4.5, which I'm not able to use. Update #1: Supposedly another way is to register the MySql Connector with various Visual Studio versions (2010/2012/2013/2015...) during installation: Go to Modify Product Features and select all the relevant Visual Studio versions. Update #2 - Visual Studio 2019 Update: When I installed MySQL Community with the ConnectorNET and VisualStudio Plugin options included - MySQL didn't show up as a data provider in Visual Studio. The installer I used included the VS Plugin version 1.2.9, which had supposedly fixed installation issues from 1.2.8, but still didn't work for me... The solution for me was to uninstall the Connector and the Visual Studio Plugin, download them as individual components, and then install them separately (not as part of the MySQLServer Installer). Install the Connector first, then VS plugin after. Connector Download VS Plugin Download I found the solution here , Thanks to @LambertHeenan. NOTE about Visual Studio Express The OP asks whether MySQL is supported with Visual Studio Express (which as far as I can tell has been renamed to Visual Studio Community ). In the past MySQL officially didn't support Visual Studio Express, as per @Paul's answer below, but they do officially support Visual Studio Community 2017 and 2019, according to this page . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16879451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1040736/']} | jdg_82112 |
stackexchange | llm_judgeable_groundtruth_similarity | 4454011 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been trying this question $\frac{(1+nx)^n}{n!} > \frac{(nx)^n}{n!}$ Since $\sum_{n=1}^{\infty}\frac{(nx)^n}{n!}$ is divergent when $x \geq \frac{1}{e} \implies \sum_{n=1}^{\infty} \frac{(1+nx)^n}{n!} $ is divergent. I don't know how to prove that $\sum_{n=1}^{\infty} \frac{(1+nx)^n}{n!}$ is convergent for $0<x < \frac{1}{e} $ Help me out.Thanks in advance
Now provide the response and nothing else.
| Here is an intuitive answer which may address your concern about $\sigma$ -algebras and information. Assume that only $3$ mutually exclusive events may happen at time $T$ . Let these be denoted by $\omega_1$ , $\omega_2$ , $\omega_3$ . The probabilities of these events are estimated to be $p_1, p_2, p_3 \in [0, 1]$ such that $p_1+p_2+p_3=1$ . At time $T$ , based on the occurrence of a particular event, John, Jack and Jane will take actions $X$ , $Y$ , $Z$ from a set of possible actions $A=\{0, 1, 2\}$ . Now consider the task of modelling $X$ , $Y$ , $Z$ mathematically, such that you can speak of the probability of a particular action taken. Finding the right model for $X$ , $Y$ , $Z$ will depend on the possible restrictions that John, Jack and Jane face at time $T$ . Assume that at time $T$ , the individual circumstances of John, Jack and Jane are as follows: At time $T$ , John will know exactly which of the mutually exclusive events $\omega_1, \omega_2, \omega_3$ has occurred and will take the action $1$ , $2$ , $3$ , respectively. At time $T$ , Jack will only be able to tell whether $\omega_1$ has occurred or not. So if $\omega_1$ has occurred, he will take action $1$ . If $\omega_1$ has not occurred, Jack will know that either $\omega_2$ or $\omega_3$ has occurred, but he will not know which one exactly, and, in either case, he will take action $2$ . At time $T$ , Jane will only be able to tell whether $\omega_2$ has occurred or not. So if $\omega_2$ has occurred, she will take action $1$ . If $\omega_2$ has not occurred, Jane will know that either $\omega_1$ or $\omega_3$ has occurred, but she will not know which one exactly, and, in either case, she will take action $3$ . Now, let us come up with a suitable mathematical model for the taken actions $X$ , $Y$ , $Z$ . This will be accomplished by designing an individual probability space $(\Omega, \mathcal{F}, \mathbb{P})$ for the random variables $X$ , $Y$ , $Z$ . In all the three cases, $\Omega$ will be given by $\{\omega_1, \omega_2, \omega_2\}$ . However, the $\sigma$ -algebra $\mathcal{F}$ should model the information accessible at time $T$ to the person under question. By saying information, we mean the events that are observable at time $T$ to the person under question. John . According to the description, action $X$ taken by John is defined as follows: $X(\omega_1)=1$ , $X(\omega_2)=2$ , $X(\omega_3)=3$ . Since John has complete information at time $T$ , i.e., he is able to distinguish which of the mutually exclusive events $\omega_1$ , $\omega_2$ and $\omega_3$ has occurred, the corresponding sigma-algebra $\mathcal{F}$ should reflect this fact. Therefore $\mathcal{F}$ should contain all the individual events $\{\omega_1\}$ , $\{\omega_2\}$ , $\{\omega_3\}$ . Of course, John is also able to observe the event "either $\omega_1$ or $\omega_2$ has occurred", which is modelled by including the union of $\{\omega_1\}$ and $\{\omega_2\}$ , given by $\{\omega_1, \omega_2\}$ , into $\mathcal{F}$ . Through a similar line of thought, we see that $\mathcal{F}$ has to be the power set of $\Omega$ : $$\mathcal{F}_1 = \mathscr{P}(\Omega) = \sigma(X).$$ The mutually exclusive events $\{\omega_1\}$ , $\{\omega_2\}$ , $\{\omega_3\}$ generate $\mathcal{F}$ , and the values of $X$ are captured/determined by the values on these generating events. Jack . According to the description, action $Y$ taken by Jack is defined as follows: $Y(\omega_1)=1$ , $Y(\omega_2)=2$ , $Y(\omega_3)=2$ . Since at time $T$ , John is able to distinguish the events " $\omega_1$ has occurred" and "either $\omega_2$ or $\omega_3$ has occurred", we include $\{\omega_1\}$ and $\{\omega_2, \omega_3\}$ in $\mathcal{F}$ . Of course John is also able to tell whether either of the two aforementioned events has occurred, which is reflected by including $\{\omega_1, \omega_2, \omega_3\}$ in $\mathcal{F}$ . Hence, $$\mathcal{F}_2 = \{ \{\omega_1, \omega_2, \omega_3\}, \{\omega_2, \omega_3\}, \{\omega_1\}, \emptyset \} = \sigma(Y).$$ The mutually exclusive events $\{\omega_1\}$ , $\{\omega_2, \omega_3\}$ generate $\mathcal{F}$ , and the values of $Y$ are captured/determined by the values on these generating events. Jane . According to the description, action $Z$ taken by Jane is defined as follows: $Z(\omega_1)=3$ , $Z(\omega_2)=1$ , $Z(\omega_3)=3$ . Since at time $T$ , Jane is able to distinguish the events " $\omega_2$ has occurred" and "either $\omega_1$ or $\omega_3$ has occurred", we include $\{\omega_2\}$ and $\{\omega_1, \omega_3\}$ in $\mathcal{F}$ . Of course Jane is also able to tell whether either of the two aforementioned events has occurred, which is reflected by including $\{\omega_1, \omega_2, \omega_3\}$ in $\mathcal{F}$ . Hence, $$\mathcal{F}_3 = \{ \{\omega_1, \omega_2, \omega_3\}, \{\omega_1, \omega_3\}, \{\omega_2\}, \emptyset \} = \sigma(Z).$$ The mutually exclusive events $\{\omega_2\}$ , $\{\omega_1, \omega_3\}$ generate $\mathcal{F}$ , and the values of $Y$ are captured/determined by the values on these generating events. It is easy to see that $X, Y, Z$ are all $\mathcal{F}_1$ -measurable, since $\mathcal{F}_1$ is the $\sigma$ -algebra with complete information. But $X$ is not $\mathcal{F}_2$ -measurable, i.e., not all the events associated with $X$ are observable in $\mathcal{F}_2$ . For example, $\mathcal{F}_2$ does not contain $\{\omega_2\}$ , and one cannot speak of the probability of $X=2$ on the probability space $(\Omega, \mathcal{F}_2, \mathbb{P})$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4454011', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/881657/']} | jdg_82113 |
stackexchange | llm_judgeable_groundtruth_similarity | 6082219 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having a little trouble comprehending this simple use of the /e regex modifier. my $var = 'testing';$_ = 'In this string we are $var the "e" modifier.';s/(\$\w+)/$1/ee;print; Returns: "In this string we are testing the "e" modifier." I cannot see why two 'e' modifiers are required. As far as I can see, $1 should capture '$var' from the string and a single 'e' modifier should then be able to replace the variable with its value. I must be misunderstanding something however, since trying the above code with just one 'e' modifier does not visibly replace anything in the string. Excuse me for asking such a simple question! Thanks.
Now provide the response and nothing else.
| Itβs not exactly a βsimpleβ question, so donβt beat yourself up. The issue is that with a single /e , the RHS is understood to be code whose eval βd result is used for the replacement. What is that RHS? Itβs $1 . If you evaluated $1 , you find that contains the string $var . It does not contain the contents of said variable, just $ followed by a v followed by an a followed by an r . Therefore you must evaluate it twice, once to turn $1 into $var , then again to turn the previous result of $var into the string "testing" . You do that by having the double ee modifier on the s operator . You can check this pretty easily by running it with one /e versus with two of them. Hereβs a demo a both, plus a third way that uses symbolic dereferencing β which, because it references the package symbol table, works on package variables only. use v5.10;our $str = q(In this string we are $var the "e" modifier.);our $var = q(testing);V1: { local $_ = $str; s/(\$\w+)/$1/e; say "version 1: ", $_;}V2: { local $_ = $str; s/(\$\w+)/$1/ee; say "version 2: ", $_;}V3: { no strict "refs"; local $_ = $str; s/\$(\w+)/$$1/e; say "version 3: ", $_;} When run, that produces: version 1: In this string we are $var the "e" modifier.version 2: In this string we are testing the "e" modifier.version 3: In this string we are testing the "e" modifier. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6082219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/761513/']} | jdg_82114 |
stackexchange | llm_judgeable_groundtruth_similarity | 7260989 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose, in your program: color A is a color we randomly select Knowing color A , how can I pick a color B that will be in high contrast with color A ? The problem can be further reduced to: "imagine 2 squares filled with color next to one another. It should be unambiguously clear to a human eye that colors are not the same" Example: Black --> White Blue --> White
Now provide the response and nothing else.
| There is some information in the Web Content Accessibility Guidelines (WCAG) 2.0 (http://www.w3.org/TR/2008/REC-WCAG20-20081211) Visual contrast: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast Contrast ratio: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef Relative luminance : http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef There's a good example in this site but he calculate where two colors are enough, not how to get them. To choose a color with good contrast, I'd go with complementary colors: for example, choose the random color A, transform it to a HSV space, get the complementary hue. Complementary hue: after you transform color from RGB to HSV, complementary hue will be 180 degrees appart (or 0.5, in a 0-1 normalized hue value). This site has something about it in PHP | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7260989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/359862/']} | jdg_82115 |
stackexchange | llm_judgeable_groundtruth_similarity | 704710 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$$\sum_{k=0}^{m}\binom{n+k}{n}=\binom{n+m+1}{n+1}$$ how to prove it without induction? I tried with several way but I failed anybody help me ?
Now provide the response and nothing else.
| $\newcommand{\+}{^{\dagger}} \newcommand{\angles}[1]{\left\langle #1 \right\rangle} \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace} \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack} \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,} \newcommand{\dd}{{\rm d}} \newcommand{\down}{\downarrow} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,{\rm e}^{#1}\,} \newcommand{\fermi}{\,{\rm f}} \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{{\rm i}} \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\isdiv}{\,\left.\right\vert\,} \newcommand{\ket}[1]{\left\vert #1\right\rangle} \newcommand{\ol}[1]{\overline{#1}} \newcommand{\pars}[1]{\left( #1 \right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}} \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,} \newcommand{\sech}{\,{\rm sech}} \newcommand{\sgn}{\,{\rm sgn}} \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert} \newcommand{\wt}[1]{\widetilde{#1}}$$\ds{\sum_{k = 0}^{m}{n + k \choose n} = {n + m + 1 \choose n + 1}:\ {\large ?}}$ \begin{align}\color{#00f}{\large\sum_{k = 0}^{m}{n + k \choose n}}&=\sum_{k = 0}^{m}\int_{\verts{z} = 1}{\pars{1 + z}^{n + k} \over z^{n + 1}}\,{\dd z \over 2\pi\ic}=\int_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z^{n + 1}}\sum_{k = 0}^{m}\pars{1 + z}^{n + k}\\[3mm]&=\int_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{1 \over z^{n + 1}}\,{\pars{1 + z}^{n}\bracks{\pars{1 + z}^{m + 1} - 1} \over \pars{1 + z} - 1}\\[3mm]&=\int_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{\pars{1 + z}^{n + m + 1} \over z^{n + 2}}-\\overbrace{%\int_{\verts{z} = 1}{\dd z \over 2\pi\ic}\,{\pars{1 + z}^{n} \over z^{n + 2}}}^{\ds{=\ 0}}\\[3mm]&=\sum_{k = 0}^{n + m + 1}{n + m + 1 \choose k}\overbrace{\int_{\verts{z} = 1}{z^{k} \over z^{n + 2}}\,{\dd z \over 2\pi\ic}}^{\ds{\delta_{k,n + 1}}}=\color{#00f}{\large{n + m + 1 \choose n + 1}}\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/704710', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_82116 |
stackexchange | llm_judgeable_groundtruth_similarity | 375303 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
(1) Are there formulae $\varphi_D(x)$ and $\varphi_\in(x,y)$ defining an internal model $\mathcal{N}$ of $ZFC$ where $\mathcal{N}$ is not set-like and no definable, set-like, internal model $\mathcal{M}$ is elementary equivalent to $\mathcal{N}$ ? (2) Are there formulae $\varphi_D(x)$ and $\varphi_\in(x,y)$ defining an internal model $\mathcal{N}$ of $ZFC$ where $\mathcal{N}$ is not set-like and no definable, set-like, $\it{well-founded}$ , internal model $\mathcal{M}$ is elementary equivalent to $\mathcal{N}$ ? A simple way to obtain non set-like models of $ZFC$ is to take a normal ultrafilter $U$ and take the iterated ultrapower of $V$ through length $Ord$ . This gives us a non set-like model of $ZFC$ , but it is elementary equivalent to $V$ . (This approach uses parameters, but they are easily removed.) In a vague nutshell, is there another way to define "long" models without some form of iteration?
Now provide the response and nothing else.
| Let me describe another method for making long models definable. First consider the case that $\kappa$ is inaccessible in $L$ and $\lambda$ is a worldly cardinal in $L$ above $\kappa$ . Let $G$ be $L$ -generic for the forcing to collapse $\lambda$ to $\kappa$ . In the forcing extension, there is a set $E\subset\kappa$ that codes the structure $\langle L_\lambda,\in\rangle$ . Let $L[G][H]$ be the forcing extension that codes the set $E$ into the GCH pattern up to $\kappa$ . This preserves the inaccessibility of $\kappa$ . Let $M=(V_\kappa)^{L[G][H]}$ , which is a model of ZFC since $\kappa$ remained inaccessible. In $M$ , we can define $E$ using the GCH pattern and therefore in $M$ we can define a copy of the structure $\langle L_\lambda,\in\rangle$ , which is a model of ZFC. This model is actually well-founded, and so the model $M$ will also look upon it as well-founded, and it is not set-like, since it has height $\lambda$ , which is taller than $\kappa$ . So this method shows how a model of ZFC can define a much taller well-founded model of ZFC. In your question, however, you had asked for more. You wanted the defined model to have a theory not realized in any set-like interpreted model of $M$ . Let me modify the construction to achieve something closer to this. I will show how to arrange that $N$ satisfies a theory not satisfied by any set structure in $M$ nor any definable well-founded set-like class structure. (Thanks, Ali, for your comments about this.) To do it, I will suppose not that $\kappa$ is actually inaccessible in $L$ , but rather merely that it is inaccessible in $L_\lambda$ , which is itself a pointwise definable model. One can make this situation from the situation above simply by taking the Mostowski collapse of the definable elements of $L_\lambda$ . Now, these are countable ordinals in $L$ , even though $L_\lambda$ thinks $\kappa$ is inaccessible. But we can still do the forcing $G$ and $H$ and form the model $M=(V_\kappa)^{L_\lambda[G][H]}$ just as above, except that we take $G$ merely $L_\lambda$ -generic and $H$ is $\langle L_\kappa,\in,E\rangle$ -generic. In $M$ , again we can define $L_\lambda$ as a well-founded non-set-like model of ZFC. The point of the pointwise definability assumption is that the theory $T$ of $L_\lambda$ ensures that every model of it contains a copy of $L_\lambda$ . There can be no set model of this theory in $M$ , because then $M$ would be able to take the definable elements of that model and thereby produce a copy of $L_\lambda$ as a set, which is impossible in $M$ since $\kappa<\lambda$ . Similarly, there can be no well-founded set-like class definable model of the theory in $M$ , since any such model $N$ would have to have an ordinal with at least $\kappa$ many predecessors, and such an order relation would not be set-like in $M$ . What remains is the possibility that there could be a definable set-like class model in $M$ , not necessarily well-founded, but which satisfies the theory. I don't at the moment know how to rule this out. The subtle point is that a set-like order in $M$ can contain a copy of $\lambda$ β after all, both $\kappa$ and $\lambda$ are countable ordinals and hence embed into $\mathbb{Q}$ , which is set-like in $M$ β and the pointwise definability idea doesn't seem quite enough to rule out such ill-founded interpreted classs models. Therefore, this answer doesn't quite fully answer the question. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/375303', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9324/']} | jdg_82117 |
stackexchange | llm_judgeable_groundtruth_similarity | 15898 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am finding Pythagorean_triple , it worked slowly. I tried to compile, but it gives some warnings. I also use "Case" or "Do" ,both of them failed.I'm sure my CCompiler has been set correctly.How can I compile the following code? With[{m = 200}, Select[Flatten[Table[{x, y, z}, {x, m}, {y, x, m}, {z, y, m}], 2], (#1^2 + #2^2 == #3^2 &) @@ # &] ]
Now provide the response and nothing else.
| There are much faster ways to generate Pythagorean triples. Update: Now twice as fast . genPTunder[lim_Integer?Positive] := Module[{prim}, prim = Join @@ Table[ If[CoprimeQ[m, n], {2 m n, m^2 - n^2, m^2 + n^2}, ## &[]], {m, 2, Floor @ Sqrt @ lim}, {n, 1 + m ~Mod~ 2, m, 2} ]; Union @@ (Range[lim ~Quotient~ Max@#] ~KroneckerProduct~ {Sort@#} & /@ prim) ]genPTunder[50] {{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17}, {9, 12, 15}, {9, 40, 41}, {10, 24, 26}, {12, 16, 20}, {12, 35, 37}, {14, 48, 50}, {15, 20, 25}, {15, 36, 39}, {16, 30, 34}, {18, 24, 30}, {20, 21, 29}, {21, 28, 35}, {24, 32, 40}, {27, 36, 45}, {30, 40, 50}} genPTunder[100000] // Length // Timing {0.125, 161436} Over 160,000 triples in an eighth of a second should be serviceable, even without compilation. | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/15898', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2090/']} | jdg_82118 |
stackexchange | llm_judgeable_groundtruth_similarity | 990489 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $R$ be a commutative ring, when $\mathfrak p$ is a prime ideal, there is the localization $M_{\mathfrak p}:=S^{-1}M$, where $S=R\setminus\mathfrak p$. Show: If $M$ is a nonzero $R$-module, then there exists a prime ideal $\mathfrak p$ such that $M_{\mathfrak p}\neq 0$. I don't understand this exercise, in which case is $M_{\mathfrak p}$ zero ? $M$ is nonzero, this is good. So does it remain to prove that the set $R\setminus\mathfrak p$ is nonempty ? $\textbf{EDIT:}$ I think I got it: If $M$ is nonzero $\implies\exists m\in M,m\neq 0$ let $I=\{a\in R:aM=0\}$ since $1\in R\Rightarrow1\cdot m=m\neq 0\implies I\neq R$ and $I$ is an ideal, so $\exists$ maximal ideal $\mathfrak p$, s.t. $I\subseteq\mathfrak p$ but every maximal ideal is prime, so suppose $M_{\mathfrak p}=0$ then ; $m/1=0$ in $M_{\mathfrak p}\implies m/1=0/1$ by definition $\exists s\in R\setminus\mathfrak p$ such that $0=s(1\cdot m-1\cdot 0)=sm$ Hence $s\in I\subseteq\mathfrak p$ but $s\in R\setminus\mathfrak p\implies s\notin\mathfrak p$ which is absurd.
Now provide the response and nothing else.
| $M_p=0$ if and only if $x/s=0/1$ for all $x\in M$ and $s\in R-p$ if and only if for all $x\in M$ there is $t_p\in R-p$ such that $t_px=0$. If all localizations $M_p$ are $0$, then $M=0$. Pick an element $x\in M$. Since $x/s=0/1$ in $M_p$ there is $t_p\in R-p$ such that $t_px=0$. Now notice that the ideal generated by all $t_p$, when $p$ runs through the set of prime ideals of $R$, equals the whole ring. Write $1$ as a (finite) linear combination of $t_p$ and multiplying by $x$ get $x=0$. Edit. An alternative proof (using annihilators): If $M\ne 0$ pick a non-zero element $x\in M$ and consider its annihilator $\operatorname{Ann}(x)=\{a\in R\mid ax=0\}$. This is an ideal of $R$ and clearly $\operatorname{Ann}(x)\ne R$. There is a prime ideal $p$ of $R$ such that $\operatorname{Ann}(x)\subseteq p$. Then $x/1\ne0/1$ in $M_p$, otherwise there is $t_p\in R-p$ such that $t_px=0$, a contradiction. This proves that $M_p\ne0$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/990489', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166923/']} | jdg_82119 |
stackexchange | llm_judgeable_groundtruth_similarity | 9114591 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Iβm looking for a way to simulate resistance using the jQueryUI draggable plugin (similar to this effect ). At the bottom of the draggable documentation it mentions: βTo manipulate the position of a draggable during drag, you can either use a wrapper as the draggable helper and position the wrapped element with absolute positioning, or you can correct internal values like so: $(this).data('draggable').offset.click.top -= xβ. Geometry not being my strong suit I was looking for help on how to best achieve the effect of resistance when dragging something. I thought that using this tip above, I could change the distance the draggable is moved using a geometric function. Iβm not sure if the best term is resistance or elasticity, but Iβm looking for the feel as if an element is attached to a point by a rubber band or bungee cord so that the further you drag, the less the object moves. For example, say I want to drag an object a total distance of 500 pixels (in any direction). I would like the resistance effect to increase the closer to 500 pixels away from the starting point I get. Iβve looked around and havenβt seen anything like this. Update : I created a basic jsFiddle that calculates the distance an item has been dragged at http://jsfiddle.net/Z8m4B/ The calculation is: var x1=x2=y1=y2=0;$("#draggable").draggable({ start: function(e, ui) { y1 = ui.position.top; x1 = ui.position.left; }, stop: function(e, ui) { y2 = ui.position.top; x2 = ui.position.left; dist = parseInt(Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2)), 10); console.log(dist); }}); Obviously I would want to change the distance during the drag event and not on stop. Does anyone know how a function to create this resistance or stretch effect?
Now provide the response and nothing else.
| you can try with this http://jsfiddle.net/sAX4W/ with the drag event you can calculate the distance and get a % from the real distance var x1 = x2 = y1 = y2 = 0;$("#draggable").draggable({ revert: true, revertDuration: 100, axis: 'y', drag: function(e, ui) { y2 = ui.position.top; x2 = ui.position.left; dist = parseInt(Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)), 10); ui.position.top = ui.position.top * (1 - (dist / 1000)); }, start: function(e, ui) { y1 = ui.position.top; x1 = ui.position.left; }, stop: function(e, ui) { }}); edit you can try this with both axis http://jsfiddle.net/2QndJ/ var x1 = x2 = y1 = y2 = 0;$("#draggable").draggable({ revert: true, revertDuration: 100, drag: function(e, ui) { y2 = ui.position.top; x2 = ui.position.left; dist = parseInt(Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)), 10); ui.position.top = ui.position.top * (1 - (dist / 1000)); ui.position.left = ui.position.left * (1 - (dist / 1000)); }, start: function(e, ui) { y1 = ui.position.top; x1 = ui.position.left; }, stop: function(e, ui) { }}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9114591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/616443/']} | jdg_82120 |
stackexchange | llm_judgeable_groundtruth_similarity | 864568 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to figure out how to take the modulo of a fraction. For example: 1/2 mod 3. When I type it in google calculator I get 1/2. Can anyone explain to me how to do the calculation?
Now provide the response and nothing else.
| One can perform arithmetic of fractions mod $\,m\,$ as long as all fractions $\,a/b\,$ have denominator $\,b\,$ coprime to $\,m,\,$ since then, by Bezout, $\,b\,$ is invertible mod $\,m\,$ so the fraction has the unique denotation $\,x = a/b = ab^{-1}$ (the unique solution of $\,bx = a).\,$ The usual rules of fraction arithmetic remain true (as long as one restricts to such fractions), e.g. from a prior answer: Hint $\,\ {\rm mod}\ 13\!:\ \dfrac{41}7 \equiv \dfrac{28}7 \equiv 4\ \ $ by $\ \ 41\equiv 41\!-\!13 \equiv 28$ Alternatively $\,\ \dfrac{41}{7}\equiv\dfrac{(-2)(-1)}{-6}\equiv \dfrac{-2}{-2}\dfrac{12}3\equiv 4\ \ $ by $\ \ \begin{eqnarray}41&&\!\!\equiv\ \ 2\\ 7 &&\!\!\equiv -6\end{eqnarray}$ Alternatively $\,\ \dfrac{41}{7}\equiv \dfrac{2}7\equiv \dfrac{4}{14}\equiv \dfrac{4}1\ $ by Gauss's Algorithm. Such twiddling (adding/subtracting the modulus from numerator or denominator till things divide or factor nicely) works quite well for small numbers. For larger numbers one can invert the denominator by the Extended Euclidean Algorithm , or Gauss's algorithm if the modulus is prime. Beware $\ $ The use of fractions in modular arithmetic is valid only when the denominator is invertible, i.e. coprime to the modulus. Otherwise the quotient need not be unique, for example mod $\rm\:10,\:$ $\rm\:4\,x\equiv 2\:$ has solutions $\rm\:x\equiv 3,8,\:$ so the "fraction" $\rm\:x \equiv 2/4\pmod{10}\,$ cannot designate a unique solution of $\,4x\equiv 2.\,$ Indeed, the solution is $\rm\:x\equiv 1/2\equiv 3\pmod 5,\,$ which requires canceling $\,2\,$ from the modulus too, since $\rm\:10\:|\:4x-2\iff5\:|\:2x-1.\:$ Generally the grade-school rules of fraction arithmetic apply universally (i.e. in all rings) where the denominators are invertible. This fundamental property will be clarified conceptually when one learns in university algebra about the universal properties of fractions rings and localizations. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/864568', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112806/']} | jdg_82121 |
stackexchange | llm_judgeable_groundtruth_similarity | 5026285 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know we can easily do this by a simple loop, but I want to persue this LINQ/Predicate? string[] columnNames = dt.Columns.?orstring[] columnNames = from DataColumn dc in dt.Columns select dc.name;
Now provide the response and nothing else.
| Try this (LINQ method syntax): string[] columnNames = dt.Columns.Cast<DataColumn>() .Select(x => x.ColumnName) .ToArray(); or in LINQ Query syntax: string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray(); Cast is required, because Columns is of type DataColumnCollection which is a IEnumerable , not IEnumerable<DataColumn> . The other parts should be obvious. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5026285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205783/']} | jdg_82122 |
stackexchange | llm_judgeable_groundtruth_similarity | 31165 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $K$ be a algebraic number field of degree $n$ over $\mathbb{Q}$, and $O$ its ring of integers. Let $P$ be a prime ideal of $O$ and $(p)=P \cap \mathbb{Z}$.Is it true that the localization $O_{P}$ is a rank $n$ free module over $\mathbb{Z}_{(p)}$ (the localization of $\mathbb{Z}$ at $(p)$) if and only if $P$ is the only prime above $(p)$?
Now provide the response and nothing else.
| Well, if $P$ is not the only prime above $p$, then $O_P$ cannot be a finitely-generated $\mathbb{Z}_{(p)}$-module for the following reason. Suppose $Q$ is another prime ideal above $p$ and select $\beta\in Q\setminus P$. Then $\beta^{-1}\in O_P$. If $O_P$ were finitely-generated as a module over $\mathbb{Z}_{(p)}$, then it would be integral over $\mathbb{Z}_{(p)}$, and hence would be contained in the integral closure of $\mathbb{Z}_{(p)}$ in $K$, which is $O_p$. But then $\beta^{-1}\in O_p$, so $1/\beta=\alpha/m$ for some integer $m$ not divisible by $p$. This means that $m=\alpha\beta\in Q$, whence $m\in Q\cap\mathbb{Z}=(p)$, a contradiction. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/31165', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7456/']} | jdg_82123 |
stackexchange | llm_judgeable_groundtruth_similarity | 28085201 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this html: <select onchange="check_status(this);" name="status[171]"> <option selected="true" value="open" data="04f2cf35e4d7a1c0158459fd0450a605">open</option> <option value="in_process" data="04f2cf35e4d7a1c0158459fd0450a605">pending</option> <option value="finished" data="04f2cf35e4d7a1c0158459fd0450a605">finished</option> <option value="canceled" data="04f2cf35e4d7a1c0158459fd0450a605">canceled</option> </select> and js function check_status(obj){ var uid = obj.getAttribute('data'); alert(uid);} but it always alerts null instead of data valueWhere is the problem guys? Thanks
Now provide the response and nothing else.
| The problem is that you get select element and not selected option element as function argument. And it does not have the data attribute. You have to get the option attribute like so: function check_status(obj) { var uid = obj.options[obj.selectedIndex].getAttribute('data-uid'); alert(uid);} <select onchange="check_status(this);" name="status[171]"> <option selected="true" value="open" data-uid="01f2cf35e4d7a1c0158459fd0450a601">open</option> <option value="in_process" data-uid="02f2cf35e4d7a1c0158459fd0450a602">pending</option> <option value="finished" data-uid="03f2cf35e4d7a1c0158459fd0450a603">finished</option> <option value="canceled" data-uid="04f2cf35e4d7a1c0158459fd0450a604">canceled</option></select> Notice that I changed the attribute name to data-uid for it to be valid according to HTML5 specificaion. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28085201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3873057/']} | jdg_82124 |
stackexchange | llm_judgeable_groundtruth_similarity | 15451501 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Playing around in ghci I got the following expression: unlines . map (\(a,b) -> show a ++ " " ++ show b) Now when I check it via :t I get: > :t unlines . map (\(a,b) -> show a ++ " " ++ show b)unlines . map (\(a,b) -> show a ++ " " ++ show b) :: (Show a, Show a1) => [(a, a1)] -> String So exactly as expected. But now if I try to assign it to some name, I get a more specific signature than the original one: > let f = unlines . map (\(a,b) -> show a ++ " " ++ show b)> :t ff :: [((), ())] -> String Why does this happen?
Now provide the response and nothing else.
| Because of the monomorphism restriction , definitions of the form x = ... (no parameters) are given a monomorphic (i.e. non-polymorphic) type, which usually involves some defaulting as mentioned in the other answer . To prevent this from happening, either add a type signature to your definition, or disable the monomorphism restriction using :set -XNoMonomorphismRestriction . You can add this to your .ghci file to have it run automatically on startup until it gets disabled by default in GHCi in some future version . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15451501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31667/']} | jdg_82125 |
stackexchange | llm_judgeable_groundtruth_similarity | 1607086 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been looking for a regular expression with Google for an hour or so now and can't seem to work this one out :( If I have a number, say: 2345 and I want to find any other number with the same digits but in a different order, like this: 2345 For example, I match 3245 or 5432 (same digits but different order) How would I write a regular expression for this?
Now provide the response and nothing else.
| There is an "elegant" way to do it with a single regex: ^(?:2()|3()|4()|5()){4}\1\2\3\4$ will match the digits 2, 3, 4 and 5 in any order. All four are required. Explanation: (?:2()|3()|4()|5()) matches one of the numbers 2, 3, 4, or 5. The trick is now that the capturing parentheses match an empty string after matching a number (which always succeeds). {4} requires that this happens four times. \1\2\3\4 then requires that all four backreferences have participated in the match - which they do if and only if each number has occurred once. Since \1\2\3\4 matches an empty string, it will always match as long as the previous condition is true. For five digits, you'd need ^(?:2()|3()|4()|5()|6()){5}\1\2\3\4\5$ etc... This will work in nearly any regex flavor except JavaScript. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1607086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119396/']} | jdg_82126 |
stackexchange | llm_judgeable_groundtruth_similarity | 42789953 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Swift 3 and trying to access captured groups. let regexp = "((ALREADY PAID | NOT ALR | PROVIDER MAY | READY | MAY BILL | BILL YOU | PAID)((.|\\n)*))(( \\d+)(\\.+|-+)(\\d\\d))"// check if some substring is in the recognized textif let range = stringText.range(of:regexp, options: .regularExpression) { let result = tesseract.recognizedText.substring(with:range)} I want to be able to extract out the last two numbers captured ( \d\d ) so if the text was: ALREADY PAID asfasdfadsfasdf 39.15 , it would extract 15 . Here is a regex builder that shows what I want. Normally, I would be able to do $8 to get the 8th group that was extracted but I don't know how to do that in Swift 3. http://regexr.com/3fh1e
Now provide the response and nothing else.
| but I don't know how to do that in Swift 3. When you receive a match from NSRegularExpression, what you get is an NSTextCheckingResult. You call rangeAt to get a specific capture group. Example: let s = "hey ho ha"let pattern = "(h).*(h).*(h)"// our goal is capture group 3, "h" in "ha"let regex = try! NSRegularExpression(pattern: pattern)let result = regex.matches(in:s, range:NSMakeRange(0, s.utf16.count))let third = result[0].rangeAt(3) // <-- !!third.location // 7third.length // 1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42789953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487135/']} | jdg_82127 |
stackexchange | llm_judgeable_groundtruth_similarity | 434124 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My Software Engineering teacher just said: "Avoid using continue and break , always make it work without using these". Is there a problem with these instructions? I would say he didn't say something so coherent, but maybe I don't know something about it?
Now provide the response and nothing else.
| Some teachers oversimplify on this topic (especially when they only teach, but don't do daily real-world programming any more). Of course, I don't know if that applies to your teachers, but I would not listen to the advice against continue and break too literally. continue and break can make loops more readable or less readable, depending on how they are used. The real problem are loops with too large inner bodies and many conditions for stopping them or executing only parts. Having multiple continue and break in such a loop is only a symptom for this "disease", but working around those keywords just formally isn't the cure. If running into such a situation, one could try to avoid the mentioned keywords by using boolean flags and complex if/else blocks instead, but that will not make the code simpler. Quite the opposite - often it will become even uglier. So what is the cure? Refactor inner parts of large loops into smaller functions. These functions might return some status information which can be used to control the outer calling loop, and it can be perfectly fine to use break or continue controlled by the returned status. If the functions are still complex, decompose them to smaller functions themselves. Avoid processing too many things in one loop. Instead, organize your code to process sets of data, which can lead to a sequence of two or three simpler loops instead of one complex one. So there might be one loop which produces some intermediate array of data, then a second one which takes the output of the first loop, iterates over this data and hands the result set to a third. Often, each of these loops can be put into a function on their own, returning its result set, which is passed as a parameter into the next function. You will be astonished how much much simpler your code will get when you just apply these two guidelines rigorously. | {} | {'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/434124', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/406256/']} | jdg_82128 |
stackexchange | llm_judgeable_groundtruth_similarity | 646468 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to see a proof, or at least to know when can I use that statement: $$\text{ord}(mn,a)=\text{lcm}(\text{ord}(m,a),\text{ord}(n,a))$$ where $\text{ord}(n,x)$ means the order of $x$ in $\mathbb{Z}_n $ (i.e the smallest $t$ such that $x^t = 1 \mod n$).
Now provide the response and nothing else.
| By an obvious change variable we have $$\int_1^A\frac{f(x)-f(2x)}{x}dx=\int_1^A\frac{f(x)}{x}dx-\int_2^{2A}\frac{f(x)}{x}dx=\int_1^2\frac{f(x)}{x}dx-\int_A^{2A}\frac{f(x)}{x}dx$$ Now since $\displaystyle\lim_{x\to\infty}f(x)=L$ we prove easily that$$\lim_{A\to\infty}\int_A^{2A}\frac{f(x)}{x}dx=L\log2\tag{*}$$so$$\int_1^\infty\frac{f(x)-f(2x)}{x}dx=\int_1^2\frac{f(x)}{x}dx-L\log2$$ Edit Here I explain the equality $(*)$: We have $\displaystyle\lim_{x\to\infty}f(x)=L$ so for $\epsilon>0$ there's $A>0$ and if $x\ge A$ we have $|f(x)-L|\le\epsilon$, hence$$\left|\int_A^{2A}\frac{f(x)}{x}dx-L\log2\right|=\left|\int_A^{2A}\frac{f(x)-L}{x}dx\right|\le\int_A^{2A}\frac{|f(x)-L|}{x}dx\le\epsilon\log2$$so we have the desired equality. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/646468', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/122372/']} | jdg_82129 |
stackexchange | llm_judgeable_groundtruth_similarity | 6778793 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a pretty basic question. In some examples I've seen, objects are just released in the dealloc method. In others, the objects are released and then set to nil . Is there a reason for this? Is setting to nil after releasing advantageous?
Now provide the response and nothing else.
| Three ways to dealloc 1. Just release - (void)dealloc { [airplane release]; [super dealloc];} Now the object reference points to a random position, which may be one of two things: Most likely it is garbage, because the memory position can't be interpreted as an object. Rarely it will be a different object, because memory have been reused to create a new object. The effect of a further method calls through this pointer is one of these three (which one is undefined): A crash with EXC_BAD_ACCESS because the pointer points to garbage. A crash with undefined selector because it points to a valid object which doesn't have that method. A successful method execution because the new object has a method by the same name. 2. Release and nil - (void)dealloc { [airplane release], airplane = nil; [super dealloc];} Now the object reference is nil and any further method calls are ignored. This may silently cause a defined but unforeseen lateral effect in your code, but at least it doesn't crash your application. 3. Nil and release - (void)dealloc { id temp = airplane; airplane = nil; [temp release]; [super dealloc];} This is the same as before, but it removes that small window between release and nil where the object reference points to an invalid object. Which one is best? It is a matter of choice: If you rather crash choose just release. If you rather ignore the mistake choose nil+release or release+nil. If you are using NSZombieEnabled=TRUE then just release, don't nil the zombie! Macros and zombies A easy way to defer your choice is using a macro. Instead [airplane release] you write safeRelease(x) where safeRelease is the following macro that you add to your .pch target file: #ifdef DEBUG #define safeRelease(x) [x release]#else #define safeRelease(x) [x release], x=nil#endif This macro doesn't respect zombies. Here is the problem: when NSZombieEnabled is TRUE the object turns into a NSZombie . If you nil its object reference, any call sent to him will be ignored. To fix that, here is a macro from Kevin Ballard that sets the pointer to an invalid made up reference ONLY when NSZombieEnabled is FALSE . This guarantees a crash during debug time if zombies are not enabled, but leaves the zombies be otherwise. #if DEBUG #define safeRelease(x) do { [x release]; if (!getenv("NSZombieEnabled")) x = (id)0xDEADBEEF; } while (0)#else #define safeRelease(x) [x release], x = nil#endif References Apple doesn't have a recommendation on which one is best. If you want to read the thoughts of the community here are some links (the comment threads are great too): Dealloc Jeff Lamarche Donβt Coddle Your Code Daniel Jalkut More on dealloc Jeff Lamarche To nil, or not to nil, that is the question Ching-Lan Huang Defensive Coding in Objective-C Uli Kusterer | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6778793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781303/']} | jdg_82130 |
stackexchange | llm_judgeable_groundtruth_similarity | 7717527 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section. Using Anchor links, I can make the page scroll towards the anchor and guide the users there. Is there a way to make that scrolling smooth? But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?
Now provide the response and nothing else.
| Update April 2018: There's now a native way to do this : document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); });}); This is currently only supported in the most bleeding edge browsers. For older browser support, you can use this jQuery technique: $(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500);}); And here's the fiddle: http://jsfiddle.net/9SDLw/ If your target element does not have an ID, and you're linking to it by its name , use this: $('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top }, 500); return false;}); For increased performance, you should cache that $('html, body') selector, so that it doesn't run every single time an anchor is clicked: var $root = $('html, body');$('a[href^="#"]').click(function () { $root.animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); return false;}); If you want the URL to be updated, do it within the animate callback: var $root = $('html, body');$('a[href^="#"]').click(function() { var href = $.attr(this, 'href'); $root.animate({ scrollTop: $(href).offset().top }, 500, function () { window.location.hash = href; }); return false;}); | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/7717527', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/699978/']} | jdg_82131 |
stackexchange | llm_judgeable_groundtruth_similarity | 16122466 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently, I have been trying to understand what is the difference between using the Service Locator "anti-pattern" and using the Castle Windsor container. I have found some info here and there on the Internet and I have summarized what I have learned so far in an unfinished blog post . EDIT: Until now I have been thinking that Dependency Injection is all one would need to guarantee separation. But everywhere I look I see a push in the direction of containers such as Castle Windsor. I would like to clearly understand the reasons.Please... Explain this to me like I'm a 6 year old :)
Now provide the response and nothing else.
| Funny you should ask to have it explained like you were six years old; here's an explanation like you were five years old :) everywhere I look I see a push in the direction of containers such as Castle Windsor Frankly, I think the reason for that is that most people actually don't understand what Dependency Injection is, which means that instead of grasping the concept of Inversion of Control, they go looking for a replacement for the new keyword they're already used to. Then they find a DI Container and (mis)use it as a Service Locator. Unfortunately, that's very easy to do. This is the reason why, in my book , I explain all the DI concepts without coupling the explanation to any single DI Container. That's actually the majority of the book. Service Locator and Dependency Injection are two fundamentally different attempts at achieving loose coupling . Service Locator has many disadvantages, and offers no advantages not also offered by DI. This is why I think it's safe to call Service Locator an anti-pattern. You don't need a DI Container to use DI; in fact, I would say that unless you take a rather sophisticated approach, it's probably better to avoid one . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16122466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438078/']} | jdg_82132 |
stackexchange | llm_judgeable_groundtruth_similarity | 17836939 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a class: class DatabaseThing(): def __init__(self, dbName, user, password): self.connection = ibm_db_dbi.connect(dbName, user, password) I want to test this class but with a test database. So in my test class I am doing something like this: import sqlite3 as liteimport unittestfrom DatabaseThing import *class DatabaseThingTestCase(unittest.TestCase): def setUp(self): self.connection = lite.connect(":memory:") self.cur = self.connection.cursor() self.cur.executescript ('''CREATE TABLE APPLE (VERSION INT, AMNT SMALLINT); INSERT INTO APPLE VALUES(16,0); INSERT INTO APPLE VALUES(17,5); INSERT INTO APPLE VALUES(18,1); INSERT INTO APPLE VALUES(19,15); INSERT INTO APPLE VALUES(20,20); INSERT INTO APPLE VALUES(21,25);''') How would I go about using this connection than the connection from the class I want to test? Meaning using the connection from setUp(self) instead of the connection from DatabaseThing . I cannot test the functions without instantiating the class. I want to mock the __init__ method somehow in the Test Class, but I didn't find anything that seemed useful in the documentation .
Now provide the response and nothing else.
| Instead of mocking, you could simply subclass the database class and test against that: class TestingDatabaseThing(DatabaseThing): def __init__(self, connection): self.connection = connection and instantiate that class instead of DatabaseThing for your tests. The methods are still the same, the behaviour will still be the same, but now all methods using self.connection use your test-supplied connection instead. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17836939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_82133 |
stackexchange | llm_judgeable_groundtruth_similarity | 5226550 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I override the behavior of the Function object so that I can inject behavior prior t every function call, and then carry on as normal? Specifically, (though the general idea is intriguing in itself) can I log to the console every function call without having to insert console.log statements everywhere? And then the normal behavior goes on? I do recognize that this will likely have significant performance problems; I have no intention of having this run typically, even in my development environment. But if it works it seems an elegant solution to get a 1000 meter view on the running code. And I suspect that the answer will show me something deeper about javascript.
Now provide the response and nothing else.
| The obvious answer is something like the following: var origCall = Function.prototype.call;Function.prototype.call = function (thisArg) { console.log("calling a function"); var args = Array.prototype.slice.call(arguments, 1); origCall.apply(thisArg, args);}; But this actually immediately enters an infinite loop, because the very act of calling console.log executes a function call, which calls console.log , which executes a function call, which calls console.log , which... Point being, I'm not sure this is possible. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5226550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165031/']} | jdg_82134 |
stackexchange | llm_judgeable_groundtruth_similarity | 337766 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The entry OEIS A139605 (also related OEIS A145271 ) has a matrix computation for the partition polynomials that represent the expansions of iterated derivatives, or vectors in differential geometry, $$(g(x)D_x)^n.$$ The formula section of A139605 contains the matrix formula. Multiply the $n$ -th diagonal (with $n=0$ the main diagonal) of the lower triangular Pascal matrix A007318 by $g_n = D_x^n g(x)$ to obtain the matrix $VP$ with $VP_{n,k} = \binom{n}{k}g_{n-k} $ . Then $$(g(x)D)^n = (1, 0, 0,..) [VP \dot \; S]^n (1, D, D^2, ..)^T,$$ where S is the shift matrix A129185 , representing differentiation in the divided powers basis $x^n/n!$ . Example: $$(g(x)D_x)^3$$ $$= (1, 0, 0, 0) [VP \dot \; S]^3 (1, D, D^2, D^3)^T$$ $$= \begin{pmatrix}1 & 0 & 0 & 0\end{pmatrix} \begin{pmatrix}0 & g_0 & 0 & 0 \\ 0 & g_1 & g_0 & 0\\ 0 & g_2 & 2g_1 & g_0 \\ 0 & g_3 & 3g_2 & 3g_1\end{pmatrix}^3 \begin{pmatrix}1 \\ D \\ D^2 \\ D^3 \end{pmatrix} $$ $$ = [g_0g_1^2 + g_0^2 g_2] D + 3 g_0^2g_1 D^2 + g_0^3D^3 $$ And, the pdf Mathemagical Forests gives a diagrammatic method for creating forests of trees through "natural growth" that represent the partition polynomials. I have either lost a proof of the validity of this formula or got sidetracked before I developed one. Question : Can someone prove this conjecture? Some background: The refined Eulerian numbers (RENs) of A145271 are related analytically to the compositional inversion of functions and formal generating series and to flow fields generated by tangent vectors. The $n$ -th row of RENs are the numerical coefficients of the expansion of $(g(x)\frac{d}{dx})^ng(x)$ in terms of the monomials in the derivatives of $g(x)$ , i.e., $$g_k=\frac{d^k}{dx^k}g(x).$$ For example, $$(g(x)\frac{d}{dx})^3g(x) = 1 g_0^1 g_1^3 + 4 g_0^2 g_1^1 g_2^1 + 1 g_0^3 g_3^1.$$ With $(\omega,x) = (f(x),f^{(-1)}(\omega))$ and $g(x) = 1/f^{'}(x)$ , $$\exp[t g(x)d/dx]x = \exp[td/d\omega]f^{(-1)}(\omega) = f^{(-1)}(t+\omega)=f^{(-1)}(t+f(x)).$$ Evaluated at the origin of $x$ , this gives the compositional inverse $$\exp[tg(x)d/dx] x |_{x=0}=f^{(-1)}(t).$$ See also 1) MO-Q Guises of the refined Eulerian numbers generated by tangent vectors 2) MO-Q Important formulas in combinatorics 3) MO-Q Why is there a connection between enumerative geometry and nonlinear waves?
Now provide the response and nothing else.
| I have finally written up the proof in detail. It is in my note Darij Grinberg, Commutators, matrices and an identity of Copeland , also available as arXiv:1908.09179v1 . Your result is a particular case of Theorem 4.2. More precisely, you get it from Theorem 4.2 if you set $\mathbb{L}$ to be the ring of differential operators (whatever kind of differential operators you are considering), $\mathbb{K}$ to be the base ring, $a$ to be the differentiation operator (which is your $D$ ), $x$ to be the "multiplication by $t$ " operator (you use $x$ for what I call $t$ , but I keep them separate because my ring $\mathbb{L}$ doesn't have to contain the polynomial ring $\mathbb{K}\left[t\right]$ ), and $h$ to be the identity map. I derive this from a more general formula (Theorem 2.7), which expresses $\left(ba\right)^n$ as a matrix product when $a$ and $b$ are two arbitrary elements of a noncommutative ring. I work in a setting that allows the matrices to be finite or infinite as the reader prefers. This is responsible for a lot of the length of the note (as I have to set up an appropriate ring of infinite matrices on which multiplication is defined and associative, but also mess around with partial equalities in the case of finite matrices because the finite version of the shift operator doesn't behave as well as the infinite one). I hope the exposition is not completely wasted; meanwhile I trust you know what to skip and what to skim. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/337766', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12178/']} | jdg_82135 |
stackexchange | llm_judgeable_groundtruth_similarity | 42043226 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
in this scenario: async def foo(f): async def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper@fooasync def boo(*args, **kwargs): pass is the call to foo as a decorator for boo decorator an async call? --First Edit:Also how does one handle calling chain of coroutines as decorators?
Now provide the response and nothing else.
| Thanks to @blacknght's comment, considering def foo(): def wrapper(func): @functools.wraps(func) async def wrapped(*args): # Some fancy foo stuff return await func(*args) return wrapped return wrapper and def boo(): def wrapper(func): @functools.wraps(func) async def wrapped(*args): # Some fancy boo stuff return await func(*args) return wrapped return wrapper as two decorators, and @foo()@boo()async def work(*args): pass As the foo is wrapping the work coroutine, the key is to await the func(*arg) in both decorators. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42043226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6764079/']} | jdg_82136 |
stackexchange | llm_judgeable_groundtruth_similarity | 302577 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If it's harder to explain using words, let's look at an exampleI have a generic function like this void FunctionA<T>() where T : Form, new(){} If I have a reflected type, how do I use it with the above function? I'm looking forward to do this Type a = Type.GetType("System.Windows.Forms.Form");FunctionA<a>(); Of cause the above method doesn't work.
Now provide the response and nothing else.
| You can't. Generics in .NET must be resolved at compile time. You're trying to do something that would resolve them at runtime. The only thing you can do is to provide an overload for FunctionA that takes a type object. Hmmm... the commenter is right. class Program{ static void Main(string[] args) { var t = typeof(Foo); var m = t.GetMethod("Bar"); var hurr = m.MakeGenericMethod(typeof(string)); var foo = new Foo(); hurr.Invoke(foo, new string[]{"lol"}); Console.ReadLine(); }}public class Foo{ public void Bar<T>(T instance) { Console.WriteLine("called " + instance); }} MakeGenericMethod . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/302577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20007/']} | jdg_82137 |
stackexchange | llm_judgeable_groundtruth_similarity | 10276074 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When running my program by clicking Run or pressing Ctrl + F5 , is it possible to open different windows based on some check condition? I.e if some condition is satisfied I wish to open a particular window, but if its not I want to open another window. It should be like before opening any window it should first check for the condition like if(File.Exists(<path-to-file>) Open Window 1else Open Window 2 Is this possible?
Now provide the response and nothing else.
| look into App.xaml remove StartupUri="MainWindow.xaml" add Startup="Application_Startup" new event Handler <Application x:Class="YourProject.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="Application_Startup"> form code behind App.xaml.cs create Application_Startup like... private void Application_Startup(object sender, StartupEventArgs e) { //add some bootstrap or startup logic var identity = AuthService.Login(); if (identity == null) { LoginWindow login = new LoginWindow(); login.Show(); } else { MainWindow mainView = new MainWindow(); mainView.Show(); } } | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10276074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/942533/']} | jdg_82138 |
stackexchange | llm_judgeable_groundtruth_similarity | 55988991 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've done npm audit and it showed me that I have one High vulnerability. That's the information that it gave to me: βββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ High β Arbitrary File Overwrite ββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββ€β Package β tar ββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββ€β Patched in β >=4.4.2 ββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββ€β Dependency of β node-sass-chokidar ββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββ€β Path β node-sass-chokidar > node-sass > node-gyp > tar ββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββ€β More info β https://npmjs.com/advisories/803 |βββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββ I looked at my package-lock.json for node-gyp package and I found that tar package still has version 2.0.0 however I need 4.4.8: "node-gyp": { "version": "3.8.0", "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-3.8.0.tgz", "integrity": "sha512-3g8lYefrRRzvGeSowdJKAKyks8oUpLEd/DyPV4eMhVlhJ0aNaZqIrNUIPuEWWTAoPqyFkfGrM67MC69baqn6vA==", "requires": { "fstream": "^1.0.0", "glob": "^7.0.3", "graceful-fs": "^4.1.2", "mkdirp": "^0.5.0", "nopt": "2 || 3", "npmlog": "0 || 1 || 2 || 3 || 4", "osenv": "0", "request": "^2.87.0", "rimraf": "2", "semver": "~5.3.0", "tar": "^2.0.0", "which": "1" }, "dependencies": { "nopt": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", "requires": { "abbrev": "1" } }, "semver": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=" }, "tar": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz", "integrity": "sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE=", "requires": { "block-stream": "*", "fstream": "^1.0.2", "inherits": "2" } } }} Then I searched for the same problem so I've found this answer . Then I did npm cache verifyrm -rf node_modules/npm i -g npm npm-check-updatesncu -gncu -unpm i but the version for tar package still remains the same. I also tried updating it directly with npm install [email protected] but it just put tar in my package.json. I also tried npm update and npm outdated. Everything looks up to date.
Now provide the response and nothing else.
| The reason this is happening is because Webpack (in production mode) is putting your code through a minimiser, and the mysql module that serverless-mysql is using is not compatible with minimising. You can see the issue here: https://github.com/mysqljs/mysql/issues/1655 . It's quite a common problem with Node modules which rely on function names to do code building, as uglyifiers/minifiers attempt to obfuscate/save space by changing the names of functions to single letters. The simplest fix would be to switch off minimising in your webpack config by adding: optimization: { minimize: false } There is some discussion in the linked issue on configuring various other minimising plugins (like terser) to not mangle names, which would allow you to get some of the benefit of minimising if you need it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55988991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5184474/']} | jdg_82139 |
stackexchange | llm_judgeable_groundtruth_similarity | 1814039 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given $p: \mathbb{R} \times \mathbb{R} \to \mathbb{R}, (x,y) \mapsto x$ Why is $p$ open but not closed? Shouldn't it be the case $p$ is closed not open because it sends a singleton to singleton, and all singletons in Euclidean spaces are closed?
Now provide the response and nothing else.
| The set $F=\{(\frac{1}{n},n):n\in\mathbb{N}\}$ is a closed subset of $\mathbb{R}^2$ because it has no limit points, but its projection onto the $x$ coordinate is the set $\{\frac{1}{n}:n\in\mathbb{N}\}$, which is not closed because it doesn't contain the limit point $0$. Therefore the projection is not a closed map. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1814039', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/105951/']} | jdg_82140 |
Subsets and Splits