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
102282
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: Lets say I have following file word1 something blablaanotherword somethingelse asdfyetanother else 123 For each line, I need to put a comment infront of the second column, which always starts at position 15 (that is, to insert # at position 15). How can I do it? Now provide the response and nothing else.
Assuming GNU sed or compatible for its -r option¹ sed -r -e 's/^.{15}/&#/' file results in word1 #something blablaanotherword #somethingelse asdfyetanother #else 123 ¹ that's for extended regexp support. Most other sed s support -E for that now (including GNU sed since version 4.2 though it wasn't documented until 4.3, released long after this answer was initially written) as that's what is now in the 2023 edition of the POSIX standard. Without -E / -r , you'd use \{...\} instead of {...} .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/102282', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43007/']}
jdg_372841
stackexchange
llm_judgeable_groundtruth_similarity
117057
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I would like to monitor NGinx stats through Munin but the Nginx plugins show no data. Is it possible to diagnose why only one of the munin nginx plugins seems to be working? The server runs on CentOS 5.3 Now provide the response and nothing else.
The nginx plugins rely on the following URL to get the status info: http://127.0.0.1/nginx_status Usually, nginx does not have this URL configured to show status data. From the documentation of the plugins, I see that nginx needs to be configured to show status data in a spesific URL. You need to enable nginx status by adding the following lines to the site's configuration: server { listen 127.0.0.1; server_name localhost; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } } Don't forget to restart the server after adding this configuration, and make sure the stus URL returns the status data. For the complete documentation of each plugin, you can run: munindoc nginx_request Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/117057', 'https://serverfault.com', 'https://serverfault.com/users/28207/']}
jdg_372842
stackexchange
llm_judgeable_groundtruth_similarity
6460671
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 need to get column names and their tables in a SQLite database. What I need is a resultset with 2 columns: table_name | column_name . In MySQL, I'm able to get this information with a SQL query on database INFORMATION_SCHEMA . However the SQLite offers table sqlite_master : sqlite> create table students (id INTEGER, name TEXT);sqlite> select * from sqlite_master; table|students|students|2|CREATE TABLE students (id INTEGER, name TEXT) which results a DDL construction query ( CREATE TABLE ) which is not helpful for me and I need to parse this to get relevant information. I need to get list of tables and join them with columns or just get columns along with table name column. So PRAGMA table_info(TABLENAME) is not working for me since I don't have table name. I want to get all column metadata in the database. Is there a better way to get that information as a result set by querying database? Now provide the response and nothing else.
You've basically named the solution in your question. To get a list of tables (and views), query sqlite_master as in SELECT name, sql FROM sqlite_masterWHERE type='table'ORDER BY name; (see the SQLite FAQ ) To get information about the columns in a specific table, use PRAGMA table_info(table-name); as explained in the SQLite PRAGMA documentation . I don't know of any way to get tablename|columnname returned as the result of a single query. I don't believe SQLite supports this. Your best bet is probably to use the two methods together to return the information you're looking for - first get the list of tables using sqlite_master, then loop through them to get their columns using PRAGMA table_info().
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6460671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54929/']}
jdg_372843
stackexchange
llm_judgeable_groundtruth_similarity
376794
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 know that the fat Cantor set under the subspace topology is homeomorphic to Cantor space $\{0,1\}^{\mathbb N}$ under the product topology induced by the discrete topology on $\{0,1\}$. Call the natural homeomorphism $f$. What about the measure induced by Lebesgue measure on Cantor space via $f$? Is it the same (up to a constant) as the usual product measure, i.e. the probability measure used to describe an infinite sequence of coin tosses? A reference would be helpful. Now provide the response and nothing else.
Yes, it is. Note that the Cantor set is in fact a compact group, and the product measure $\mu$ is the Haar measure, that is, the invariant finite, regular Borel measure, which is by Haar's theorem unique up to a scaling factor. That Lebesgue measure restricted to the fat Cantor set is invariant is an easy exercise (it follows easily from the fact that the Lebesgue measure is translation invariant). It is also regular, because it is a restriction of a regular measure, so by Haar's theorem it is a scalar multiple of the product measure.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/376794', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73374/']}
jdg_372844
stackexchange
llm_judgeable_groundtruth_similarity
10268
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: After reading this question about how for-pay wifi routers identify specific devices it got me thinking about what a secure alternative might be. I know that certain research has focused on identifying devices by their browser signature and by their hardware clock skew signature . The former can be defeated by changing the browser signature, and the latter is difficult to implement and takes time to create the baseline. MAC addresses can be altered, IPs can be rotated, and cookies can be hijacked or accidentally erased (eg. in the case of the for-pay wifi router, that would be undesirable). Are there any practical alternatives to identify a specific device? Are there characteristics of hardware that are consistent, unalterable, and undeniable (eg. CPU IDs [are they even still implemented?], but TPMs perhaps?) How would you secure a for-pay wifi router to prevent others from gaining free access? Now provide the response and nothing else.
The only way to accurately identify a specific client on a network would be with cryptography. If each client had their own asymmetric key pair and you used a SSL VPN then it would be a lot easier to enforce resource usage rules. Panopticlick would never work for this. The browser signature will change because of updates or installing new plugins/languages/etc. Not only that but this value is about as easy to spoof as a MAC Address, just run Panopticlick on the victim's browser and then modify your system to match. The bottom line is that software fingerprinting is too easy to fool and is error prone. My gut feeling is that hardware fingerprinting is not the right path. What if the attacker has identical hardware? Macbooks are pretty popular these days. Again this kind of fuzzy matching is error prone and could produce false positives/false negatives.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/10268', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/6249/']}
jdg_372845
stackexchange
llm_judgeable_groundtruth_similarity
24705465
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 in trouble on setting up a MySQL RDS. From my EC2 instance I can connect fine, but from my laptop I get error 2003 (timeout). My RDS instance is configured to be publicly accessible. My security group has a rule inbound and outbound to allow all traffic everywhere (0.0.0.0/0). Should I configure something on my VPC or Internet Gateway? Now provide the response and nothing else.
As your security groups are wide open, my guess is that your LAN is blocking outbound traffic on port 3306. Infact, looking at this support page ( http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToInstance.html ) firewall issues are listed as number 2 in common reasons for being unable to connect. This question may help you out: MySql networking issue . May be worth taking a look at your local firewall settings. You mention you are on a laptop so my guess is your current network is classed as a public network and your outbound ports are being blocked (as mentioned in the question Ive linked). If that gets you nowhere, its worth telnetting to your RDS instance on port 3306 and seeing what happens. This may well give you some more debug information which could help with the general Googling around of the issue. As an aside, personally I wouldn't open up an RDS instance to the Internet directly. Its reasonably straight forward to setup an ssh tunnel to forward traffic to your RDS instance through an SSH server. Something like the stuff shown here: http://www.techrepublic.com/blog/linux-and-open-source/tips-and-tricks-to-help-you-do-more-with-openssh/ UPDATE:I've never used RDS with the 'publicly available' option (all our setups used ssh tunnelling to private RDS instances). Googling around, I came across quite a few queries in the AWS forums relating to access issues to public RDS instances. For example, https://forums.aws.amazon.com/thread.jspa?threadID=123483 . May be worth trying the suggested fix of explicitly creating entries in the route table for the subnets that compose the RDS instance?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24705465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3175226/']}
jdg_372846
stackexchange
llm_judgeable_groundtruth_similarity
84904
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Without appealing to a guess-and-check approach, how might I select a pair of random points inside of a sphere of radius $R$ s.t. the points always a distance $d \leq R$ apart? Can the selected points be 'random' in the sense that a large number of such pairs can be split into two equal-sized populations that independently appear uniformly distributed within the sphere's volume? If it simplifies matters, and I'm not sure it would, I would also be interested in the case of a cube of edge-length $R$. So that I can better understand the distribution of point pairs: Imagine I select a pair of points meeting the above separation distance criterion. If I randomly select another such pair, what is the probability that the distance between the first points in either pair is $\leq \delta_1$, and the distance between the second points in either pair is $\leq \delta_2$ for some $\delta_1,\delta_2 \leq R$? Now provide the response and nothing else.
From an algorithmic point of view, a very simple and computationally effective way to produce points is exactly the guess and check that you say you don't want. [ You don't say, but I'm assuming you're working in 3 dimensions? As the dimensionality increases, so the methods that I'm talking about become progressively worse ] Let $X$ be a randomly chosen point in the ball of radius $R$; let $Z$ be a randomly chosen point in the ball of radius 1. Then set $Y=X+dZ/|Z|$. If $Y$ lies in the sphere of radius $R$, then keep the pair $(X,Y)$; otherwise generate a new pair. This is efficient because it's simple to generate points in a ball and the expected number of attempts you have to make to get a valid pair is small (if you take a spherical shell of radius $d$ centred at a point on the boundary of a ball of radius $R$, a lower bound for the probability of success is the proportion of the shell lying inside the ball. I haven't done the calculation, but this must be large, even for $d=R$.) Since the success probability is high, you don't have to repeat too often to get a valid pair. Next notice that each pair of valid points has the same chance of being selected so that you are truly picking from the distribution you want. To answer your question about uniform distribution, you can see from the construction that the first coordinate (and hence the second coordinate also since the distribution is symmetric) is not uniformly distributed in the sphere. For example if $d$ is a lot smaller than $R$, then if you pick $X$ near the boundary of the sphere, the probability of the pair being rejected is about 50%, whereas if you pick $X$ far from the boundary then the probability of rejection is 0. This means that if you take the marginal distribution of either coordinate, it is biased towards being at the centre of the ball.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/84904', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20364/']}
jdg_372847
stackexchange
llm_judgeable_groundtruth_similarity
98357
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 am following this tutorial on how to do a firmware update to my NAND flash. I followed it only changing the directory where I am placing my new root. I am copying all of the /bin /dev /sbin /usr folders into a tmpfs that I have located in RAM . The following commands are where I start running into problems: umount /sysumount /proc If I killall5 sys unmounts without a problem but then when I try to unmount proc it gives me: umount: can't umount /proc: Device or resource busy I have tried using chroot similar to this link on a similar issue. But it doesn't seem to help much. I tried to chroot to my newroot, using the following command but it then gives me more grief: chroot /tmp/newroot /bin/ash Error: umount: can't umount /proc: Invalid argument Could someone point me in the right direction? I'm getting the feeling I'm missing something trivial, as is ussually the case. Now provide the response and nothing else.
Well, you probably don't need to unmount /proc . The procfs is not even a real filesystem , rather a representation of the contents of memory and the currently running processes. What you want is probably to bind mount it to a location inside the chroot: # mkdir -m 0555 /tmp/newroot/proc# mount --bind /proc /tmp/newroot/proc
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/98357', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/33696/']}
jdg_372848
stackexchange
llm_judgeable_groundtruth_similarity
748387
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Unfortunately an item can only be removed from the stack by "pop". The stack has no "remove" method or something similar, but I have a stack (yes I need a stack!) from which I need to remove some elements between. Is there a trick to do this? Now provide the response and nothing else.
If you need to remove items that aren't on the top, then you need something other than a stack. Try making your own implementation of a stack from a List. Then you get to implement your own push and pop functions (add & remove on the list), and your own special PopFromTheMiddle function. For example public class ItsAlmostAStack<T>{ private List<T> items = new List<T>(); public void Push(T item) { items.Add(item); } public T Pop() { if (items.Count > 0) { T temp = items[items.Count - 1]; items.RemoveAt(items.Count - 1); return temp; } else return default(T); } public void Remove(int itemAtPosition) { items.RemoveAt(itemAtPosition); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/748387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90745/']}
jdg_372849
stackexchange
llm_judgeable_groundtruth_similarity
7139103
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hope you can help a bit here...I have a form that translate a word in a field, populate the field with the translated term and then do submit action all in one submit button. the submit is being made by jquery.problem is the target page is being blocked as all 3 major browsers treat it as popup,Do you know how to let it open just as a new tab or new window ?I don't want to set the target as _self as I want people to have my site open as well. I believe the problem is in this string: document.forms.form1.submit(); but I also know there should be a way to rephrase it so the target won't be treated as a popup. this is the script: <script type="text/javascript">$(function transle() { $('#transbox').sundayMorningReset(); $('#transbox input[type=button]').click(function(evt) { $.sundayMorning( $('#transbox input[type=text]').val(), { source: '', destination: 'ZH', menuLeft: evt.pageX, menuTop: evt.pageY }, function(response) { $('#transbox input[type=text]').val(response.translation); //document.getElementById("form1").submit(); document.forms.form1.submit(); } ); });});</script> and this is the form: <table id="transbox" name="transbox" width="30px" border="0" cellspacing="0" cellpadding="0"> <form action="custom-page" method="get" name="form1" target="_blank" id="form1"> <tr> <td> <input id="q" name="q" type="text" class="search_input" onFocus="if (this.value == 'Evening dress') {this.value = '';}" onBlur="if (this.value == '') {this.value = 'Evening dress';}" value="Evening dress" /> </td> <td> <input type="button" value="Find" style="color: #333; width: 157px; font-weight:bold"></input> </td> </tr> </form></table> EDIT I have tried all of these strings to submit: document.getElementById("form1").submit();document.forms.form1.submit();form1.submit(); all ends up with the target being popup blocked.please, is there any other way I should do the code to not let it popup ? maybe should use the onsubmit to make jQuery ?someone knows how ? Now provide the response and nothing else.
A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event . That means the user has to actively click somewhere to open a popup. In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context. In jQuery this should do the trick: $.ajax({ url: 'http://yourserver/', data: 'your image', success: function(){window.open(someUrl);}, async: false}); Here is your answer: Open new tab without popup blocker after ajax call on user click
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7139103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/904456/']}
jdg_372850
stackexchange
llm_judgeable_groundtruth_similarity
31681
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In this question about countries boycotting the World Cup , it was pointed out in several answers, quite correctly, that the national football leagues in question aren’t government agencies and the government doesn’t directly control them, making it somewhat difficult for the government to actually be in charge of whether or not the country boycotts the event. However, those national leagues will play as “Team Country Name,” the official representatives of that country, at the World Cup, and it seems to me that the government of those countries might (but also might not) have some say over how the country’s name is used and who can or cannot claim to represent the country. I’m reminded of similar logic used (I’ve been told) by the emperor of Korea when giving his first televised address regarding the poor safety record of Korean Airlines. As I understand it, he noted that Korean Airlines was a private company, but since they were using the country’s name and in a sense representing the country on the international stage—and representing it poorly by its then-terrible safety record—he felt it was appropriate for him to comment on what was going on and express his dissatisfaction. Obviously, that was very much not a Western democracy, but similar logic might still apply. So do Western democracies tend to assert any kind of rights towards the country’s name and who can and cannot claim to represent the country? Could they tell the national football league that they can go to the World Cup if they like, but they can’t claim to be the official team from that country and must play under some other name? Or can any private citizens of that country use the country’s name as they see fit, and any group of them claim to represent that country for some particular event? I realize that this is fairly broad, since it isn’t focused on any particular country, but I’m looking for an answer that’s more of political philosophy than it is particular laws—though examples to illustrate the philosophy, or differences in philosophy, would be ideal as well. Now provide the response and nothing else.
What governments can do (supposedly) and what they do are two different issues. Technically, FIFA is an independent, private association and governments of the world don't have a say in their decisions. In the practice, however, FIFA can be subjected to many kinds of pressure that make sure they kowtow to the will of the states. The more powerful the state, the easier to subdue FIFA. In Spain, for example, the "Ley del Deporte" (Law of Sports) determines that the national Spanish federations are the only ones allowed to participate or represent Spain in international tournaments. That's to prevent the long-sustained ambition of Catalonia (mainly) and the Basque Country to have their own teams competing in international tournaments just like Scotland and Wales are allowed to do in the United Kingdom. Since many Catalan sport federations were founded before there was a Spanish federation of the same sport, Catalonia was able to register for many international sport associations. Spain then successfully forced them to merge with the Spanish federations and substituted them in international matches. Currently there are only 20 Catalan sport federations which can compete internationally, all of them in minority sports. If quidditch ever becomes a hugely popular sport, be sure Spain will have its way to prevent the Catalan national team from competing.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/31681', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/1608/']}
jdg_372851
stackexchange
llm_judgeable_groundtruth_similarity
45477583
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 want to add more components after clicking on the button. Can you share code or an idea so that I can implement? As the image shows, every time when user click on the add button, one row / component will be added. Now provide the response and nothing else.
It's where state shining of, for example: constructor(props) { super(props); this._handleAddButton = this._handleAddButton.bind(this); this.state = { /* initial your state. without any added component */ data: [] }}_handleAddButton() { let newly_added_data = { title: 'new title', content: 'new content goes here' }; this.setState({ data: [...this.state.data, newly_added_data] });}render() { let added_buttons_goes_here = this.state.data.map( (data, index) => { return ( <MyComponent key={index} pass_in_data={data} /> ) }); return ( <View> <Button title="Add more" onPress={this._handleAddButton} /> {added_buttons_goes_here} </View> );} So every time you click the button, _handleAddButton get called a new data is added, update with setState() render() get triggered. more <MyComponent> added into View and show ================ 2017/8/3 edited: if you want to further delete <MyComponent> , the prop key should be taken care of. The key act as change detector for react framework, an auto-increment key would suit your case. example: _handleAddButton() { let newly_added_data = { /* psedo code to simulate key auto increment */ key: this.state.data[this.state.data.length-1].key+1, title: 'new title', content: 'new content goes here' }; this.setState({ data: [...this.state.data, newly_added_data] });}_handleRemoveButton(key) { let result = this.state.data.filter( (data) => data.key !== key ); this.setState({ data: result, });}render() { let added_buttons_goes_here = this.state.data.map( (data, index) => { return ( <MyComponent key={data.key} pass_in_data={data}> /// psedo code of pass-in remove button as a children <Button title="Remove" onPress={ () => this._handleRemoveButton(data.key) } /> </MyComponent> ) }); return ( <View> <Button title="Add more" onPress={this._handleAddButton} /> {added_buttons_goes_here} </View> );}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45477583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2530594/']}
jdg_372852
stackexchange
llm_judgeable_groundtruth_similarity
60301010
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Good day, My team and I are trying to push our Rails app to Heroku - git push heroku dev:master is successful, but thereafter heroku run rails db:migrate , heroku run rails console , etc. all fail with the following error (full trace pasted at bottom of post): NoMethodError: undefined method `map' for nil:NilClass /app/vendor/bundle/ruby/2.4.0/gems/warden-jwt_auth-0.3.6/lib/warden/jwt_auth.rb:89:in `upcase_first_items' I tracked down the failing method upcase_first_items in the files of the gem jwt_auth , but remain unable to solve this. Searching the error on Google (including iterations of the error) turns up 0 results. We successfully pushed this app to Heroku two weeks ago, and have not since changed anything with regards to authentication (which I've made sure of by reviewing all our commits from the last 2 weeks). Any ideas? Thanks,Michael Full trace: [cocomio-languages (dev)]$ heroku run rails db:migrate --traceRunning rails db:migrate --trace on ⬢ coco-sprint-3... up, run.2956 (Hobby)** Invoke db:migrate (first_time)** Invoke db:load_config (first_time)** Invoke environment (first_time)** Execute environmentrails aborted!NoMethodError: undefined method `map' for nil:NilClass/app/vendor/bundle/ruby/2.4.0/gems/warden-jwt_auth-0.3.6/lib/warden/jwt_auth.rb:89:in `upcase_first_items'/app/vendor/bundle/ruby/2.4.0/gems/warden-jwt_auth-0.3.6/lib/warden/jwt_auth.rb:50:in `block in <module:JWTAuth>'/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/setting.rb:119:in `evaluate'/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/setting.rb:70:in `value'/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/config.rb:111:in `method_missing'/app/vendor/bundle/ruby/2.4.0/gems/devise-jwt-0.5.9/lib/devise/jwt/railtie.rb:19:in `block (3 levels) in <class:Railtie>'/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/methods.rb:15:in `configure'/app/vendor/bundle/ruby/2.4.0/gems/devise-jwt-0.5.9/lib/devise/jwt/railtie.rb:15:in `block (2 levels) in <class:Railtie>'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:69:in `block in execute_hook'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:62:in `with_execution_control'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:67:in `execute_hook'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:52:in `block in run_load_hooks'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:51:in `each'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:51:in `run_load_hooks'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application/finisher.rb:75:in `block in <module:Finisher>'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:32:in `instance_exec'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:32:in `run'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:61:in `block in run_initializers'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:347:in `each'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:347:in `call'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:60:in `run_initializers'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application.rb:361:in `initialize!'/app/config/environment.rb:5:in `<main>'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require_with_bootsnap_lfi'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `block in require'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:257:in `load_dependency'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `require'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application.rb:337:in `require_environment!'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application.rb:520:in `block in run_tasks_blocks'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:281:in `block in execute'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:281:in `each'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:281:in `execute'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:219:in `block in invoke_with_call_chain'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:199:in `invoke_with_call_chain'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:243:in `block in invoke_prerequisites'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `each'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `invoke_prerequisites'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:218:in `block in invoke_with_call_chain'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:199:in `invoke_with_call_chain'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:243:in `block in invoke_prerequisites'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `each'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `invoke_prerequisites'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:218:in `block in invoke_with_call_chain'/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:199:in `invoke_with_call_chain'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:188:in `invoke'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:160:in `invoke_task'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:116:in `block (2 levels) in top_level'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:116:in `each'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:116:in `block in top_level'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:125:in `run_with_threads'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:110:in `top_level'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/commands/rake/rake_command.rb:23:in `block in perform'/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:186:in `standard_exception_handling'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/commands/rake/rake_command.rb:20:in `perform'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/command.rb:48:in `invoke'/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/commands.rb:18:in `<main>'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require_with_bootsnap_lfi'/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `block in require'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:257:in `load_dependency'/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `require'/app/bin/rails:4:in `<main>'Tasks: TOP => db:migrate => db:load_config => environment Update 1 I reverted to each commit from the previous two weeks (i.e. between now and the last working deploy), and deployed, but received the same error. I reached commits from even before the last deploy (the deploy that was working), and still have the same error, which leads me to believe it has nothing to do with our commits from the last few weeks. When I went to the Heroku dashboard and reverted the build to the deploy from two weeks ago, the Rails commands (heroku run rails c, heroku run rails db:migrate, etc.) once again work. Now provide the response and nothing else.
With the version 0.8.0 of devise-jwt it's no longer a problem. Please see the breaking change in version 0.7.0 , when upgrading. Previous answer Probably someone or something upgraded the dry-configurable gem from version 0.9.0 to 0.11.1 . This gem is a dependency of warden-jwt_auth which is a dependency of devise-jwt and the new version breaks it. A few days ago the version 0.11.0 of dry-configurable was released and warden-jwt_auth uses it, because it specifies the version of this dependency with ~> 0.6 , which includes the faulty version (everything from 0.6 to 1.0 would be fine). You can see that in the Gemfile.lock or in the dependencies of warden-jwt_auth . If somebody did run bundle upgrade it will have pulled the new faulty version. I recommend you to pin the older version of dry-configurable in your Gemfile : gem 'dry-configurable', '0.9.0' Then run bundle update and deploy again.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60301010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7336499/']}
jdg_372853
stackexchange
llm_judgeable_groundtruth_similarity
2872437
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've been trying to speed up an algorithm where the most expensive operation is the square-root. However, I can often guarantee that the input value is a perfect-square. I'm curious to know if there are any algorithms that will find the square-root faster (constant time?) if it is known that the input is a perfect-square? Thanks,Ryan Now provide the response and nothing else.
The sum of the first $k$ odd numbers is $k^2$. Knowing this, you can you calculate the square root by summing successive odd numbers (starting from one)—once you reach the input value, return the number of summations you made. For example, $16 = 1 + 3 + 5 + 7$; that's $4$ addends, so $\sqrt{16}=4$. This process will always work, since our input is guaranteed to be of the form $k^2$ with $k \in \mathbb N$. I think this method would run in $O(\sqrt n)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2872437', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/494652/']}
jdg_372854
stackexchange
llm_judgeable_groundtruth_similarity
31944501
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 tried to change the color of my drawable inside my row depending on a value but instead of one drawable the adapter changed all of them. Here is my Adapter: public class ReportAdapter extends RecyclerView.Adapter<ReportAdapter.ReportViewHolder> { DataBaseHelper dataBase; private LayoutInflater inflater; List<ChoosedSubject> data = Collections.emptyList(); Context context; OnItemClickListener itemClickListener; public ReportAdapter(Context context, List<ChoosedSubject> data, OnItemClickListener itemClickListener) { inflater = LayoutInflater.from(context); this.data = data; this.context = context; this.itemClickListener = itemClickListener; } @Override public ReportViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.report_cell, parent, false); ReportViewHolder holder = new ReportViewHolder(view); dataBase = new DataBaseHelper(context); return holder; } //Set Data inside RecyclerView @Override public void onBindViewHolder(ReportViewHolder holder, int position) { ChoosedSubject current = data.get(position); Grades grades = new Grades(context); Resources resources = context.getResources(); int iconColor; Drawable icon; icon = ContextCompat.getDrawable(context, dataBase.getSpecificChoosedSubjectAppendingToName(current.getName()).get(0).getChoosedIcon()); if (dataBase.getSpecificChoosedSubjectAppendingToName(current.getName()).get(0).getChoosedIcon() != R.drawable.subject_default) { iconColor = resources.getColor(dataBase.getSpecificChoosedSubjectAppendingToName(current.getName()).get(0).getChoosedColor()); icon.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN); holder.icon.setBackground(icon); } else { holder.icon.setImageResource(R.drawable.subject_default); } holder.subject.setText(current.getName().toString()); NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(0); formatter.setMaximumFractionDigits(0); String output = formatter.format(dataBase.getSpecificChoosedSubjectAppendingToName(current.getName()).get(0).getAverage()); int formattedValue = Integer.valueOf(output); //CHANGING COLOR DEPENDING ON VALUE int boxColor = 0; Drawable box = ContextCompat.getDrawable(context, R.drawable.markbox); Drawable boxBorder = ContextCompat.getDrawable(context, R.drawable.markbox_border); if (formattedValue >= 10) { boxColor = resources.getColor(R.color.positive); } else if (formattedValue >= 4 && formattedValue <= 9) { boxColor = resources.getColor(R.color.neutral); } else if (formattedValue < 4) { boxColor = resources.getColor(R.color.negative); } box.setAlpha(204); box.setColorFilter(boxColor, PorterDuff.Mode.SRC_IN); boxBorder.setColorFilter(boxColor, PorterDuff.Mode.SRC_IN); holder.markbox.setImageDrawable(box); holder.markboxBorder.setImageDrawable(boxBorder); holder.average.setText(output); holder.average.setTypeface(EasyFonts.robotoBlack(context)); } @Override public int getItemCount() { return data.size(); } public class ReportViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView subject; ImageView icon; ImageView markbox; ImageView markboxBorder; TextView average; public ReportViewHolder(View itemView) { super(itemView); subject = (TextView) itemView.findViewById(R.id.report_subject); icon = (ImageView) itemView.findViewById(R.id.report_icon); markbox = (ImageView) itemView.findViewById(R.id.report_markbox); markboxBorder = (ImageView) itemView.findViewById(R.id.report_markbox_border); average = (TextView) itemView.findViewById(R.id.report_average); itemView.setOnClickListener(this); } @Override public void onClick(View v) { itemClickListener.onItemClick(v, this.getAdapterPosition()); } }} Knows anybody what to do? Thank you for your help!!! Now provide the response and nothing else.
It's sort of caching. From the Android docs : if you instantiate two Drawable objects from the same image resource, then change a property (such as the alpha) for one of the Drawables, then it will also affect the other. So when dealing with multiple instances of an image resource, instead of directly transforming the Drawable, you should perform a tween animation. Drawable.mutate() after creating should fix the issue. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Something like this: Drawable box = ContextCompat.getDrawable(context, R.drawable.markbox).mutate();Drawable boxBorder = ContextCompat.getDrawable(context, R.drawable.markbox_border).mutate();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31944501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4051366/']}
jdg_372855
stackexchange
llm_judgeable_groundtruth_similarity
21269793
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 lm object and want to get the formula extracted with coefficients. I know how to extract the formula without coefficients, and how to get the coefficients without the formula, but not how to get eg. y ~ 10 + 1.25b as opposed to y~b or a table of what intercept, b etc. equal This is the code I'm working with currently: a = c(1, 2, 5)b = c(12, 15, 20)model = lm(a~b)summary(model)formula = formula(model)formulacoefficients(model) What I'd like to get from the above is y ~ -5.326 + .51b Thanks Edit: In my actual code I'm working with over 63 predictors and 18 different models, so I'd like something that can scale up without too much work. Now provide the response and nothing else.
as.formula( paste0("y ~ ", round(coefficients(model)[1],2), " + ", paste(sprintf("%.2f * %s", coefficients(model)[-1], names(coefficients(model)[-1])), collapse=" + ") ))# y ~ -5.33 + 0.51 * b
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21269793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3051065/']}
jdg_372856
stackexchange
llm_judgeable_groundtruth_similarity
4268139
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 there a more efficient way than: select * from transactions partition( partition1 ) union all select * from transactions partition( partition2 ) union all select * from transactions partition( partition3 ); Now provide the response and nothing else.
It should be exceptionally rare that you use the PARTITION( partitionN ) syntax in a query. You would normally just want to specify values for the partition key and allow Oracle to perform partition elimination. If your table is partitioned daily based on TRANSACTION_DATE, for example SELECT * FROM transactions WHERE transaction_date IN (date '2010-11-22', date '2010-11-23', date '2010-11-24') would select all the data from today's partition, yesterday's partition, and the day before's partition.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4268139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241449/']}
jdg_372857
stackexchange
llm_judgeable_groundtruth_similarity
12284719
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 used join in linq to join 2 tables. What is the difference between a join and Include. From what I see, they both behave the same. Include vs. Join Now provide the response and nothing else.
An Included is intended to retain the original object structures and graphs. A Join is needed to project a flattened representation of the object graph or to join types which are not naturally related through the graph (ie. join the customer's city with a shipping facility's city). Compare the following: db.Customers.Include("Orders") Generates an IEnumerable each of which may contain their corresponding list of Orders in an object graph like this: Customer 1 Order Order OrderCustomer 2 Order Order In contrast, if you do the same with a join projecting into an anonymous type you could get the following: from c in db.Customers join o in db.Orders on c.CustomerId equals o.CustomerId select new {c, o} This produces a new IEnumerable<Anonymous<Customer, Order>> where the customer is repeated for each order. { Customer1, orderA }{ Customer1, orderB }{ Customer1, orderC }{ Customer2, orderD }{ Customer2, orderE }{ Customer2, orderF } While both may issue the same request to the database, the resulting type may be quite different.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12284719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/996431/']}
jdg_372858
stackexchange
llm_judgeable_groundtruth_similarity
9516224
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 RESTful service that consumes and produces JSON objects, and I would like Jersey to use Gson instead of Jackson. How can this be done...? Now provide the response and nothing else.
You need to write custom implementations of MessageBodyReader and MessageBodyWriter (possibly in the same class) and register with Jersey (if you use package scanning, the @Provider annotation is enough) -- pretty much like JacksonJsonProvider does it: @Provider@Consumes({MediaType.APPLICATION_JSON, "text/json"})@Produces({MediaType.APPLICATION_JSON, "text/json"})class GsonJsonProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> { ...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9516224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/922340/']}
jdg_372859
stackexchange
llm_judgeable_groundtruth_similarity
17783909
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 Gson to serialize/deserialize java objects to json. I want to display it in UI , and needs a schema to make a better description. This will allow me to edit objects and add more data than there actually is. Can Gson provide json schema? Does any other framework has that capability? Now provide the response and nothing else.
Gson library probably does not contain any feature like that but you can try to solve your problem with Jackson library and jackson-module-jsonSchema module. For example, for below classes: class Entity { private Long id; private List<Profile> profiles; // getters/setters}class Profile { private String name; private String value; // getters / setters} this program: import java.io.IOException;import java.util.List;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.module.jsonSchema.JsonSchema;import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;public class JacksonProgram { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); mapper.acceptJsonFormatVisitor(Entity.class, visitor); JsonSchema schema = visitor.finalSchema(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema)); }} Prints below schema: { "type" : "object", "properties" : { "id" : { "type" : "integer" }, "profiles" : { "type" : "array", "items" : { "type" : "object", "properties" : { "name" : { "type" : "string" }, "value" : { "type" : "string" } } } } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17783909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411965/']}
jdg_372860
stackexchange
llm_judgeable_groundtruth_similarity
1065759
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 to replace the Mac OS X login window, /System/Library/CoreServices/loginwindow.app, with a custom login window application? ( See my rational for doing so .) I'm afraid my Cocoa programming skills are rudimentary. I do find it interesting that, when I run probe CGSession (which is a undocumented utility that performs fast user switching) to see what functions it uses, by doing nm -mg /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession that one of the linked function is: (undefined [lazy bound]) external _CGSCreateLoginSession (from ApplicationServices) I haven't found documentation on the ApplicationServices framework. I suspect I'm getting deep into Service Provider Interfaces instead of Application Programmer Interfaces. I did find this really interesting snippet: ( google cache ) ( direct link to down page ; it appears the site is undergoing re-organization) from an application that claims to switch to the login window even if fast user switching is disabled. #include "CGSInternal.h"int main (int argc, const char * argv[]) { // switch to the login window CGSCreateLoginSession(NULL); return 0;} I take CG to mean CoreGraphics, and don't understand what that has to do with logging in (except with perhaps putting a login dialog up over the current user's work). Even if it is not possible to achieve a replacement for the login window, I'd be interested to know what can be done along these lines (by people who don't work for Apple). Now provide the response and nothing else.
The login window application is defined as part of the launchd configuration in /System/Library/LaunchDaemons/com.apple.loginwindow.plist . In theory you can replace the login window with your own but I don't know what you have to do in the new app - I think the login window does a bit more then authentication and setting up the user session -> amongst others, it looks like its doing some launchd related chores. I've compiled an application that calls CGSCreateLoginSession and once you run it it transitions to the login window via the rotating cube. I imagine this is why it requires CoreGraphics - it's just a graphics function that calls logout at the end. You could try an InputManager and see it the login window loads the code -> if it does, you could then alter the loginwindow NIB ( LoginWindowUI.nib ) and add some buttons to display a new window with the user browser. Once the student chooses a picture of him/herself you could autofill the username and password fields in the loginwindow. Node this is all theory, and it looks very fragile and unsafe. Good luck. Later edit Please note this is very unsafe so use with care - I did hose my system a couple of times when trying out this stuff Here's a proof-of-concept implementation that injects code in the loginwindow. #include <stdio.h>#include <unistd.h>#include <sys/time.h>#include <strings.h>#include <syslog.h>#import <Cocoa/Cocoa.h>#include <execinfo.h>@interface LLApp:NSApplication@end@implementation LLApp- (void)run{ syslog(LOG_ERR, "LLApp being run"); [super run];}@endvoid my_openlog(const char *ident, int logopt, int facility);typedef struct interpose_s { void * new_func; void * orig_func;} interpose_t;int MyNSApplicationMain(int argc, const char ** argv);static const interpose_t interposers[] __attribute__ ((section("__DATA, __interpose"))) = {{ (void *) my_openlog, (void *) openlog },};void my_openlog(const char *ident, int logopt, int facility){ openlog(ident, logopt, facility); if(!strcmp(ident, "/System/Library/CoreServices/loginwindow.app/Contents/MacOS/loginwindow")) { [LLApp poseAsClass:[NSApplication class]]; } else { syslog(LOG_ERR, "Ignoring unknown indent: >%s<", ident); } return;} The code compiles with: gcc -Wall -dynamiclib -undefined dynamic_lookup -o ~/Desktop/libinterposers.dylib testin.m -framework Cocoa Code loading is based on interposing so the launchd definition of loginwindow has to contain an additional entry (to enable interposing in the dynamic linker), i.e.: <key>EnvironmentVariables</key><dict> <key>DYLD_INSERT_LIBRARIES</key> <string>path_to/Desktop/libinterposers.dylib</string></dict>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1065759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74817/']}
jdg_372861
stackexchange
llm_judgeable_groundtruth_similarity
28642
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I give you an undirected graph with weighted edges, and tell you that each node corresponds to a point in 3d space. Whenever there's an edge between two nodes, the weight of the edge is the distance between the points. Your goal is to reconstruct the relative positions of the points, given only the available distances (represented by the edge weights). For example, if I gave you $d_{0,1} = d_{0,2} = d_{0,3} = d_{1,2} = d_{1,3} = d_{2,3} = 1$ , then you know the points are the vertices of a tetrahedron. You don't know where it is relative to the origin, or its orientation, or if it's been mirrored, but you can tell it's a tetrahedron. In general, the problem is easy if I give you all of the edge lengths. Just arbitrarily pick a point $p_0$ to be at $(0,0,0)$ , then pick a neighboring point $p_1$ and place it at $(d_{0,1},0,0)$ , then a common neighbor $p_2$ gets triangulated onto the XY plane, then a final common neighbor $p_3$ gets triangulated into the half-space $z > 0$ and breaks the remaining symmetry (assuming you didn't pick degenerate points). You can use those four points to triangulate all the remaining ones. On the other hand, when some edge lengths are missing it may not be possible to recover the embedding. For example, if there's a vertex that disconnects the graph when cut, then the two components it would separate if removed can swing around relative to each other. Which raises the questions: How expensive is it to find a solution? How do you determine if a solution is unique, up to translation/rotation/mirroring? Is 3-connectedness sufficient? Necessary? What sorts of conditions make the problem trivial? If I don't promise the edge weights actually correspond to point distances in 3d, how expensive is it to determine if an embedding is possible at all? Now provide the response and nothing else.
The problem is NP-Complete . The positions of the points is a good certificate, so it's in NP, and you can encode circuits into the "is there a satisfying set of points?" problem. Reduction from Circuit Evaluation to Distance Embedding We're going to reduce circuit evaluation into a distance embedding problem by creating a coordinate system, putting logical bits in it, wiring bits to be equal, and creating widgets for NOT and AND gates. Coordinates . We need some kind of coordinate system that we can position points with. Do this by creating a "base" tetrahedron of points. Add four points all declared to be a distance of $1$ from each other. This forces the shape of those four points into a tetrahedron. We can position other points relative to our tetrahedron coordinate system by specifying their distance to each of the four corners of the base. The tetrahedron can be translated and rotated and reflected, but the same thing will happen to all the other points as well. Bits . To make a bit, we position a triangle of points relative to the base tetrahedron. The triangle's normal must point upward along the Z axis, so that the triangle is parallel to the XY plane (in tetrahedron coordinates). Also its edges must have length $1$. With that done, we add a "value" point $v$, specified to be a distance of $1$ from the other three. We don't connect $v$ to the base coordinate system. This gives it two possible positions: centered $\frac{1}{\sqrt{3}}$ above or below the triangle, as the final corner of a tetrahedron. The bit is ON if the point is above the triangle, and OFF if it's below. Wires . We can force two bits to be equal by saying the distance between their value points is equal to the distance between the centers of their triangles. There is one exception: when the top or bottom corner of one of the bits exactly lines up with the center plane of the other. In that case we first use a wire to move one of the bits vertically. NOT . We can get the negation of a bit by adding a second value point $w$ to the same triangle, but requiring that $w$ be a distance of $\frac{2}{\sqrt{3}}$ from $v$. This forces $w$ to take the position opposite of $v$, with respect to the triangle, giving us a bit with the opposite value. IMPLIES . The equidistant issue we had to work around with the wires is actually quite useful. When the bits line up in that way, which we can force with a vertical wire, the higher one implies the lower one. If the higher one is true, only the top of the lower one is the right distance away. If the higher one is false, both the top and bottom are the right distance away. AND . To make a bit $C$ be equal to $A$ AND $B$, we need two implications and a widget to force equality when $A$ and $B$ agree. The implications are just $C \implies A$ and $C \implies B$. To make the widget we move $A$ and $B$ vertically so they're on the same level and a distance $\frac{2}{\sqrt 3}$ apart, then we move $C$ to be equidistant between them. We then add a points $S_A$ and $S_B$ a distance $\frac{\sqrt 2 - 1}{2 \sqrt 3}$ from $A$ and $B$'s value points respectively, and force the distance between $S_A$ and $S_B$ to be $\frac{\sqrt 2 + 1}{\sqrt 3}$. We also add a point $S_C$ a distance $\frac{\sqrt 2 + 1}{2 \sqrt 3}$ from both $S_A$ and $S_B$. This creates a chain between $A$ and $B$'s value points, with $S_C$ at the chain's center. When $A \neq B$, the chain is stretched to the limit and $S_C$ is in the center of $C$'s triangle. When $A = B$ the chains links are forced to go in exact opposite directions, pushing it to the limit and placing $S_C$ on $C$'s value point equal to $A$. To force $C$'s value point, we insert a point $S_D$ a distance $\frac{1}{2 \sqrt 3}$ from both $S_C$ and $C$'s value point. This doesn't constrain $C$'s value point when $A \neq B$, but forces $A=B=C$ when $A=B$. With those elements, you can encode any circuit into a distance embedding. The inputs become bits, gates get decomposed into NOTs and ANDs introducing new bits as necessary, and that's it. Force the position of the output to be true, and you get your satisfiability problem.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/28642', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/535/']}
jdg_372862
stackexchange
llm_judgeable_groundtruth_similarity
240178
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 list of lists: xs = [[1] * 4] * 3# xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] Then, I changed one of the innermost values: xs[0][0] = 5# xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] Why did every first element of each sublist change to 5 ? Now provide the response and nothing else.
When you write [x]*3 you get, essentially, the list [x, x, x] . That is, a list with 3 references to the same x . When you then modify this single x it is visible via all three references to it: x = [1] * 4xs = [x] * 3print(f"id(x): {id(x)}")# id(x): 140560897920048print( f"id(xs[0]): {id(xs[0])}\n" f"id(xs[1]): {id(xs[1])}\n" f"id(xs[2]): {id(xs[2])}")# id(xs[0]): 140560897920048# id(xs[1]): 140560897920048# id(xs[2]): 140560897920048x[0] = 42print(f"x: {x}")# x: [42, 1, 1, 1]print(f"xs: {xs}")# xs: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]] To fix it, you need to make sure that you create a new list at each position. One way to do it is [[1]*4 for _ in range(3)] which will reevaluate [1]*4 each time instead of evaluating it once and making 3 references to 1 list. You might wonder why * can't make independent objects the way the list comprehension does. That's because the multiplication operator * operates on objects, without seeing expressions. When you use * to multiply [[1] * 4] by 3, * only sees the 1-element list [[1] * 4] evaluates to, not the [[1] * 4 expression text. * has no idea how to make copies of that element, no idea how to reevaluate [[1] * 4] , and no idea you even want copies, and in general, there might not even be a way to copy the element. The only option * has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions. In contrast, a list comprehension reevaluates the element expression on every iteration. [[1] * 4 for n in range(3)] reevaluates [1] * 4 every time for the same reason [x**2 for x in range(3)] reevaluates x**2 every time. Every evaluation of [1] * 4 generates a new list, so the list comprehension does what you wanted. Incidentally, [1] * 4 also doesn't copy the elements of [1] , but that doesn't matter, since integers are immutable. You can't do something like 1.value = 2 and turn a 1 into a 2.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/240178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11677/']}
jdg_372863
stackexchange
llm_judgeable_groundtruth_similarity
3677622
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 table that looks like the following. <tr> <td>Link Name</td> <td><a href="#" class="edit">Edit</a></td></tr> At the bottom of the table I have the following. <tr> <form class="hidden create"> <h3>Add Link</h3> ... <input type="hidden" name="form_id" value="{menu-id}" /> </form></tr> To avoid a massive page of HTML I thought it would be cool if jquery could copy the create form, tweak a few attributes then make it appear after the links row. The only query really is how.. So here are my questions. 1) How do I grab the create form and save it as variable with jquery? 2) How do I edit the hidden field? I know how to change attributes but how do I select the field it once the form is within a variable? 3) How do I paste this form into my table after the edit link on its own row? I need something like parent-parent-after? Thanks loads Now provide the response and nothing else.
1) Place a copy of the form in a variable: var create_form = $('form.create').clone(); 2) Get the hidden input from the variable: create_form.find(':hidden[name=form_id]').doSomething()... 3) Place form after .edit link in the same row (I assume this is in an event handler): $(this).closest('tr').find('a.edit').after( create_form );
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3677622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244681/']}
jdg_372864
stackexchange
llm_judgeable_groundtruth_similarity
32537339
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 that I have found an element by its XPath using: WebElement we = driver.findElement(By.xpath("some XPath")); I know that I can get the value of a particular CSS property by we.getCssValue("some property") , but can I get the values of all the properties without having to mention their names explicitly? Now provide the response and nothing else.
Unfortunately this is not possible with native Selenium API. But using Javascript you can: You can use some javascript support, using Seleniums' JavascriptExecutor.executeScript functionality. The necessary js code can be found here and here (as proposed by @Mahsum Akbas) Now here is the Java/Selenium Code that will return you a string in the form of "css-attribute01:value01; css-attribute02:value02;". Be aware that this will return ALL css-attributes on the element. WebElement we = driver.findElement(By.tagName("div"));JavascriptExecutor executor = (JavascriptExecutor)driver;String script = "var s = '';" + "var o = getComputedStyle(arguments[0]);" + "for(var i = 0; i < o.length; i++){" + "s+=o[i] + ':' + o.getPropertyValue(o[i])+';';}" + "return s;";System.out.println(executor.executeScript(script, we)); You can change the script according to your needs. For example you could return a string that ONLY has all the values without the attributes. Feel free to change and experiment. Update If you would be interested in only the inline-styles of the element, then you can use "native" Selenium as pointed out by @JeffC in the comments: driver.findElement(By.tagName("div")).getAttribute("style") BUT!: This will give you only the "inline styles" and NOT all the css-styles that are applied to an element. If you run both versions after one another and print the results you will see the immense difference.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32537339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1096315/']}
jdg_372865
stackexchange
llm_judgeable_groundtruth_similarity
15757
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to write a simple file shredder in c++, i.e. a program that deletes a file so that it is not recoverable. Would the following be a secure and correct way to do that? (1) Open the file with ofstream myfile;myfile.open ("deleteme.txt", ios::out | ios::binary); (2) Then run through 10 rounds of something like unsigned int x = 0;for (int i =0; i <= filesize -1; i++) { myfile.seekg (i, ios::beg); myfile << (char)x; [put new random character in x] } (3) Then simply delete the file if( remove( "deleteme.txt" ) != 0 ) { cout << "Error deleting file"; } else {cout << "File successfully deleted"; } (I guess one could simply also just delete the file in a console.) Would it add extra security to rename the file before deletion? Is there anything else that should be done to completely remove a file so that it cannot recovered or is this enough? EDIT1 : Just to clarify, the above code is sime-pseudo. My main concern is if overwriting a file byte by byte and the deleting the file will be a good way to make it irrecoverable. EDIT2 : I am just interested in the best way to do this by using software alone. Edit3 : Adding one more thing: I am mostly interested in a level of security that prevents recovery by methods of software. Now provide the response and nothing else.
Sounds like a fun project. I know you said "simple," but here are my thoughts anyway. The data you're writing the file over with isn't random, and one pass will still leave traces of the original data. It depends on the storage medium. For example, with magnetic devices, there's magnetic force microscopy . Even after ten rounds of the same thing, I'm not sure you're adding any extra benefits. Renaming and deleting files won't add robust protection because, on most file systems, it simply changes the pointer to the location on the disk where the data is. Deleting a file only removes the pointer, so the disk sees the blocks as "available" even though the file is actually there. (This is why recovery software works.) Thorough, secure deletes have the following features (software-based, not considering hardware solutions): PRNG ( Pseudorandom number generator ) which generates random values to write at every byte of the file's allocated space (also see the encryption feature below). Multiple passes (careful here, depends on the medium) A run with all 0s then all 1s couldn't hurt, either. It may help interrupt a predictable, yet subtle, pattern of randomness (because computers aren't truly random). Some file systems are "Copy-on-write", which is like a type of "revision control." These try to avoid overwriting data already in place. That protection would have to be circumvented. RAID devices mirror changes to a disk onto another disk. Fragmented files may start at one sector and finish at an entirely other part of the disk. Alternatively, anti-fragmentation features may keep redundant copies of the data or relocate them in real time. Solid-state drives manage the disk space differently than magnetic drives. Coupled with wear-leveling, there are technical reasons that make secure wiping a little tricky. (See Wikipedia link below) Encrypting a file before wiping it will help fill it with "random" bits... but really the best answer to secure shredding is to encrypt it before it ever hits the disk. Don't miss this great question which talks about wiping info on solid-state drives, particularly flash drives. Remember that SSDs wear out after being written enough times. Look at this article on Wikipedia for some more detailed background info. By the way... I'd really like to see a shredder that grants some plausible deniability. It would securely erase the file, then plop remnants of a decoy file in its place, perhaps a file chosen by the user that exists elsewhere on the hard drive. It would appear to be the remnants of a copy of that file which at one time was pointed to by the file system, was deleted by the user, and, depending on the size, was potentially being gradually overwritten by regular use. If a forensics agent were to examine the portion of a disk where a regular shredder was run, it's easy to tell that it was wiped with random data. But if a decoy file was put in its place, I imagine it would be harder to tell.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/15757', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/10435/']}
jdg_372866
stackexchange
llm_judgeable_groundtruth_similarity
50507382
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 the best practice way to store a connection string in appsettings.json in a .net Core 2 MVC app (like you do in web.config in MVC 5). I want to use Dapper not EF (I found many EF examples). Something like this: { "ConnectionStrings": { "myDatabase": "Server=.;Database=myDatabase;Trusted_Connection=true;" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }} Surely there are many examples online? Nothing I can find that is for .net core 2.0. Several things have changed between 1 and 2 and I want to ensure I'm using version 2 best practices. I've found this - but it seems to be .net core 1: Visual Studio 2017 - MVC Core - Part 05 - Connection String from appsettings.json This uses key value pair appsettings - not the connectionstrings: Read AppSettings in ASP.NET Core 2.0 Again it's unclear if this is .net Core 1 or 2: Net Core Connection String Dapper visual studio 2017 Now provide the response and nothing else.
Define your connection string(s) in appsettings.json { "connectionStrings": { "appDbConnection": "..." }} Read its value on Startup If you follow the convention and define your connection string(s) under connectionStrings , you can use the extension method GetConnectionString() to read its value. public class Startup{ public IConfiguration Configuration { get; private set; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { // Since you said you're using Dapper, I guess you might want to // inject IDbConnection? services.AddTransient<IDbConnection>((sp) => new SqlConnection(this.Configuration.GetConnectionString("appDbConnection")) ); // ... }} Use IDbConnection within the repository? public interface ISpecificationRepository{ Specification GetById(int specificationId);}public SpecificationRepository : ISpecificationRepository{ private readonly IDbConnection _dbConnection; public SpecificationRepository(IDbConnection dbConnection) { _dbConnection = dbConnection; } public Specification GetById(int specificationId) { const string sql = @"SELECT * FROM [YOUR_TABLE] WHERE Id = @specId;"; return _dbConnection .QuerySingleOrDefault<Specification>(sql, new { specId = specificationId }); }} Just need the connection string in a POCO? You might use the Options Pattern . Define a class that exactly matches the JSON object structure in appsettings.json public class ConnectionStringConfig{ public string AppDbConnection { get; set; }} Register that configuration on Startup public void ConfigureServices(IServiceCollection services){ // ... services.Configure<ConnectionStringConfig>( this.Configuration.GetSection("connectionStrings") ); // ...} Receive the accessor in your POCO public class YourPoco{ private readonly ConnectionStringConfig _connectionStringConfig; public YourPoco(IOptions<ConnectionStringConfig> configAccessor) { _connectionStringConfig = configAccessor.Value; // Your connection string value is here: // _connectionStringConfig.AppDbConnection; }} Notes: See my sample codes on how to read values from appsettings.json both on Core 1.x and 2.0. See how I setup if you have more than 1 connection string.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50507382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2254951/']}
jdg_372867
stackexchange
llm_judgeable_groundtruth_similarity
22746956
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 want to pass String array from C++ to Java by JNI, means return String[] to java. When I print the char* in C++ is correct, but when I print the String in Java is incorrect.For example, in C++ char* is "AdaptationSet 1", but in Java sometimes is "AdaptationSe" sometimes is "tring;" (I don't know what's this). I'm not sure where is incorrect in my code, please give me any helps. This is my C++ code jobjectArray getJavaStringArray(JNIEnv *env, char ** array, int size){ jobjectArray ret; int i; ret = (jobjectArray) env->NewObjectArray(size, env->FindClass("java/lang/String"), NULL); for (i = 0; i < size; i++) { env->SetObjectArrayElement(ret, i, env->NewStringUTF(array[i])); } return ret;} and extern "C" JNIEXPORT jobjectArray Java_com_example_test_MainActivity_nGetStrings(JNIEnv *env, jobject obj){ int i, size = 1; jobjectArray ret = NULL; char **array = (char**) calloc(size, sizeof(char*)); for (i = 0; i < size; i++) { std::stringstream ss; ss << "AdaptationSet " << i+1; array[i] = (char*) ss.str().c_str(); } return getJavaStringArray(env, array, size);} Java code package com.example.testimport ...;public class MainActivity extends Activity { private native String[] nGetStrings(); static { System.loadLibrary("myLib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] arrays = nGetStrings(); for(int i = 0; i < arrays.length; i++) { System.out.println("arrays[" + i + "] = " + arrays[i]); } }} SOLUTION: The problem is at this line: array[i] = (char*) ss.str().c_str(); The solution is copy the content, like this: array[i] = (char*) calloc(ss.str().size()+1, sizeof(char));memcpy(array[i], ss.str().c_str(), ss.str().size()); Thanks for your suggestions. Now provide the response and nothing else.
While it is unusual that a class implements both List and Set , there are some situations, where a Set can also support being a somewhat limited List . Personally, I prefer to declare an asList() method in these cases, instead of implementing both List and Set at the same time. Something like this: public class SetList<V> implements Set<V> { public List<V> asList(){ // return a list representation of this Set }} On the other hand, if you already have an existing class, that implements both List and Set , then the simplest solution for your problem is perhaps to explicitly call one of the super spliterator() methods: public class SetList<V> implements Set<V>, List<V> { @Override public Spliterator<V> spliterator() { return List.super.spliterator(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22746956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2380757/']}
jdg_372868
stackexchange
llm_judgeable_groundtruth_similarity
15191550
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 trying to create a simple menu with one button that will call a method to clear the array. I don't want to use xml because all I need is one button. Something like this - public boolean onCreateOptionsMenu(Menu menu) { button "Clear Array"; onClick{// run method that wipes array}; return true;} Thank you Now provide the response and nothing else.
A--C's method works, but you should avoid setting the click listeners manually. Especially when you have multiple menu items. I prefer this way: private static final int MENU_ITEM_ITEM1 = 1;...@Overridepublic boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MENU_ITEM_ITEM1, Menu.NONE, "Item name"); return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ITEM_ITEM1: clearArray(); return true; default: return false; }} By using this approach you avoid creating unecessary objects (listeners) and I also find this code easier to read and understand.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15191550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764080/']}
jdg_372869
stackexchange
llm_judgeable_groundtruth_similarity
196853
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand and simulate SYN Flood DDOS attacks. I am using snort to give me alerts. While I have control over the rate for my testing, I am interested in knowing what a good estimate of the traffic rate might be for an actual attack? Now provide the response and nothing else.
Nowadays TCP SYN attacks are not common, focus more on UDP amplification attacks over DNS, memcache and other UDP services. On the other hand, if you want to compute the traffic rate you can use the formula, IP header (20 bytes) + TCP header (20/32) bytes per packet, so is easy to know how many packets per second you need to send if you want a 1GB for example. Another key aspect that you may consider is the "IP address spooofing", in order to avoid the detection of the source of the attack is easy spoof IP/UDP packets than IP/TCP if you want full TCP connection.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/196853', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/187753/']}
jdg_372870
stackexchange
llm_judgeable_groundtruth_similarity
21857581
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From the CAP, I read HBase supports consistency and partition tolerance.I would like to know how consistency is achieved in HBase. Any locks are applied? I checked online didn't find good material on this. Could any body provide any blogs/articles on this topic. Now provide the response and nothing else.
Access to row data is atomic and includes any number of columns being read or writtento. There is no further guarantee or transactional feature that spans multiple rows oracross tables. The atomic access is a factor to this architecture beingstrictly consistent, as each concurrent reader and writer can make safe assumptionsabout the state of a row. When data is updated it is first written to a commit log, called a write-ahead log (WAL)in HBase, and then stored in the (sorted by RowId) in-memory memstore . Once the data in memory hasexceeded a given maximum value, it is flushed as an HFile to disk. After the flush, thecommit logs can be discarded up to the last unflushed modification. Thus a lock is needed only to protect the row in RAM.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21857581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243713/']}
jdg_372871
stackexchange
llm_judgeable_groundtruth_similarity
15943
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§=~[];Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§={___:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$$$$:(![]+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§],__$:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$_$_:(![]+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§],_$_:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$_$$:({}+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§],$$_$:(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§]+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§],_$$:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$$$_:(!""+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§],$__:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$_$:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$$__:({}+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§],$$_:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$$$:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$___:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§,$__$:++Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§};Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_=(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_=Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$]+(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$=Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$])+(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$=(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$])+((!Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§)+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$]+(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__=Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_])+(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$=(!""+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$])+(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._=(!""+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_])+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$]+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$;Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$=Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$+(!""+"")[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$]+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$;Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$=(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___)[Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_][Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_];Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$(Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$+"\""+"$('<\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+"=\\\""+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"."+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+".\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"?\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+"="+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+"\\\"><\\\\/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+">')."+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+"(\\\""+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\\"),\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"$('<\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+"=\\\""+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+".\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+"_"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+".\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+"?\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+"="+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+"\\\"><\\\\/\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$__+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__+">')."+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.___+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$_+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$_+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$__+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+"(\\\""+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$_$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§._$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$_$+"\\"+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.$$$+Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§.__$+"\\\");"+"\"")())(); Now provide the response and nothing else.
This obfuscated code is taking advantage of the wide possibilities to name Javascript variables. This makes a simple-obfuscated Javascript code to look much more scarier. As noted in the great article Valid JavaScript variable names and taken by me from this answer , Javascript variables can be represented using a wide-range of characters: An identifier must start with $ , _ , or any character in the Unicode categories “ Uppercase letter (Lu) ”, “ Lowercase letter (Ll) ”, “ Titlecase letter (Lt) ”, “ Modifier letter (Lm) ”, “ Other letter (Lo) ”, or “ Letter number (Nl) ”. The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters , U+200D zero width joiner characters , and characters in the Unicode categories “ Non-spacing mark (Mn) ”, “ Spacing combining mark (Mc) ”, “ Decimal digit number (Nd) ”, or “ Connector punctuation (Pc) ”. To begin deobfuscate the code I recommend to first rename the variable name into more readable one, let's say x . Using your favorite editor, replace every instance of Ø Ø¡Ø¢Ø£Ø¤Ø¥Ø¦Ø§ to x . Then put a new line after each semicolon to make the reading easier: x=~[];x={___:++x,$$$$:(![]+"")[x],__$:++x,$_$_:(![]+"")[x],_$_:++x,$_$$:({}+"")[x],$$_$:(x[x]+"")[x],_$$:++x,$$$_:(!""+"")[x],$__:++x,$_$:++x,$$__:({}+"")[x],$$_:++x,$$$:++x,$___:++x,$__$:++x};x.$_=(x.$_=x+"")[x.$_$]+(x._$=x.$_[x.__$])+(x.$$=(x.$+"")[x.__$])+((!x)+"")[x._$$]+(x.__=x.$_[x.$$_])+(x.$=(!""+"")[x.__$])+(x._=(!""+"")[x._$_])+x.$_[x.$_$]+x.__+x._$+x.$;x.$$=x.$+(!""+"")[x._$$]+x.__+x._+x.$+x.$$;x.$=(x.___)[x.$_][x.$_];x.$(x.$(x.$$+"\""+"$('<\\"+x.__$+x.$$_+x._$$+x.$$__+"\\"+x.__$+x.$$_+x._$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$$_+x.___+x.__+"\\"+x.$__+x.___+"\\"+x.__$+x.$$_+x._$$+"\\"+x.__$+x.$$_+x._$_+x.$$__+"=\\\""+x.$_$_+"\\"+x.__$+x.$$_+x._$$+"\\"+x.__$+x.$$_+x._$$+x.$$$_+x.__+"\\"+x.__$+x.$$_+x._$$+"/\\"+x.__$+x.$_$+x._$_+"\\"+x.__$+x.$$_+x._$$+"/\\"+x.__$+x.__$+x.$_$+x.$_$_+x.__+"\\"+x.__$+x.$__+x.$$$+"\\"+x.__$+x.$_$+x.___+"\\"+x.__$+x.$$$+x.__$+x._+"/\\"+x.__$+x.___+x._$$+x.$$$_+x.$_$+x.$_$_+"/\\"+x.__$+x.$$_+x.$$$+x.$_$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$$_+x._$_+"."+x.$$__+x._$+"\\"+x.__$+x.$$_+x._$_+x.$$$_+".\\"+x.__$+x.$_$+x._$_+"\\"+x.__$+x.$$_+x._$$+"?\\"+x.__$+x.$$_+x.$$_+"="+x.__$+x.$$_+"\\\"><\\\\/\\"+x.__$+x.$$_+x._$$+x.$$__+"\\"+x.__$+x.$$_+x._$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$$_+x.___+x.__+">')."+x.$_$_+"\\"+x.__$+x.$$_+x.___+"\\"+x.__$+x.$$_+x.___+x.$$$_+"\\"+x.__$+x.$_$+x.$$_+x.$$_$+"\\"+x.__$+x._$_+x.$__+x._$+"(\\\""+x.$_$$+x._$+x.$$_$+"\\"+x.__$+x.$$$+x.__$+"\\\"),\\"+x.__$+x._$_+"$('<\\"+x.__$+x.$$_+x._$$+x.$$__+"\\"+x.__$+x.$$_+x._$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$$_+x.___+x.__+"\\"+x.$__+x.___+"\\"+x.__$+x.$$_+x._$$+"\\"+x.__$+x.$$_+x._$_+x.$$__+"=\\\""+x.$_$_+"\\"+x.__$+x.$$_+x._$$+"\\"+x.__$+x.$$_+x._$$+x.$$$_+x.__+"\\"+x.__$+x.$$_+x._$$+"/\\"+x.__$+x.$_$+x._$_+"\\"+x.__$+x.$$_+x._$$+"/\\"+x.__$+x.__$+x.$_$+x.$_$_+x.__+"\\"+x.__$+x.$__+x.$$$+"\\"+x.__$+x.$_$+x.___+"\\"+x.__$+x.$$$+x.__$+x._+"/\\"+x.__$+x.___+x._$$+x.$$$_+x.$_$+x.$_$_+"/\\"+x.__$+x.$$_+x.$$$+x.$_$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$$_+x._$_+".\\"+x.__$+x.$_$+x.$_$+x.$_$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$_$+x.$$_+"_"+x._$+x._+x.__+".\\"+x.__$+x.$_$+x._$_+"\\"+x.__$+x.$$_+x._$$+"?\\"+x.__$+x.$$_+x.$$_+"="+x.$$_+"\\\"><\\\\/\\"+x.__$+x.$$_+x._$$+x.$$__+"\\"+x.__$+x.$$_+x._$_+"\\"+x.__$+x.$_$+x.__$+"\\"+x.__$+x.$$_+x.___+x.__+">')."+x.$_$_+"\\"+x.__$+x.$$_+x.___+"\\"+x.__$+x.$$_+x.___+x.$$$_+"\\"+x.__$+x.$_$+x.$$_+x.$$_$+"\\"+x.__$+x._$_+x.$__+x._$+"(\\\""+x.$_$$+x._$+x.$$_$+"\\"+x.__$+x.$$$+x.__$+"\\\");"+"\"")())(); Now, without diving deeper into the code you can see that the code is combined from 6 lines. The first five are variable declarations and applying values to them, whereas the last line is the actual execution of the code ( notice the () at the end which is a call for a function ). The fastest way, in my opinion, to understand what the code does is to simply replace the () at the end with .toString() . This will make the program print the final code instead of executing it. Thus, with just a simple step you can deobfuscate and understand the code. NOTE: don't execute an obfuscated or possibly-malicious code on your machine. Use virtual machine or another safe environment to execute it. x=~[];......< truncated for readability >......"\\"+x.__$+x.$$$+x.__$+"\\\");"+"\"")()).toString(); You can see that the following code is being printed to your screen: "function anonymous() {$('<script src="assets/js/Matghyu/Ce5a/wair.core.js?v=16"><\/script>').appendTo("body"),$('<script src="assets/js/Matghyu/Ce5a/wair.main_out.js?v=6"><\/script>').appendTo("body");}" Now we can understand that the obfuscated code is appending two <script> tags to the body of the HTML page. If you want to you can always try to understand how the final code was built but I usually stop here since I already figured out what the program does and following the obfuscation method might cause a headache sometimes.
{}
{'log_upvote_score': 4, 'links': ['https://reverseengineering.stackexchange.com/questions/15943', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/21032/']}
jdg_372872
stackexchange
llm_judgeable_groundtruth_similarity
67143
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 have three lists. x = {a,b,c,d}y = {A,B,C}z = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}} and I wish to construct the following list out of these three lists {{a,A,1},{a,B,2},{a,C,3},{b,A,4},{b,B,5},{b,C,6},{c,A,7},{c,B,8},{c,C,9},{d,A,10},{d,B,11},{d,C,12}} In the above list, every sublist or z is matched to an element in x and every item within a sublist in z is matched with an element in y . How can I achieve this? Now provide the response and nothing else.
Transpose[{## & @@ Transpose@Tuples[{x, y}], Flatten@z}](* {{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6}, {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}} *) or Flatten /@ Thread[{Tuples[{x, y}], Flatten@z}](* {{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6}, {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}} *) or MapThread[Append, {Tuples[{x, y}], Flatten[z]}](* {{a, A, 1}, {a, B, 2}, {a, C, 3}, {b, A, 4}, {b, B, 5}, {b, C, 6}, {c, A, 7}, {c, B, 8}, {c, C, 9}, {d, A, 10}, {d, B, 11}, {d, C, 12}} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/67143', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13408/']}
jdg_372873
stackexchange
llm_judgeable_groundtruth_similarity
5507718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's a simple example to illustrate the behavior: Given this html markup: <div data-company="Microsoft"></div> and this jQuery code (using jQuery 1.5.1): // read the dataalert($("div").data("company"));// returns Microsoft <<< OK!// set the data$("div").data("company","Apple");alert($("div").data("company"));// returns Apple <<< OK!// attribute selectoralert($("div[data-company='Apple']").length);// returns 0 <<< WHY???// attribute selector againalert($("div[data-company='Microsoft']").length);// returns 1 <<< WHY???// set the attribute directly$("div").attr("data-company","Apple");alert($("div[data-company='Apple']").length);// now returns 1 <<< OK! Since jQuery automatically imports the HTML5 data-* into jQuery's data object, shouldn't the attributes be updated as well when the data changes? Now provide the response and nothing else.
Normally, there's not a need for roundtripping .data() 's if you're consistent in using .data() to access/set/modify data on DOM elements. For that reason, it makes sense to avoid the performance overhead of accessing the DOM for every .data() set/modify operation ( .data() stores its values in jQuery.cache internally). If you want to force the roundtrip behavior yourself, you could subscribe to the "setData" or "changeData" events and then push the .data() update in those events through to the corresponding DOM element via .attr() .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5507718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/79592/']}
jdg_372874
stackexchange
llm_judgeable_groundtruth_similarity
41349
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If X and Y are non-isomorphic objects, then "[is / is not] isomorphic to [ X / Y ]" are invariants that distinguish X and Y. You can also do things like take an object Z that is not isomorphic to Y, and then "is isomorphic to X or isomorphic to Z" is another invariant that distinguishes X and Y. Similarly, if W is isomorphic to X, then "is isomorphic to W" works too. Are there any objects X and Y known to be non-isomorphic, but all known distinguishing invariants (a) use the concept or definition of isomorphism or (b) use the concept or definition of being isomorphic to some object Z, where Z is isomorphic to X or Y Now provide the response and nothing else.
Hereditarily indecomposable Banach spaces are strange objects that fail to be isomorphic to any of their proper subspaces. However, in a certain sense those subspaces are not "interestingly different" from the spaces themselves. So there is no hope of finding an invariant to distinguish between the space and a subspace. The way the proof actually works is that one proves that every operator from the space to itself can be approximated, in a certain sense, by a multiple of the identity, and hence either has no hope of being an isomorphism or is Fredholm with index zero. But an isomorphism to a proper subspace would have to be Fredholm with positive (or infinite) index.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/41349', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_372875
stackexchange
llm_judgeable_groundtruth_similarity
12228159
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 exactly as the Sandboxed Helper App example provided by Apple and all seems to be running fine. I'm able to successfully create a NSXPCConnection object and also get back my remote object (via remoteObjectProxyWithErrorHandler ). However when I call a method on the proxy object (defined in the Protocol definition), I get back this error: Failed to connect to launch agent: Error Domain=NSCocoaErrorDomain Code=4099 "Couldn’t communicate with a helper application. Essentially no matter what I do I'm not able to communicate with my helper app. I'm doing nothing fancy, just trying to make a simple call to the helper app to NSLog() something. But it doesn't work. Strangely I also don't see any output from inside: - (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection What could I possibly be doing wrong? UPDATE:Apparently if I uncheck 'Enable App Sandboxing' on my main app, it works! So there's something wrong with enabling sandboxing after which it does not want to communicate with my helper app. Do I need more entitlements? I've tried them all under xcode! Now provide the response and nothing else.
Your helper application is sandboxed. Therefore, it cannot register a mach service dynamically, although Xcode allows it for debug purpose. However, when you add your helper application to login items (using SMLoginItemSetEnabled() ), launchd will automatically register a mach service for you named with its bundle identifier. Now your main application is sandboxed. Therefore, random mach communication is not allowed. The only way to make it work was to add a temporary mach lookup entitlement. Since 10.7.4. Apple introduced the application-groups entitlements as a solution for this case, where an application needs to communicate with a helper app. Both applications have to share the same application-groups entitlement. It can be any value, but Apple requires that this value must start with your Team-ID (e.g: Team-id.myApp). Then, your helper application bundle identifier must start with that same entitlement (e.g Team-id.myApp.myHelperApp). After that, your main application can freely communicate with your helper application using a XPC communication with the service named with the helper application bundle identifier (i.e. Team-id.myApp.myHelperApp). Also, the two applications will share access to a group container folder named with the application group entitlement (e.g. ~/Library/Group Containers/Team-id.myApp), that you have to create manually if you will need it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12228159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189924/']}
jdg_372876
stackexchange
llm_judgeable_groundtruth_similarity
17723790
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 trying to get the first character of a variable, but I'm getting a Bad substitution error. Can anyone help me fix it? code is: while IFS=$'\n' read linedo if [ ! ${line:0:1} == "#"] # Error on this line then eval echo "$line" eval createSymlink $line fidone < /some/file.txt Am I doing something wrong or is there a better way of doing this? -- EDIT -- As requested - here's some sample input which is stored in /some/file.txt $MOZ_HOME/mobile/android/chrome/content/browser.js$MOZ_HOME/mobile/android/locales/en-US/chrome/browser.properties$MOZ_HOME/mobile/android/components/ContentPermissionPrompt.js Now provide the response and nothing else.
To get the first character of a variable you need to say: v="hello"$ echo "${v:0:1}"h However, your code has a syntax error: [ ! ${line:0:1} == "#"]# ^-- missing space So this can do the trick: $ a="123456"$ [ ! "${a:0:1}" == "#" ] && echo "doesnt start with #"doesnt start with #$ a="#123456"$ [ ! "${a:0:1}" == "#" ] && echo "doesnt start with #"$ Also it can be done like this: $ a="#123456"$ [ "$(expr substr $a 1 1)" != "#" ] && echo "does not start with #"$ $ a="123456"$ [ "$(expr substr $a 1 1)" != "#" ] && echo "does not start with #"does not start with # Update Based on your update, this works to me: while IFS=$'\n' read linedo echo $line if [ ! "${line:0:1}" == "#" ] # Error on this line then eval echo "$line" eval createSymlink $line fidone < file
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17723790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264276/']}
jdg_372877
stackexchange
llm_judgeable_groundtruth_similarity
111459
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 have a solution of a finite element analysis and I have a list of data {{x,y,a}....} where x, y are the coordinates and a is the value to be plotted. The geometry is half of a tooth like this but when I used ListDensityPlot[data, PlotLegends -> Automatic, AspectRatio -> Automatic, ColorFunction -> "Rainbow", InterpolationOrder -> 1 ] to plot, the boundary is blurred. it seems to be extrapolated. Anyone knows how to fix this to show the boundary? the data can be found here:[ https://drive.google.com/file/d/0BxRSTZpaT9wrcVI5enVVMl9laGs/view?usp=sharing][3] I made it a .nb file and two plots of InterpolationOrder of 0 and 1 Now provide the response and nothing else.
In short, the reason is that SumCommand 's (temporary) definition won't automatically get distributed to the parallel kernels because now SumCommand lives in the package`Private` context , not Global` . This means that SumCommand won't get evaluated to Sum on the subkernels. It gets returned as-is to the main kernel, where now SumCommand does have a definition, gets evaluated to Sum , which in turn gets evaluated to the desired result. But all the evaluation happens on the main kernel. Aside: Note that Begin["Private`"] should be Begin["`Private`"] so that private symbols will go into package`Private` and not into Private` . Why is the function slow when in a package? Most parallel functions, such as ParallelTable , automatically distribute the definitions of symbols. (The notable exception is ParallelEvaluate .) When you put the function into a package, the context of all the auxiliary symbols (such as SumCommand and TableCommand ) change. This prevents the distribution mechanism from kicking in. Package symbols, which reside in contexts other than Global` , do not get distributed by default. This is to prevent the distribution of package symbol definitions to subkernels, which would break packages which must also do initialization (such as loading LibraryFunction s) in addition to issuing definitions. Instead packages should be properly loaded on each subkernel, which can be automated with ParallelNeeds . Unfortunately I do not fully understand the distribution rules for contexts though ... you can read more at DistributedContexts and links within that page. This theory that the problem is that SumCommand doesn't get distributed can be verified by adding DistributeDefinitions[SumCommand] right after TableCommand = ParallelTable; SumCommand = Sum; . This will make it run fast again (but it is not a good workaround, see below). How to fix it? I have never written packages which use parallelization, so I have no experience with this, and no experience with what the major pitfalls are. But I would not use DistributeDefinitions the way I suggested above (which was only for testing the theory that the problem is with distribution). One problem with the way Block is used here is that Block won't have any effect across kernels. It only works on the main kernel. Thus if we simply insert DistributeDefinitions[SumCommand] inside of the Block body, the definition will get distributed to the subkernels, but it won't get cleared on the subkernels when the Block finishes. Instead it will persist even after function finishes. You can verify this with ParallelEvaluate[package`Private`SumCommand] . Instead I suggest never sending the symbol SumCommand to the subkernel in the first place. Just send Sum instead. One way to achieve this is with a With -definition (instead of a Block -definition), which does a direct replacement of SumCommand within the body of With . Here's the final code: BeginPackage["package`"];function::usage = "function[x] is a function to calculate stuff";RunInParallel::usage = "RunInParallel is an option for function which determines whether it runs in parallel or not.";Begin["`Private`"];Options[function] = {RunInParallel -> False};function[x_, OptionsPattern[]] := Block[{TableCommand, SumCommand}, Which[ OptionValue[RunInParallel] === False, TableCommand = Table; SumCommand = Sum;, OptionValue[RunInParallel] === True, TableCommand = ParallelTable; SumCommand = Sum;, True, TableCommand = OptionValue[RunInParallel][[1]]; SumCommand = OptionValue[RunInParallel][[2]]; ]; With[{SumCommand=SumCommand}, TableCommand[ SumCommand[ BesselJ[0, 10^-9 k]/(n + x^k), {k, 0, 50000} ] , {n, 0, 12}] ] ]End[];EndPackage[]; (To avoid the red colouring you might consider using a different name for the With variable.) This version is robust and runs fast.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/111459', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/39053/']}
jdg_372878
stackexchange
llm_judgeable_groundtruth_similarity
2403660
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 need to do determine processor support for SSE2 prior installing a software. From what I understand, I came up with this: bool TestSSE2(char * szErrorMsg){ __try { __asm { xorpd xmm0, xmm0 // executing SSE2 instruction } } #pragma warning (suppress: 6320) __except (EXCEPTION_EXECUTE_HANDLER) { if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION) { _tcscpy_s(szErrorMsg,MSGSIZE, _T("Streaming SIMD Extensions 2(SSE2) is not supported by the CPU.\r\n Unable to launch APP")); return false; } _tcscpy_s(szErrorMsg,MSGSIZE, _T("Streaming SIMD Extensions 2(SSE2) is not supported by the CPU.\r\n Unable to launch APP")); return false; } return true;} Would this work? I'm not really sure how to test, since my CPU supports it, so I don't get false from the function call. How do I determine processor support for SSE2? Now provide the response and nothing else.
Call CPUID with eax = 1 to load the feature flags in to edx. Bit 26 is set if SSE2 is available. Some code for demonstration purposes, using MSVC++ inline assembly (only for x86 and not portable!): inline unsigned int get_cpu_feature_flags(){ unsigned int features; __asm { // Save registers push eax push ebx push ecx push edx // Get the feature flags (eax=1) from edx mov eax, 1 cpuid mov features, edx // Restore registers pop edx pop ecx pop ebx pop eax } return features;}// Bit 26 for SSE2 supportstatic const bool cpu_supports_sse2 = (cpu_feature_flags & 0x04000000)!=0;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2403660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/261842/']}
jdg_372879
stackexchange
llm_judgeable_groundtruth_similarity
10698339
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: How do you determine the ideal buffer size when using FileInputStream? When reading raw data from a file (or any input stream) using either the C++'s istream family's read() or C's fread() , a buffer has to be supplied, and a number of how much data to read. Most programs I have seen seem to arbitrarily chose a power of 2 between 512 and 4096. Is there a reason it has to/should be a power of 2, or this just programer's natural inclination to powers of 2? What would be the "ideal" number? By "ideal" I mean that it would be the fastest. I assume it would have to be a multiple of the underlying device's buffer size? Or maybe of the underlying stream object's buffer? How would I determine what the size of those buffers is, anyway? And once I do, would using a multiple of it give any speed increase over just using the exact size? EDIT Most answers seem to be that it can't be determined at compile time. I am fine with finding it at runtime. Now provide the response and nothing else.
SOURCE: How do you determine the ideal buffer size when using FileInputStream? Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency. Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system can be extremely inefficient (i.e. if you configured your buffer to read 4100 bytes at a time, each read would require 2 block reads by the file system). If the blocks are already in cache, then you wind up paying the price of RAM -> L3/L2 cache latency. If you are unlucky and the blocks are not in cache yet, the you pay the price of the disk->RAM latency as well. This is why you see most buffers sized as a power of 2, and generally larger than (or equal to) the disk block size. This means that one of your stream reads could result in multiple disk block reads - but those reads will always use a full block - no wasted reads. Ensuring this also typically results in other performance friendly parameters affecting both reading and subsequent processing: data bus width alignment, DMA alignment, memory cache line alignment, whole number of virtual memory pages.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10698339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/331785/']}
jdg_372880
stackexchange
llm_judgeable_groundtruth_similarity
17000193
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 we have more than one @Path annotation for same REST method i.e. the method executed is the same, but it is executed on accessing more than one URL? E.g.: I want to run the searchNames() method on both http://a/b/c and http://a/b . Now provide the response and nothing else.
You can't have mutliple @Path annotations on a single method. It causes a "duplicate annotation" syntax error. However, there's a number of ways you can effectively map two paths to a method. Regular expressions in @Path annotation The @Path annotation in JAX-RS accepts parameters, whose values can be restricted using regular expressions. This annotation: @Path("a/{parameter: path1|path2}") would enable the method to be reached by requests for both /a/path1 and /a/path2 . If you need to work with subpaths, escape slashes: {a:path1\\/subPath1|path2\\/subPath2} Serving responses with a redirection status code Alternatively, you could set up a redirection. Here's a way to do it in Jersey (the reference implementation of JAX-RS), by defining another subresource. This is just an example, if you prefer a different way of handling redirections, feel free to use it. @Path("basepath")public class YourBaseResource { //this gets injected after the class is instantiated by Jersey @Context UriInfo uriInfo; @Path("a/b") @GET public Responce method1(){ return Response.ok("blah blah").build(); } @Path("a/b/c") @GET public Response method2(){ UriBuilder addressBuilder = uriInfo.getBaseUriBuilder(); addressBuilder.path("a/b"); return Response.seeOther(addressBuilder.build()).build(); }} Using a servlet filter to rewrite URLs If you're going to need such functionality often, I suggest intercepting the incoming requests using a servlet filter and rewriting the paths on the fly. This should help you keep all redirections in one place. Ideally, you could use a ready library. UrlRewriteFilter can do the trick, as long as you're fine with a BSD license (check out their google code site for details) Another option is to handle this with a proxy set up in front of your Java app. You can set up an Apache server to offer basic caching and rewrite rules without complicating your Java code.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17000193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2162168/']}
jdg_372881
stackexchange
llm_judgeable_groundtruth_similarity
85394
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 no doubt this is a basic question. However, I am working through Miranda's book on Riemann surfaces and algebraic curves, and it has yet to be addressed. Why does Miranda (and from what little I've seen, algebraic geometers in general) place so much emphasis on projective space when studying algebraic curves? Why is this the natural setting to conduct algebraic geometry in? Also, projective spaces and curves in them are hard for me to visualize, and in general I don't have any good intuition about these objects. Do working algebraic geometers simply not visualize things as much, or are there some nice interpretations of projective spaces and algebraic curves I am missing that would make them seem more natural and give me more intuition about them? Now provide the response and nothing else.
The most appropriate answer will depend on why you are working through a book on Riemann surfaces and algebraic curves, but I will try to give some suggestions. Since you mention Riemann surfaces, let's start with some analogy with smooth manifolds. The Whitney embedding theorem says that any smooth manifold can be embedded in $\mathbb{R}^N$ for $N$ sufficiently large, so we can always think of a smooth manifold as a submanifold of $\mathbb{R}^N$. This occasionally helps with intuition and visualization, and can simplify some constructions. In the case of complex manifolds (e.g. Riemann surfaces), you might ask whether the same holds true holomorphically , i.e. whether any complex manifold can be holomorphically embedded in $\mathbb{C}^N$ for $N$ sufficiently large. It turns out that usually the answer is no. It is an easy consequence of the Liouville theorem that no compact complex manifold is a complex submanifold of $\mathbb{C}^N$. If you only care about compact complex manifolds, then $\mathbb{CP}^N$ turns out to be the best possible (see e.g. the Kodaira embedding theorem, which characterizes which compact complex manifolds are complex submanifolds of $\mathbb{CP}^N$). If your motivation is the study of solutions to polynomial equations, then as mentioned in other answers and comments, projective spaces are the appropriate completions of affine space that allow as many solutions as possible, allowing various formulas (e.g. couting intersections) work without additional qualification. About visualization: for curves in $\mathbb{CP}^2$, first take some affine chart $\mathbb{C}^2 \subset \mathbb{CP}^2$, and then look at the intersection with some "real slice" $\mathbb{R}^2 \subset \mathbb{C}^2$. For example if we look at the curve in $\mathbb{CP}^2$ given by the zero set of $x^2-yz$, by working on the affine chart $z\neq0$ this becomes $y = x^2$ on $\mathbb{C}^2$, and if we restrict to real $x,y$ we get a parabola.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/85394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18240/']}
jdg_372882
stackexchange
llm_judgeable_groundtruth_similarity
7802116
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 was wondering if it's acceptable to put custom data in an HTTP authorization header. We're designing a RESTful API and we may need a way to specify a custom method of authorization. As an example, let's call it FIRE-TOKEN authentication. Would something like this be valid and allowed according to the spec: Authorization: FIRE-TOKEN 0PN5J17HBGZHT7JJ3X82:frJIUN8DYpKDtOLCwo//yllqDzg= The first part of the second string (before the ':') is the API key, the second part is a hash of query string. Now provide the response and nothing else.
The format defined in RFC2617 is credentials = auth-scheme #auth-param . So, in agreeing with fumanchu, I think the corrected authorization scheme would look like Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg=" Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)... auth-param = token BWS "=" BWS ( token / quoted-string ) I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters). Some examples of this auth-param syntax can be seen here... https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p7-auth-19#section-4.4 https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7802116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/394491/']}
jdg_372883
stackexchange
llm_judgeable_groundtruth_similarity
19624607
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Normally, we write the mapper in the form : public static class Map extends Mapper<**LongWritable**, Text, Text, IntWritable> Here the input key-value pair for the mapper is <LongWritable, Text> - as far as I know when the mapper gets the input data its goes through line by line - so the Key for the mapper signifies the line number - please correct me if I am wrong. My question is : If I give the input key-value pair for mapper as <Text, Text> then it is giving the error java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text Is it a mandatory to give the input key-value pair of mapper as <LongWritable, Text> - if yes then why ? if no then what the reason of the error ? Can you please help me understand the proper reasoning of the error ? Thanks in advance. Now provide the response and nothing else.
The input to the mapper depends on what InputFormat is used. The InputFormat is responsible for reading the incoming data and shaping it into whatever format the Mapper expects.The default InputFormat is TextInputFormat , which extends FileInputFormat<LongWritable, Text> . If you do not change the InputFormat, using a Mapper with different Key-Value type signature than <LongWritable, Text> will cause this error. If you expect <Text, Text> input, you will have to choose an appropiate InputFormat. You can set the InputFormat in Job setup: job.setInputFormatClass(MyInputFormat.class); And like I said, by default this is set to TextInputFormat. Now, let's say your input data is a bunch of newline-separated records delimited by a comma: "A,value1" "B,value2" If you want the input key to the mapper to be ("A", "value1"), ("B", "value2") you will have to implement a custom InputFormat and RecordReader with the <Text, Text> signature. Fortunately , this is pretty easy. There is an example here and probably a few examples floating around StackOverflow as well. In short, add a class which extends FileInputFormat<Text, Text> and a class which extends RecordReader<Text, Text> . Override the FileInputFormat#getRecordReader method, and have it return an instance of your custom RecordReader. Then you will have to implement the required RecordReader logic. The simplest way to do this is to create an instance of LineRecordReader in your custom RecordReader, and delegate all basic responsibilities to this instance. In the getCurrentKey and getCurrentValue-methods you will implement the logic for extracting the comma delimited Text contents by calling LineRecordReader#getCurrentValue and splitting it on comma. Finally, set your new InputFormat as Job InputFormat as shown after the second paragraph above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19624607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1091608/']}
jdg_372884
stackexchange
llm_judgeable_groundtruth_similarity
860529
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Fatal error: Call to undefined function lcfirst() in C:\xampp\htdocs\allsides\others\basecontroller.php on line 9 How come it didn't find a Text Proccessing function mentioned in the official php manual ( http://www.php.net/manual/en/function.lcfirst.php )? Now provide the response and nothing else.
Check the version: (PHP 5 >= 5.3.0) You obviously have a version lower than that. :) Use phpversion() to quickly check what version you have. As pointed out by the comments, however, this function is trivially easy to replicate: if(function_exists('lcfirst') === false) { function lcfirst($str) { $str[0] = strtolower($str[0]); return $str; }} You can throw the above code somewhere in your project's library/utilities file and it won't break when/if you upgrade to 5.3.0 down the road.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/860529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106615/']}
jdg_372885
stackexchange
llm_judgeable_groundtruth_similarity
19149186
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 topic has been addressed for text based emoticons at link1 , link2 , link3 . However, I would like to do something slightly different than matching simple emoticons. I'm sorting through tweets that contain the emoticons' icons. The following unicode information contains just such emoticons: pdf . Using a string with english words that also contains any of these emoticons from the pdf , I would like to be able to compare the number of emoticons to the number of words. The direction that I was heading down doesn't seem to be the best option and I was looking for some help. As you can see in the script below, I was just planning to do the work from the command line: $cat <file containing the strings with emoticons> | ./emo.py emo.py psuedo script: import reimport sysfor row in sys.stdin: print row.decode('utf-8').encode("ascii","replace") #insert regex to find the emoticons if match: #do some counting using .split(" ") #print the counting The problem that I'm running into is the decoding/encoding. I haven't found a good option for how to encode/decode the string so I can correctly find the icons. An example of the string that I want to search to find the number of words and emoticons is as follows: "Smiley emoticon rocks! I like you ." The challenge: can you make a script that counts the number of words and emoticons in this string? Notice that the emoticons are both sitting next to the words with no space in between. Now provide the response and nothing else.
First, there is no need to encode here at all. You're got a Unicode string, and the re engine can handle Unicode, so just use it. A character class can include a range of characters, by specifying the first and last with a hyphen in between. And you can specify Unicode characters that you don't know how to type with \U escape sequences. So: import res=u"Smiley emoticon rocks!\U0001f600 I like you.\U0001f601"count = len(re.findall(ru'[\U0001f600-\U0001f650]', s)) Or, if the string is big enough that building up the whole findall list seems wasteful: emoticons = re.finditer(ru'[\U0001f600-\U0001f650]', s)count = sum(1 for _ in emoticons) Counting words, you can do separately: wordcount = len(s.split()) If you want to do it all at once, you can use an alternation group: word_and_emoticon_count = len(re.findall(ru'\w+|[\U0001f600-\U0001f650]', s)) As @strangefeatures points out, Python versions before 3.3 allowed "narrow Unicode" builds. And, for example, most CPython Windows builds are narrow. In narrow builds, characters can only be in the range U+0000 to U+FFFF . There's no way to search for these characters, but that's OK, because they're don't exist to search for; you can just assume they don't exist if you get an "invalid range" error compiling the regexp. Except, of course, that there's a good chance that wherever you're getting your actual strings from, they're UTF-16-BE or UTF-16-LE, so the characters do exist, they're just encoded into surrogate pairs. And you want to match those surrogate pairs, right? So you need to translate your search into a surrogate-pair search. That is, convert your high and low code points into surrogate pair code units, then (in Python terms) search for: (lead == low_lead and lead != high_lead and low_trail <= trail <= DFFF or lead == high_lead and lead != low_lead and DC00 <= trail <= high_trail or low_lead < lead < high_lead and DC00 <= trail <= DFFF) You can leave off the second condition in the last case if you're not worried about accepting bogus UTF-16. If it's not obvious how that translates into regexp, here's an example for the range [\U0001e050-\U0001fbbf] in UTF-16-BE: (\ud838[\udc50-\udfff])|([\ud839-\ud83d].)|(\ud83e[\udc00-\udfbf]) Of course if your range is small enough that low_lead == high_lead this gets simpler. For example, the original question's range can be searched with: \ud83d[\ude00-\ude50] One last trick, if you don't actually know whether you're going to get UTF-16-LE or UTF-16-BE (and the BOM is far away from the data you're searching): Because no surrogate lead or trail code unit is valid as a standalone character or as the other end of a pair, you can just search in both directions: (\ud838[\udc50-\udfff])|([\ud839-\ud83d][\udc00-\udfff])|(\ud83e[\udc00-\udfbf])|([\udc50-\udfff]\ud838)|([\udc00-\udfff][\ud839-\ud83d])|([\udc00-\udfbf]\ud83e)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19149186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2322417/']}
jdg_372886
stackexchange
llm_judgeable_groundtruth_similarity
5405673
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Varargs: public static void foo(String... string_array) { ... } versus Single array param: public static void bar(String[] string_array) { ... } Java 1.6 seems to accept/reject the following: String[] arr = {"abc", "def", "ghi"};foo(arr); // acceptbar(arr); // acceptfoo("abc", "def", "ghi"); // acceptbar("abc", "def", "ghi"); // reject Assuming the above is true/correct, why not always use varargs instead of single array param? Seems to add a touch of caller flexiblity for free. Can an expert share the internal JVM difference, if there is one? Thanks. Now provide the response and nothing else.
Arrays have been around from the beginning of Java, while varargs are a fairly recent addition. Thus a lot of older code still happily uses arrays. Note also that calling a generic vararg method with an explicit array parameter may silently produce different behaviour than expected: public <T> void foo(T... params) { ... }int[] arr = {1, 2, 3};foo(arr); // passes an int[][] array containing a single int[] element Thus - apart from requiring a lot of effort for no clear benefit - it is not always desirable to replace legacy array parameters with varargs. Not to mention the cases when you can't, because there is another parameter after the array in the method parameter list: public void foo(String[] strings, String anotherParam) { ... } Reordering the parameters may technically solve this, however it breaks client code. Update: Effective Java 2nd. Edition, Item 42: Use varargs judiciously explains this in more details, giving also a concrete example: Arrays.asList() was retrofitted in Java5 to have vararg parameters, which inadvertently broke a lot of existing code may cause surprises when using this (now obsolete) idiom to print an array: System.out.println(Arrays.asList(myArray)); Update2: Double checked the source, and it says that the problem occurrs with arrays of primitive types, such as int[] . Before varargs, code like this: int[] digits = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 4 };System.out.println(Arrays.asList(digits)); would emit a compilation error, because only arrays of reference types could be converted to a List . Since varargs, and retrofitting asList , the code above compiles without warnings, and the unintended result is something like "[[I@3e25a5]" .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5405673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257299/']}
jdg_372887
stackexchange
llm_judgeable_groundtruth_similarity
70122336
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 converting SVG to vector asset by importing it to android studio. How can I draw that vector to canvas with jetpack compose. The only option I see is drawImage, which only takes ImageBitmap. But this is a vector and not a bitmap, so is there a way to just draw ImageVector. val logoVector: ImageVector = ImageVector.vectorResource(id = R.drawable.diasyst_logo) Now provide the response and nothing else.
You can wrap your ImageVector into a VectorPainter , which is able to render to the standard compose Canvas. val vector = ImageVector.vectorResource(id = R.drawable.ic_launcher_foreground)val painter = rememberVectorPainter(image = vector)Canvas(modifier = Modifier.fillMaxSize()) { with(painter) { draw(painter.intrinsicSize) }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70122336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969724/']}
jdg_372888
stackexchange
llm_judgeable_groundtruth_similarity
28513531
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 need to convert the Json response to array using JavaScript . I have the json response which is :["simmakkal madurai","goripalayam madurai"].now I want to change this results to array format . So, How to I convert the json result to array. Now provide the response and nothing else.
You can create a simple template tag to call any method with any arguments: from django import templateregister = template.Library()@register.simple_tagdef call_method(obj, method_name, *args): method = getattr(obj, method_name) return method(*args) And then in your template: {% call_method obj_customer 'get_something' obj_business %} But, of course, crating of a specialized template tag is more safe :-) @register.simple_tagdef get_something(customer, business): return customer.get_something(business) Template: {% get_something obj_customer obj_business %}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28513531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3608179/']}
jdg_372889
stackexchange
llm_judgeable_groundtruth_similarity
77769
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 a question about simple field extensions. For a field $F$, if $[F(a):F]$ is odd, then why is $F(a)=F(a^2)$? Now provide the response and nothing else.
Note that $F(a)\supseteq F(a^2)\supseteq F$, hence$$\text{odd }=[F(a):F]=[F(a):F(a^2)][F(a^2):F].$$What can $[F(a):F(a^2)]$ be? What, therefore, must it be?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/77769', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18653/']}
jdg_372890
stackexchange
llm_judgeable_groundtruth_similarity
46528616
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 array [a, b, c] . I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0] . I guess it would be something like this, but I can't make it works. for (let i = 0; i < array.length; i++) { newArray = [ ...array.splice(0, i), 0, ...array.splice(i, array.length), ];} Thank you for helping me! Now provide the response and nothing else.
For getting a new array, you could concat the part an add a zero element for each element. var array = ['a', 'b', 'c'], result = array.reduce((r, a) => r.concat(a, 0), [0]); console.log(result); Using the same array var array = ['a', 'b', 'c'], i = 0;while (i <= array.length) { array.splice(i, 0, 0); i += 2;}console.log(array); A bit shorter with iterating from the end. var array = ['a', 'b', 'c'], i = array.length;do { array.splice(i, 0, 0);} while (i--)console.log(array);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46528616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8392424/']}
jdg_372891
stackexchange
llm_judgeable_groundtruth_similarity
10776191
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 little Excel VBA function always returns false, no what word is passed in. Function SpellCheck(SomeWord As String)SpellCheck = Application.CheckSpelling(SomeWord)End Function In fact, in the IDE I can verify that Application.CheckSpelling("hello") fails, though the Excel spellchecker does detect misspellings. What I'm trying to do is get a T/F value for each word if it is spelled correctly. Now provide the response and nothing else.
Like I mentioned in my comment it works. Option ExplicitSub Sample() MsgBox SpellCheck("hello") '<~~ Returns True MsgBox SpellCheck("daasd") '<~~ Returns FalseEnd SubFunction SpellCheck(SomeWord As String) As Boolean SpellCheck = Application.CheckSpelling(SomeWord)End Function Application.CheckSpelling will not correct or offer to correct a misspelled word, it only returns True or False I tested ?Application.CheckSpelling("hello") in immediate window and it returned True EDIT : Calling Application.CheckSpelling from UDF would always return False . Last time I checked, it was still a bug and there was no way around it. If there is a recent update on that then I am not aware of it. :) MORE EDIT Here is your function slightly modified which will work as a UDF as well :) Got the idea from this link Function SpellCheck(rng As Range) As Boolean Dim oxlAp As Object Set oxlAp = CreateObject("Excel.Application") SpellCheck = oxlAp.CheckSpelling(rng.Value) oxlAp.Quit Set oxlAp = NothingEnd Function
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10776191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/782880/']}
jdg_372892
stackexchange
llm_judgeable_groundtruth_similarity
15038
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: In any of the RAID levels that use striping, increasing the number of physical disks usually increases performance, but also increase the chance of any one disk in the set failing. I have this idea that I shouldn't use more than about 6-8 disks in a given RAID set but that's more just passed down knowledge and not hard fact from experience. Can anyone give me good rules with reasons behind them for the max number of disks in a set? Now provide the response and nothing else.
The recommended maximum number of disks in a RAID system varies a lot. It depends on a variety of things: Disk technology SATA tolerates smaller arrays than SAS/FC does, but this is changing. RAID Controller limits The RAID controller itself may have fundamental maximums. If it is SCSI based and each visible disk is a LUN, the 7/14 rule holds true. If it FibreChannel based, it can have up to 120 or more visible disks. RAID Controller processor If you go with any kind of parity RAID, the CPU in the RAID card will be the limiter on how fast you can write data. There will be a fundamental maximum for the card. You'll see it when a drive fails in a RAID5/6 LUN, as the performance drop will affect all LUNs associated with the RAID card. Bus bandwidth U320 SCSI has its own limits, as does FibreChannel. For SCSI keeping RAID members on different channels can enhance parallelism and improve performance, if the controller supports it. For SATA-based RAID, you don't want to have more than about 6.5TB of raw disk if you're using RAID5. Go past than and RAID6 is a much better idea. This is due to the non-recoverable read error rate. If the size of the array is too large, the chances of a non-recoverable read error occurring during the array rebuild after a loss get higher and higher. If that happens, it's very bad. Having RAID6 greatly reduces this exposure. However, SATA drives have been improving in quality lately, so this may not hold true for much longer. The number of spindles in an array doesn't really worry me over much, as it's pretty simple to get to 6.5TB with 500GB drives on U320. If doing that, it would be a good idea to put half of the drives on one channel and half on the other just to reduce I/O contention on the bus side. SATA-2 speeds are such that even just two disks transferring at max-rate can saturate a bus/channel. SAS disks have a lower MTBF rate than SATA (again, this is beginning to change) so the rules are less firm there. There are FC arrays that use SATA drives internally. The RAID controllers there are very sophisticated, which muddies the rules of thumb. For instance, the HP EVA line of arrays groups disks into 'disk groups' on which LUNs are laid out. The controllers purposefully place blocks for the LUNs in non-sequential locations, and perform load-leveling on the blocks behind the scenes to minimize hot-spotting. Which is a long way of saying that they do a lot of the heavy lifting for you with regards to multiple channel I/O, spindles involved in a LUN, and dealing with redundancy. Summing up, failure rates for disks doesn't drive the rules for how many spindles are in a RAID group, performance does. For the most part.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/15038', 'https://serverfault.com', 'https://serverfault.com/users/5473/']}
jdg_372893
stackexchange
llm_judgeable_groundtruth_similarity
25832149
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 read some threads about how the javascript function parameters passing works when the parameter is an object; I noticed that there is much confusion on the passing method, at least in the terminology: pass-by-reference, pass-by-copy-reference, and so on.This question is not about how is named this passing method, or how it works inside, but involves some way an answer to this question. I have some large, very large object, to pass to a function as argument; I need to understand if the object-passing implies some copy of the object, so memory consumption, computational effort, memory leak risks are proportional to the size of the object passed, for each function call (I have many calls), or if it is passed in a non size-proportional consequences way. Since altering the object's properties in the function alters the object in the outer scope, but altering the object itself does not, I think the memory used internally in the function to store and "reference" the parameter is not dependent on its size, because the object seems not to be copied, but I need to be sure about it. Sorry for the poor explaining of my english! EDIT: the answer involves in some way an insight on JS passing mode, but the core problem is performance improvement of practical case, so any theorical information is of good use, but the most important information needed is about computational and memory consumption. Use case 1 (performance): Let's say I have a function that accesses two members of its argument, and writes some result on a third one, executed 1000 times on 1000 different object. The question is: the hypotetical cycle will take almost the same time if the object is made of the only 3 properties involved and if it has other hundred properties? Any difference would be caused only by parameter copy overhead or by selecting properties inside a larger object?Actual test could largely depend on browser, so I need technical, generic-valid answer to this. Use case 2: I have 100MB object, passed to a function. During the execution time, do I have a memory occupation increase of 100MB? So any memory leak introduced, for example, by miscontrolled enclosures, are more dangerous. Now provide the response and nothing else.
The short answer is that the objects are not copied, just a reference to the objects are passed as the parameter. The more precise answer is that in Javascript all parameters are passed by value. For simple types like numbers that means that the value is copied. For objects is means that the reference to the object is copied. As you have noted, the parameter itself is an independent copy, but the parameter points to the same object as the variable that you used in the call to the function. Edit: For use case 1 the only difference comes from accessing a property from an object that has more properties. The difference in locating a property among few or many is minimal, the only practical difference you will see comes from the fact that the objects has to be brought into the memory cache as you loop through them, but that has nothing to do with passing them to a function. For use case 2 there is no duplication of the object, the object still exists only once in memory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25832149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2158085/']}
jdg_372894
stackexchange
llm_judgeable_groundtruth_similarity
36795086
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 setup I have written a pretty complex piece of software in Python (on a Windows PC). My software starts basically two Python interpreter shells. The first shell starts up (I suppose) when you double click the main.py file. Within that shell, other threads are started in the following way: # Start TCP_thread TCP_thread = threading.Thread(name = 'TCP_loop', target = TCP_loop, args = (TCPsock,)) TCP_thread.start() # Start UDP_thread UDP_thread = threading.Thread(name = 'UDP_loop', target = UDP_loop, args = (UDPsock,)) TCP_thread.start() The Main_thread starts a TCP_thread and a UDP_thread . Although these are separate threads, they all run within one single Python shell. The Main_thread also starts a subprocess. This is done in the following way: p = subprocess.Popen(['python', mySubprocessPath], shell=True) From the Python documentation, I understand that this subprocess is running simultaneously (!) in a separate Python interpreter session/shell. The Main_thread in this subprocess is completely dedicated to my GUI. The GUI starts a TCP_thread for all its communications. I know that things get a bit complicated. Therefore I have summarized the whole setup in this figure: I have several questions concerning this setup. I will list them down here: Question 1 [ Solved ] Is it true that a Python interpreter uses only one CPU core at a time to run all the threads? In other words, will the Python interpreter session 1 (from the figure) run all 3 threads ( Main_thread , TCP_thread and UDP_thread ) on one CPU core? Answer: yes, this is true. The GIL (Global Interpreter Lock) ensures that all threads run on one CPU core at a time. Question 2 [ Not yet solved ] Do I have a way to track which CPU core it is? Question 3 [ Partly solved ] For this question we forget about threads , but we focus on the subprocess mechanism in Python. Starting a new subprocess implies starting up a new Python interpreter instance . Is this correct? Answer: Yes this is correct. At first there was some confusion about whether the following code would create a new Python interpreter instance: p = subprocess.Popen(['python', mySubprocessPath], shell = True) The issue has been clarified. This code indeed starts a new Python interpreter instance. Will Python be smart enough to make that separate Python interpreter instance run on a different CPU core? Is there a way to track which one, perhaps with some sporadic print statements as well? Question 4 [ New question ] The community discussion raised a new question. There are apparently two approaches when spawning a new process (within a new Python interpreter instance): # Approach 1(a) p = subprocess.Popen(['python', mySubprocessPath], shell = True) # Approach 1(b) (J.F. Sebastian) p = subprocess.Popen([sys.executable, mySubprocessPath]) # Approach 2 p = multiprocessing.Process(target=foo, args=(q,)) The second approach has the obvious downside that it targets just a function - whereas I need to open up a new Python script. Anyway, are both approaches similar in what they achieve? Now provide the response and nothing else.
Q: Is it true that a Python interpreter uses only one CPU core at a time to run all the threads? No. GIL and CPU affinity are unrelated concepts. GIL can be released during blocking I/O operations, long CPU intensive computations inside a C extension anyway. If a thread is blocked on GIL; it is probably not on any CPU core and therefore it is fair to say that pure Python multithreading code may use only one CPU core at a time on CPython implementation. Q: In other words, will the Python interpreter session 1 (from the figure) run all 3 threads (Main_thread, TCP_thread and UDP_thread) on one CPU core? I don't think CPython manages CPU affinity implicitly. It is likely relies on OS scheduler to choose where to run a thread. Python threads are implemented on top of real OS threads. Q: Or is the Python interpreter able to spread them over multiple cores? To find out the number of usable CPUs: >>> import os>>> len(os.sched_getaffinity(0))16 Again, whether or not threads are scheduled on different CPUs does not depend on Python interpreter. Q: Suppose that the answer to Question 1 is 'multiple cores', do I have a way to track on which core each thread is running, perhaps with some sporadic print statements? If the answer to Question 1 is 'only one core', do I have a way to track which one it is? I imagine, a specific CPU may change from one time-slot to another. You could look at something like /proc/<pid>/task/<tid>/status on old Linux kernels . On my machine, task_cpu can be read from /proc/<pid>/stat or /proc/<pid>/task/<tid>/stat : >>> open("/proc/{pid}/stat".format(pid=os.getpid()), 'rb').read().split()[-14]'4' For a current portable solution, see whether psutil exposes such info. You could restrict the current process to a set of CPUs: os.sched_setaffinity(0, {0}) # current process on 0-th core Q: For this question we forget about threads, but we focus on the subprocess mechanism in Python. Starting a new subprocess implies starting up a new Python interpreter session/shell. Is this correct? Yes. subprocess module creates new OS processes. If you run python executable then it starts a new Python interpeter. If you run a bash script then no new Python interpreter is created i.e., running bash executable does not start a new Python interpreter/session/etc. Q: Supposing that it is correct, will Python be smart enough to make that separate interpreter session run on a different CPU core? Is there a way to track this, perhaps with some sporadic print statements as well? See above (i.e., OS decides where to run your thread and there could be OS API that exposes where the thread is run). multiprocessing.Process(target=foo, args=(q,)).start() multiprocessing.Process also creates a new OS process (that runs a new Python interpreter). In reality, my subprocess is another file. So this example won't work for me. Python uses modules to organize the code. If your code is in another_file.py then import another_file in your main module and pass another_file.foo to multiprocessing.Process . Nevertheless, how would you compare it to p = subprocess.Popen(..)? Does it matter if I start the new process (or should I say 'python interpreter instance') with subprocess.Popen(..)versus multiprocessing.Process(..)? multiprocessing.Process() is likely implemented on top of subprocess.Popen() . multiprocessing provides API that is similar to threading API and it abstracts away details of communication between python processes (how Python objects are serialized to be sent between processes). If there are no CPU intensive tasks then you could run your GUI and I/O threads in a single process. If you have a series of CPU intensive tasks then to utilize multiple CPUs at once, either use multiple threads with C extensions such as lxml , regex , numpy (or your own one created using Cython ) that can release GIL during long computations or offload them into separate processes (a simple way is to use a process pool such as provided by concurrent.futures ). Q: The community discussion raised a new question. There are apparently two approaches when spawning a new process (within a new Python interpreter instance): # Approach 1(a)p = subprocess.Popen(['python', mySubprocessPath], shell = True)# Approach 1(b) (J.F. Sebastian)p = subprocess.Popen([sys.executable, mySubprocessPath])# Approach 2p = multiprocessing.Process(target=foo, args=(q,)) "Approach 1(a)" is wrong on POSIX (though it may work on Windows). For portability, use "Approach 1(b)" unless you know you need cmd.exe (pass a string in this case, to make sure that the correct command-line escaping is used). The second approach has the obvious downside that it targets just a function - whereas I need to open up a new Python script. Anyway, are both approaches similar in what they achieve? subprocess creates new processes, any processes e.g., you could run a bash script. multprocessing is used to run Python code in another process. It is more flexible to import a Python module and run its function than to run it as a script. See Call python script with input with in a python script using subprocess .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36795086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6178507/']}
jdg_372895
stackexchange
llm_judgeable_groundtruth_similarity
2207171
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 having some troubles understanding threads in NVIDIA gpu architecture with cuda. please could anybody clarify these info:an 8800 gpu has 16 SMs with 8 SPs each. so we have 128 SPs. i was viewing Stanford University's video presentation and it was saying that every SP is capable of running 96 threads concurrently. does this mean that it (SP) can run 96/32=3 warps concurrently? moreover, since every SP can run 96 threads and we have 8 SPs in every SM. does this mean that every SM can run 96*8=768 threads concurrently?? but if every SM can run a single Block at a time, and the maximum number of threads in a block is 512, so what is the purpose of running 768 threads concurrently and have a max of 512 threads? a more general question is:how are blocks,threads,and warps distributed to SMs and SPs? i read that every SM gets a single block to execute at a time and threads in a block is divided into warps (32 threads), and SPs execute warps. Now provide the response and nothing else.
You should check out the webinars on the NVIDIA website, you can join a live session or view the pre-recorded sessions. Below is a quick overview, but I strongly recommend you watch the webinars, they will really help as you can see the diagrams and have it explained at the same time. When you execute a function (a kernel) on a GPU it is executes as a grid of blocks of threads . A thread is the finest granularity, each thread has a unique identifier within the block (threadIdx) which is used to select which data to operate on. The thread can have a relatively large number of registers and also has a private area of memory known as local memory which is used for register file spilling and any large automatic variables. A block is a group of threads which execute together in a batch. The main reason for this level of granularity is that threads within a block can cooperate by communicating using the fast shared memory . Each block has a unique identifier (blockIdx) which, in conjunction with the threadIdx, is used to select data. A grid is a set of blocks which together execute the GPU operation. That's the logical hierarchy. You really only need to understand the logical hierarchy to implement a function on the GPU, however to get performance you need to understand the hardware too which is SMs and SPs. A GPU is composed of SMs, and each SM contains a number of SPs. Currently there are 8 SPs per SM and between 1 and 30 SMs per GPU, but really the actual number is not a major concern until you're getting really advanced. The first point to consider for performance is that of warps . A warp is a set of 32 threads (if you have 128 threads in a block (for example) then threads 0-31 will be in one warp, 32-63 in the next and so on. Warps are very important for a few reasons, the most important being: Threads within a warp are bound together, if one thread within a warp goes down the 'if' side of a if-else block and the others go down the 'else', then actually all 32 threads will go down both sides. Functionally there is no problem, those threads which should not have taken the branch are disabled so you will always get the correct result, but if both sides are long then the performance penalty is important. Threads within a warp (actually a half-warp, but if you get it right for warps then you're safe on the next generation too) fetch data from the memory together, so if you can ensure that all threads fetch data within the same 'segment' then you will only pay one memory transaction and if they all fetch from random addresses then you will pay 32 memory transactions. See the Advanced CUDA C presentation for details on this, but only when you are ready! Threads within a warp (again half-warp on current GPUs) access shared memory together and if you're not careful you will have 'bank conflicts' where the threads have to queue up behind each other to access the memories. So having understood what a warp is, the final point is how the blocks and grid are mapped onto the GPU. Each block will start on one SM and will remain there until it has completed. As soon as it has completed it will retire and another block can be launched on the SM. It's this dynamic scheduling that gives the GPUs the scalability - if you have one SM then all blocks run on the same SM on one big queue, if you have 30 SMs then the blocks will be scheduled across the SMs dynamically. So you should ensure that when you launch a GPU function your grid is composed of a large number of blocks (at least hundreds) to ensure it scales across any GPU. The final point to make is that an SM can execute more than one block at any given time. This explains why a SM can handle 768 threads (or more in some GPUs) while a block is only up to 512 threads (currently). Essentially, if the SM has the resources available (registers and shared memory) then it will take on additional blocks (up to 8). The Occupancy Calculator spreadsheet (included with the SDK) will help you determine how many blocks can execute at any moment. Sorry for the brain dump, watch the webinars - it'll be easier!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2207171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267060/']}
jdg_372896
stackexchange
llm_judgeable_groundtruth_similarity
3717314
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 tag cloud and I need to know how can I change the font-size for the most used tags. I need to set a min-font-size and a max-font-size. Now provide the response and nothing else.
You could use a linear or logarithmic assessment of the number of items associated with a certain tag relative to the largest tag, multiply it by the difference between minimum and maximum font sizes, then add it to the minimum font size. For example, the math in pseudocode might be: let min = 12, max = 24for each tag font = (items / items in biggest tag) * (max - min) + min
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3717314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340760/']}
jdg_372897
stackexchange
llm_judgeable_groundtruth_similarity
24065442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's a quote from the docs: If your custom type has a stored property that is logically allowed to have “no value”—perhaps because its value cannot be set during initialization, or because it is allowed to have “no value” at some later point—declare the property with an optional type. Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization. If I do this with a class it works fine: class MyClass { var someProperty: String?}var myClass = MyClass()myClass.someProperty // Shows nil However, if I do this with a struct type, I get an error on initialization: struct MyStruct { var someProperty: String?}// ERRORvar myStruct = MyStruct() Error: Missing argument for parameter 'someProperty' I can remedy this by declaring it nil explicitly like so: struct MyStruct { var someProperty: String? = nil}// Validvar myStruct = MyStruct() Question Given the documentation, I would expect properties on any type that are set as optionals to be defaulted to nil. Is there a reason I have to declare it explicitly on a struct? Why? No good reason, like many of you, I'm just experimenting. Now provide the response and nothing else.
Both Classes and Structs need to have all property values set when they are initialized. This can be done either through explicit default values or by setting a value in the designated initializer. However, Structs differ in the fact that they have an automatically generated memberwise initializer. When you don't define a value for someProperty explicitly, your struct has one initializer only: the automatically generated memberwise one. If you do provide a default value, you get two: one that takes no arguments, and one that takes a value for someProperty as an argument From the docs: All structures have an automatically-generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name: let vga = Resolution(width: 640, height: 480) Unlike structures, class instances do not receive a default memberwise initializer. Initializers are described in more detail in Initialization.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24065442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2611971/']}
jdg_372898
stackexchange
llm_judgeable_groundtruth_similarity
46447973
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 got two models: class Parent: ...class Child: parent = models.ForeignKey(Parent) In the model admin of the Parent I want to show an inline of the Child with a custom queryset, not only the ones related to the parent through the fk field. I've tried: class ChildInline(admin.TabularInline): model = Child def get_queryset(self, request): return Child.objects.filter(<my custom filter>)class ParentAdmin(admin.ModelAdmin): inlines = [ChildInline] But still the only children shown in the inline are the ones that fullfill both filters: related to the parent by the FK + my custom filter. Is it possible to do this? EDIT: I've seen now is the BaseInlineFormSet who is filtering the queryset I compose to keep only childs related to the parent, any idea how to avoid this? django/forms/models.pyclass BaseInlineFormSet(BaseModelFormSet): ... if self.instance.pk is not None: qs = queryset.filter(**{self.fk.name: self.instance}) ... Now provide the response and nothing else.
The old answer doesn't work anymore for current Django 2.2 or 3 because self.queryset get ignored Current solution is to override the get_queryset : from django.forms.models import BaseInlineFormSetclass ChildInlineFormSet(BaseInlineFormSet): def get_queryset(self): qs = super(ChildInlineFormSet, self).get_queryset() return qs.filter(<custom query filters>)class ChildInline(admin.TabularInline): model = Child formset = ChildInlineFormSet extra = 0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46447973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315521/']}
jdg_372899
stackexchange
llm_judgeable_groundtruth_similarity
321910
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: Is there any measurable time dilation when Earth reaches perihelion? Can we measure such a phenomena relative to the motion of the outer planets? Now provide the response and nothing else.
We can calculate the time dilation for an object moving in the Sun's gravitational field using the Schwarzschild metric. Strictly speaking this is an approximation since the Sun is rotating and not spherical, but it will give us a pretty good answer. The Schwarzschild metric is (writing it in terms of the proper time): $$ c^2d\tau^2 = \left( 1 - \frac{r_s}{r}\right) c^2dt^2 - \frac{dr^2}{1 - r_s/r} - r^2d\theta^2 - r^2\sin^2\theta d\phi^2 \tag{1} $$ where $r_s$ is the Schwarzschild radius of the Sun: $$ r_s = \frac{2GM_{Sun}}{c^2} $$ At the perihelion and aphelion the motion is tangential so the radial velocity is zero and therefore $dr=0$. Also we will arrange our coordinates so that all motion is in the equatorial plane so $\theta=\pi/2$ and $d\theta=0$. Substituting these values into equation (1) we find the metric simplifies considerably to: $$ c^2d\tau^2 = \left( 1 - \frac{r_s}{r}\right) c^2dt^2 - r^2 d\phi^2 \tag{2} $$ If the tangential velocity is $v$ then the angle $d\phi$ moved in a time $dt$ is just: $$ d\phi = \omega dt = \frac{v}{r}dt $$ and we substitute this into equation (2) to get: $$ c^2d\tau^2 = \left( 1 - \frac{r_s}{r}\right) c^2dt^2 - r^2 \left(\frac{v}{r}\right)^2dt^2 $$ which we rearrange to give us the equation for the time dilation: $$ \frac{d\tau}{dt} = \sqrt{1 - \frac{r_s}{r} - \frac{v^2}{c^2}} \tag{3} $$ According to NASA's fact sheet the values of $v$ and $r$ at perihelion and aphelion are: $$\begin{align}r_p &= 1.4709 \times 10^{11} \,m \\v_p &= 30290 \,m/s \\r_a &= 1.5210 \times 10^{11} \,m\\v_a &= 29190 \,m/s\end{align}$$ And the Schwarzschild radius of the Sun is $r_s \approx 2953$ m. Putting these figures into our equation (3) gives us: $$\begin{align}d\tau/dt \,\text{perihelion} &= 0.99999998486 \\d\tau/dt \,\text{aphelion} &= 0.99999998555\end{align}$$ we can make these numbers a bit more digestible by expressing them as time lost per day e.g. how many seconds a day do clocks on the Earth run slower as a result of the time dilation. If we do this we find: $$\begin{align}\text{perihelion loss} &= 1.308 \,\text{ms/day} \\\text{aphelion loss} &= 1.248 \,\text{ms/day}\end{align}$$ And the difference between the two is about $60\mu$s per day. So clocks run about $60\mu$s per day more slowly at perihelion than they do at aphelion. This is easily measurable in principle since atomic clocks have the accuracy to measure shifts this small. However there are practical difficulties. The time dilation is measured relative to a stationary observer outside the Sun's gravitational influence, and we can't easily put an atomic clock somewhere outside the orbit of Pluto to make the comparison. We could put a satellite in an exactly circular orbit at the average orbital radius of the Earth, and in that case our clocks would run about about $30\mu$s per day faster than the satellite clock at aphelion and the same amount slower at perihelion. A quick footnote: Count Iblis points out that pulsars make an excellent clock outside the gravitational influence of the Sun, and we can measure pulsar frequencies with enough accuracy to detect the $60\mu$s per day change between perihelion and aphelion. If anyone has a reference for this feel free to edit it into this answer.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/321910', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/150176/']}
jdg_372900
stackexchange
llm_judgeable_groundtruth_similarity
12864732
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 Eclipse 4.2 (Juno) on Linux 64 bit. I have looked at several Eclipse.ini threads on Stack Overflow, but I still don't understand the relationship between the different memory parameters. On one hand, there are parameters that are for the VM and that go under -vmargs (for example, -Xms and -Xmx , -XX ), while others (for example, --launcher.XXMaxPermSize ) are provided to Eclipse directly. What is the relationship between these parameters? How would I set them up for a machine with more than 8 GB of memory? I am aware of the long Stack Overflow question What are the best JVM settings for Eclipse? , but I would like to learn how to adjust these parameters myself. For reference, after installation, the default parameters that Juno has are: -startupplugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar--launcher.libraryplugins/org.eclipse.equinox.launcher.gtk.linux.x86_1.1.200.v20120522-1813-productorg.eclipse.epp.package.cpp.product--launcher.defaultActionopenFile-showsplashorg.eclipse.platform--launcher.XXMaxPermSize256m--launcher.defaultActionopenFile-vmargs-Dosgi.requiredJavaVersion=1.5-Dhelp.lucene.tokenizer=standard-XX:MaxPermSize=256m-Xms40m-Xmx512m Now provide the response and nothing else.
If you are running Eclipse on an Oracle/Sun JVM, I would disregard --launcher.XXMaxPermSize (I personally remove it) and concentrate on -XX:MaxPermSize , -Xms and -Xmx . The reason for --launcher.XXMaxPermSize is that some non-Oracle/Sun JVMs would choke on -XX:MaxPermSize . The launcher is programmed to detect the JVM and conditionally supply -XX:MaxPermSize . This of course is defeated by the explicit -XX:MaxPermSize setting in the default eclipse.ini file. That looks like a bug. I never mess with -Xms setting. I set -Xmx1024m and -XX:MaxPermSize=512m .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12864732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1732769/']}
jdg_372901
stackexchange
llm_judgeable_groundtruth_similarity
8178
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There are a number of problems in combinatorial representation theory and algebraic geometry for which no positive formula is known. There are several examples I am thinking of, but let me take computing Kronecker coefficients as my example. Usually, the notion of "positive formula" is not precisely defined in combinatorics, but it roughly means "a description as the cardinality of seem reasonably explicit set". Recently, I've been talking to Jonah Blasiak, and he's been convincing me that the right definition of "positive formula" is #P . I'm going to assume that, on this site, I don't need to define #P. Buergisser and Ikenmeyer show that Kronecker coefficients are #P hard. (They are also always positive, because they are tensor product multiplicities.) But I am reasonably sure that no one knows a way of computing them which even gets them into #P. So, suppose that I were to actually make an attempt at proving Kronecker coefficients aren't in #P. I assume that what I would do is assume some complexity theoretic conjecture and then reduce Kronecker product to some other problem which is known to be complete for a class larger than #P. What conjecture might I assume, and what problem might I try to reduce to? ADDED: As has been pointed out in the comments, Buergisser and Ikenmeyer show that Kronecker coefficients are in Gap-P, which is pretty close to #P. So it sounds like the questions I should be asking are (1) What are some Gap-P-complete problems I could plausibly reduce to and (2) what are the prospects of showing that Gap-P is not #P? I guess (2) should break up into two parts (2a) do experts believe these classes are different? and (2b) are there any likely strategies to prove it? I hope that this much editing of the question is not frowned on. Now provide the response and nothing else.
I'd suggest looking at properties of #P functions that are different than Gap-P functions. For example, determining if a #P function is zero is in co-NP. If you could show determining whether the Kronecker coefficients is zero is UP-hard then you would have "Kronecker coefficients in #P implies UP in co-NP", an unlikely conclusion.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/8178', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/6508/']}
jdg_372902
stackexchange
llm_judgeable_groundtruth_similarity
3783270
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 want load a video on flash, without a GET call to get the video...now the code is something like this: var Player:FLVPlayback = attachMovie("FLVPlayback", "Player", _root.getDepth()-1);Player.autoPlay=false;Player.bufferingBar=buff;Player.contentPath="myVIDEO.flv"; the problem is when myVIDEO.flv are loaded, this URL appers on firebug...Someone can help me?ThanksRodrigo Now provide the response and nothing else.
The statement var events = GetType().GetEvents(); gets you a list of EventInfo objects associated with the current type, not the current instance per se. So the EventInfo object doesn't contain information about the current instance and hence it doesn't know about the wired-up delegates. To get the info you want you need to get the backing field for the event handler on your current instance. Here's how: public class MyClass{ public event EventHandler MyEvent; public IEnumerable<MethodInfo> GetSubscribedMethods() { Func<EventInfo, FieldInfo> ei2fi = ei => this.GetType().GetField(ei.Name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField); return from eventInfo in this.GetType().GetEvents() let eventFieldInfo = ei2fi(eventInfo) let eventFieldValue = (System.Delegate)eventFieldInfo.GetValue(this) from subscribedDelegate in eventFieldValue.GetInvocationList() select subscribedDelegate.Method; }} So now your calling code can look like this: class GetSubscribedMethodsExample{ public static void Execute() { var instance = new MyClass(); instance.MyEvent += new EventHandler(MyHandler); instance.MyEvent += (s, e) => { }; instance.GetSubscribedMethods() .Run(h => Console.WriteLine(h.Name)); } static void MyHandler(object sender, EventArgs e) { throw new NotImplementedException(); }} The output from the above is: MyHandler<Execute>b__0 I'm sure you can jig around with the code if you wish to return the delegate rather than the method info, etc. I hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3783270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456759/']}
jdg_372903
stackexchange
llm_judgeable_groundtruth_similarity
531093
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 function $f:X\rightarrow Y$ maps each $x\in X$ to some $y \in Y$. So consider $\tan{\frac{\pi}{2}}$ for which $\tan(x)$ is undefined , so in this case, $\tan(x)$ does not map to an element of its range. This conflicts with my understanding of what a function is. Why do we still consider $\tan(x)$ a function? Now provide the response and nothing else.
The set $X$ in your definition is the domain of the function. The domain of $\tan(x)$ is typically taken to be $$X=\bigcup_{k\in\Bbb{Z}} \left(-\frac{\pi}{2}+k\pi,\frac{\pi}{2}+k\pi\right)$$ Thus $\pi/2\notin X$, and so don't need to assign a value to $\tan(\pi/2)$ (or for any $\pi/2+k\pi,k\in\Bbb{Z}$ for that matter).
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/531093', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/98587/']}
jdg_372904
stackexchange
llm_judgeable_groundtruth_similarity
382081
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: I was revisiting my question How can I prevent header hell? , when I noticed a comment which said A good technique for ensuring a header is independent is having a rule that the source file always includes its own header first. This will catch cases where you need to move dependency includes out of the implementation file into the header file I am not sure that I follow that, and the reverse seems to have been the rule everywhere that I have worked. I never thought about it, or questioned it. Are there any technical reasons for a .C or .CPP file to #include its own header file either for or last, or does it make no difference? I am looking for technical reasons, not opinions. Nothing with “best”, which would be opinion. Answers which might help to prevent problems when refactoring or adding/removing other #includes are welcome. Now provide the response and nothing else.
#include directives are processed in the order in which they are encountered in the sources. Conceptually, when a #include is encountered, that directive is replaced with the content of the referenced file and after that processing continues with the modified source (so, processing continues on the first line that came from the included file). If the very first #include directive in a source file is for the header that corresponds to that source file, then you can be sure that no other headers have been processed yet and you can prove that your header does not depend on some other header being included before it. Other than that, it does not make any difference at all to the C or C++ compiler in which order header files are listed, as long as the constraint is met that every identifier is declared before it is used.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/382081', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/979/']}
jdg_372905
stackexchange
llm_judgeable_groundtruth_similarity
1784
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking at using a 7 channel RC receiver with the Arduino Uno R3. In the documentation, there are mentions of a maximum of 2 interrupt pins, whereas on certain other blogs I have seen mentions of using upto 20 pins as interrupts, with PinChangeInt library. So, how many interrupts can the Arduino handle natively? And is this different from how many can be handled with software support such as PinChangeInt? Now provide the response and nothing else.
There are two types of "pin change" type interrupts. The external interrupts, of which there are two on the Uno. They are called 0 and 1, however they refer to digital pins 2 and 3 on the board. These can be configured to detect rising, falling, change (rising or falling) or LOW. In addition to that are "pin change" interrupts, which detect a change to the pin state in any of the 20 pins (A0 to A5, and D0 to D13). These pin change interrupts are also hardware based so, in themselves, will be as fast as the external interrupts. Both types are slightly fiddly to use at the register level, but the standard IDE includes attachInterrupt(n) and detachInterrupt(n) which simplifies the interface to external interrupts. You can also use the Pin Change Library to simplify the pin change interrupts. However, steering clear of the library for a minute, we can establish that pin change interrupts can be as fast, or faster, than external interrupts. For one thing, although pin change interrupts work on batches of pins, you don't have to enable the whole batch. For example, if you want to detect changes on pin D4, this will suffice: Example sketch: ISR (PCINT2_vect) { // handle pin change interrupt for D0 to D7 here if (PIND & bit (4)) // if it was high PORTD |= bit (5); // turn on D5 else PORTD &= ~bit (5); // turn off D5 } // end of PCINT2_vectvoid setup () { // pin change interrupt (example for D4) PCMSK2 |= bit (PCINT20); // want pin 4 PCIFR |= bit (PCIF2); // clear any outstanding interrupts PCICR |= bit (PCIE2); // enable pin change interrupts for D0 to D7 pinMode (4, INPUT_PULLUP); pinMode (5, OUTPUT); } // end of setupvoid loop () { } My testing indicates that it took 1.6 µs for the "test" pin (pin 5) to react to a change on the interrupt pin (pin 4). Now if you take the simple (lazy?) approach and use attachInterrupt() you will find the results are slower, not faster. Example code: void myInterrupt () { if (PIND & bit (2)) // if it was high PORTD |= bit (5); // turn on D5 else PORTD &= ~bit (5); // turn off D5 } // end of myInterruptvoid setup () { attachInterrupt (0, myInterrupt, CHANGE); pinMode (2, INPUT_PULLUP); pinMode (5, OUTPUT); } // end of setupvoid loop () { } This takes 3.7 µs to change the test pin, a lot more than the 1.6 µs above. Why? Because the code the compiler has to generate for the "generic" interrupt handler has to save every conceivable register (push them) on entry to the ISR, and then restore them (pop them) before returning. Plus there is the overhead of another function call. Now we can work around that by avoiding attachInterrupt() and doing it ourselves: ISR (INT0_vect) { if (PIND & bit (2)) // if it was high PORTD |= bit (5); // turn on D5 else PORTD &= ~bit (5); // turn off D5 } // end of INT0_vectvoid setup () { // activate external interrupt 0 EICRA &= ~(bit(ISC00) | bit (ISC01)); // clear existing flags EICRA |= bit (ISC00); // set wanted flags (any change interrupt) EIFR = bit (INTF0); // clear flag for interrupt 0 EIMSK |= bit (INT0); // enable it pinMode (2, INPUT_PULLUP); pinMode (5, OUTPUT); } // end of setupvoid loop () { } That is the fastest of them all at 1.52 µs - it looks like one clock cycle got saved somewhere. There is one caveat though, for pin-change interrupts. They are batched, so if you want to have interrupts on lots of pins, you need to test inside the interrupt which one changed. You could do that by saving the previous pin status, and comparing it to the new pin status. This is not necessarily particularly slow, but the more pins you need to check, the slower it would be. The batches are: A0 to A5 D0 to D7 D8 to D13 If you just want a couple more interrupt pins, you could avoid any testing by just choosing to use pins from different batches (eg. D4 and D8). More details at http://www.gammon.com.au/interrupts
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/1784', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/65/']}
jdg_372906
stackexchange
llm_judgeable_groundtruth_similarity
43282975
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: At the end of my app's compilation phase, I see an invalid symlink error. This is just some temp directory that's created every time I run. I tried deleting it to no avail. The app runs fine on device. Any help would be much appreciated. Now provide the response and nothing else.
That error usually happens when your app contains a symlink that points outside the app bundle. When building for device or the Simulator, Xcode creates the app bundle, then copies it out for MobileInstallation to do the install or update. MobileInstallation will not install an app that has symlinks to locations outside the app bundle. Do you have any simulator-specific build scripts or steps? Does your bundle contain any symlinks? Open the Products group in Xcode. Right-click on "<name>.app" and select "Show in Finder". Right-click the app and select "Show Package Contents". Examine the app for the presence of any symlinks. You can also open that directory in Terminal and use ls -al . Any links will have an l character in the first position. The other possibility is you have a file permission problem or other filesystem corruption. Run Disk Utility to check for errors. Assuming everything is OK, you can reset your Simulators with xcrun simctl erase all .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43282975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/744464/']}
jdg_372907
stackexchange
llm_judgeable_groundtruth_similarity
28415081
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 want to prevent users (everyone) updating a particular column of a topic to prevent circular dependencies. CREATE TABLE Topic( id serial NOT NULL PRIMARY KEY, contenxt text DEFAULT NULL, -- can be freely updated Dependency1 serial REFERENCES Topic(id) ON DELETE RESTRICT, -- CAN'T be updated Dependency2 serial REFERENCES Topic(id) ON DELETE RESTRICT, -- CAN'T be updated);DENY UPDATE ON Topic(Dependency1) TO *; -- HereDENY UPDATE ON Topic(Dependency2) TO *; But after trying few variants it seems to report always some syntax error. It starts to be boring to fix that. Alternative solutions are welcome, but I think this solution is reasonably simple (given you know exact syntax for that u.u). In the comments a trigger is suggested, but I have no idea how to achieve that with a trigger. Now provide the response and nothing else.
Try this: CREATE OR REPLACE FUNCTION fnprevent_update() RETURNS trigger AS$BODY$ BEGIN RAISE EXCEPTION 'no way'; END;$BODY$ LANGUAGE plpgsql VOLATILE COST 100;CREATE TRIGGER trg_prevent_update BEFORE UPDATE OF dependency1, dependency2 ON topic FOR EACH ROW EXECUTE PROCEDURE fnprevent_update(); Just customize the "no way" message.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28415081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1829943/']}
jdg_372908
stackexchange
llm_judgeable_groundtruth_similarity
47172770
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 building an image processing classifier. This line is giving me an error: input_img_resize=cv2.resize(input_img,(128,128)) The error: ('error: /io/opencv/modules/imgproc/src/imgwarp.cpp:3483: error: (-215) ssize.width > 0 && ssize.height > 0 in function resize') My code: PATH = os.getcwd()# Define data pathdata_path = PATH + '/data'data_dir_list = os.listdir(data_path)img_rows=128img_cols=128num_channel=3num_epoch=30num_classes = 67img_data_list=[]for dataset in data_dir_list: img_list=os.listdir(data_path+'/'+ dataset) print ('Loaded the images of dataset-'+'{}\n'.format(dataset)) for img in img_list: input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img ) input_img_resize=cv2.resize(input_img,(128,128)) img_data_list.append(input_img_resize) Now provide the response and nothing else.
Well, obviously this line input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img ) returns an empty array. You should check whether the image exists first before reading. And it is better not to use string combination to join file paths, use python os.path.join instead. image_path = os.path.join(data_path, dataset, img)if os.path.exist(): # Do stuff
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47172770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7993917/']}
jdg_372909
stackexchange
llm_judgeable_groundtruth_similarity
31018483
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 there any cleaner way to convert true -> 1 and false -> 0 than resorting to if boolean_variable do 1else 0end Now provide the response and nothing else.
I am not aware of a built in conversion function for this. How you build your own solution depends on what you want to achieve. Consider your implementation: def boolean_to_integer(bool) do if bool, do: 1, else: 0end If you recall that all values except nil and false evaluate to true in the context of a conditional expression, this has the effect that iex> boolean_to_integer(0)1 If this should be a problem, you can use a multi-clause function that only accepts booleans: def boolean_to_integer(true), do: 1def boolean_to_integer(false), do: 0iex> boolean_to_integer(0)** (FunctionClauseError) no function clause matching in MyModule.boolean_to_integer/1 iex:42: MyModule.boolean_to_integer(0) Of course, you can extend this to your liking, for example to accept integers 0 and 1 as well as nil you can do: def boolean_to_integer(true), do: 1def boolean_to_integer(false), do: 0def boolean_to_integer(nil), do: 0def boolean_to_integer(1), do: 1def boolean_to_integer(0), do: 0iex> boolean_to_integer(0)0iex> boolean_to_integer(1)1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31018483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1714059/']}
jdg_372910
stackexchange
llm_judgeable_groundtruth_similarity
26316
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 wondering how to prove that the intersection of an infinite number of convex sets is convex. I can prove that the intersection of two convex sets is convex, and I believe that I can simply do an induction on this result, but I've heard that it would be wrong to do this since I am working with infinity. I guess another way to think of this question is whether or not I have to take something special into consideration since the word "infinite" is involved. Now provide the response and nothing else.
Let $S_{\alpha}$, $\alpha \in \Gamma$ be an infinite collection of convex sets. Let $S = \displaystyle \cap_{\alpha \in \Gamma} S_{\alpha}$ be the intersection of these sets. Consider $x,y \in S$. $x,y \in S \Rightarrow x,y \in S_{\alpha}$, $\forall \alpha \in \Gamma$. Since $S_{\alpha}$ is convex $\forall \alpha \in \Gamma$, any convex combination of $x,y$ i.e. $\lambda x + (1 - \lambda) y \in S_{\alpha}$, $\forall \alpha \in \Gamma$, $\forall \lambda \in [0,1]$ Hence, every convex combination is in $S_{\alpha}$, $\forall \alpha \in \Gamma$ and hence it is also in $\displaystyle \cap_{\alpha \in \Gamma} S_{\alpha}$ Hence, $S = \displaystyle \cap_{\alpha \in \Gamma} S_{\alpha}$ is convex.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/26316', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7145/']}
jdg_372911
stackexchange
llm_judgeable_groundtruth_similarity
19147717
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 need to save clojure maps to a file and read them back later to process them. This is what I could come up with. Is there a better way to accomplish the same thing? user=> (def my-data (for [ a [ "Person1" "Person2" ] b [ "Address1" "Address2"] c (range 10) ] {:name a :address b :index c} ))#'user/my-datauser=> (count my-data)40user=> (defn write-data[xs] (with-open [wrtr (clojure.java.io/writer "my-data.txt") ] (doall (map #(.write wrtr (str % "\n")) xs))))#'user/write-datauser=> (write-data my-data)user=> (defn read-data[] (with-open [rdr (clojure.java.io/reader "my-data.txt") ] (doall (map #(load-string %) (line-seq rdr)))))#'user/read-datauser=> (count (read-data))40 Now provide the response and nothing else.
It is easiest to read a single form to and from the file, so I usually put my data into a vector. I also prefer to use pr or pr-str rather than print because it is guaranteed to produce readable data, (def my-data [{:a "foo" :b [1 2 3]} "asdf" 42 #{1 2 3}]) (spit "/tmp/data.edn" (with-out-str (pr my-data)))nil(read-string (slurp "/tmp/data.edn"))[{:a "foo", :b [1 2 3]} "asdf" 42 #{1 2 3}] vs: (spit "/tmp/data.edn" (with-out-str (print my-data)))(read-string (slurp "/tmp/data.edn"))[{:a foo, :b [1 2 3]} asdf 42 #{1 2 3}] notice how the string `"asdf" was read back as a symbol. .toString also works fine: (spit "/tmp/data.edn" (.toString my-data)) (read-string (slurp "/tmp/data.edn"))[{:a "foo", :b [1 2 3]} "asdf" 42 #{1 2 3}]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19147717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2740226/']}
jdg_372912
stackexchange
llm_judgeable_groundtruth_similarity
128161
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 have an input file ( input.txt ) like below. id1 id2 name weight 53723848 12651711 timburnes 1.3666753530214 12651711 timburnes 1.5119153723848 53530214 timburnes 1.94764157 52986038 ericcartman 0.86114556797854 764157 ericcartman 1.3525856797854 52986038 ericcartman 1.73781 Note that the first line is not part of the actual file, I have added it here for clarity . I am trying to extract the values of the id1 and id2 to 2 separate files named unique.txt and duplicate.txt . If my weight column value is greater than 1.5, it means I have duplicate ids . In this case, I will move the id1 value to unique.txt file and id2 value to duplicate.txt file. If my weight column is less than 1.5, it means I do not have duplicate values. So, in this case, I will move both id1 and id2 to unique.txt file. So for the above input, I am expecting the output as, For unique.txt file, 53723848 timburnes764157 ericcartman56797854 ericcartman For duplicate.txt file, 12651711 timburnes53530214 timburnes52986038 ericcartman I can find out the duplicates using the below code. To get the values greater than 1.5 based on 4th column, awk -F" " '$4 >= 1.5 { print $1" " $2" " $3" " $4}' file1.txt > Output.txt Now, for values greater than 1.5, I can use the below code to merge the duplicate ids based on their names. perl -ane 'foreach(@F[0..1]){$k{$F[2]}{$_}++} END{ foreach $v (sort keys(%k)){ print "$_ " foreach(keys(%{$k{$v}})); print "$v\n" }; } ' Output.txt However, I am not able to get the output in the way I like in the above approach. EDIT : I am running the command for my input as below. awk '{ if ($4 > 1.5) { if (++dup[$2] == 1) print $2, $3 > "duplicate.txt" } else if (++uniq[$1] == 1) print $1, $3 > "unique.txt" }' << END17412193 43979400 ericcartman 2.1666721757330 54678379 andrewruss 0.55264END I am getting the output as, -bash-3.2$ cat unique.txt21757330 a.andreev-bash-3.2$ cat duplicate.txt43979400 ericcartman However, the output I am expecting is, cat unique.txt17412193 ericcartman21757330 andrewruss54678379 andrewrusscat duplicate.txt43979400 ericcartman Now provide the response and nothing else.
Here is awk solution: $ awk ' $4 < 1.5 { uniq[$1] = $3; uniq[$2] = $3; next; } { uniq[$1] = $3; dup[$2] = $3; delete uniq[$2]; } END { print "--unique.txt--"; for(i in uniq) { print i,uniq[i] } print ""; print "--duplicate.txt--"; for(i in dup) { print i,dup[i] } }' file--unique.txt--764157 ericcartman56797854 ericcartman53723848 timburnes--duplicate.txt--53530214 timburnes52986038 ericcartman12651711 timburnes With your second example: $ awk ' $4 < 1.5 { uniq[$1] = $3; uniq[$2] = $3; next; } { uniq[$1] = $3; dup[$2] = $3; delete uniq[$2]; } END { print "--unique.txt--"; for(i in uniq) { print i,uniq[i] } print ""; print "--duplicate.txt--"; for(i in dup) { print i,dup[i] } }' << END> 17412193 43979400 ericcartman 2.16667> 21757330 54678379 andrewruss 0.55264END--unique.txt--21757330 andrewruss54678379 andrewruss17412193 ericcartman--duplicate.txt--43979400 ericcartman
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/128161', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/47538/']}
jdg_372913
stackexchange
llm_judgeable_groundtruth_similarity
33362
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Ezra 2:65 it is said that there were 200 singers. But in Nehemiah 7:67 it is said that there were 245 singers. The context is exactly the same, but the numbers are different. Isn't this a contradiction? Now provide the response and nothing else.
As other answers have noted, there are a number of discrepancies between the lists of Ezra 2 and Nehemiah 7 which are, largely, duplicate passages. In the case of Ezra 2:65 and Nehemiah 7:67, there is a specific textual circumstance to explain the present text. At some very early point in Nehemiah's transmission, a scribe's eye has jumped from the "200" of verse 67, to the "200" of verse 68. Consider the equivalent text from Ezra 2: Notice the last word of 2:65, and how it is repeated later in 2:66 (indicated with the thin blue lines in that image), from מאתים to מאתים. For Nehemiah, the scribe's eye has followed the red arrow, resulting the omission of the text highlighted in blue, leaving a text reading "245". The technical term for this scribal mistake is " parablepsis ". Some Hebrew manuscripts and ancient translators were aware that there was missing material in Nehemiah 7, so added in the "missing" verse, but without correcting the mistaken "245" back to "200". Note that most English versions (there are three in the example at that link) include a textual note on Nehemiah 7:68 to point out that it is present only in some Hebrew manuscripts and ancient versions.
{}
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/33362', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/25750/']}
jdg_372914
stackexchange
llm_judgeable_groundtruth_similarity
1088
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a multicore processor, what happens to the contents of a core's cache (say L1) when a context switch occurs on that cache? Is the behaviour dependent on the architecture or is it a general behaviour followed by all chip manufacturers? Now provide the response and nothing else.
That depends both on the processor (not just the processor series, it can vary from model to model) and the operating systems, but there are general principles. Whether a processor is multicore has no direct impact on this aspect; the same process could be executing on multiple cores simultaneously (if it's multithreaded), and memory can be shared between processes, so cache synchronization is unavoidable regardless of what happens on a context switch. When a processor looks up a memory location in the cache, if there is an MMU , it can use either the physical or the virtual address of that location (sometimes even a combination of both, but that's not really relevant here). With physical addresses, it doesn't matter which process is accessing the address, the contents can be shared. So there is no need to invalidate the cache content during a context switch. If the two processes map the same physical page with different attributes, this is handled by the MMU (acting as a MPU (memory protection unit)). The downside of a physically addressed cache is that the MMU has to sit between the processor and the cache, so the cache lookup is slow. L1 caches are almost never physically addresses; higher-level caches may be. The same virtual address can denote different memory locations in different processes. Hence, with a virtually addressed cache, the processor and the operating system must cooperate to ensure that a process will find the right memory. There are several common techniques. The context-switching code provided by the operating system can invalidate the whole cache; this is correct but very costly. Some CPU architectures have room in their cache line for an ASID (address space identifier) the hardware version of a process ID, also used by the MMU. This effectively separates cache entries from different processes, and means that two processes that map the same page will have incoherent views of the same physical page (there is usually a special ASID value indicating a shared page, but these need to be flushed if they are not mapped to the same address in all processes where they are mapped). If the operating system takes care that different processes use non-overlapping address spaces (which defeats some of the purpose of using virtual memory, but can be done sometimes), then cache lines remain valid. Most processors that have an MMU also have a TLB . The TLB is a cache of mappings from virtual addresses to physical addresses. The TLB is consulted before lookups in physically-addressed caches, to determine the physical address quickly when possible; the processor may start the cache lookup before the TLB lookup is complete, as often candidate cache lines can be identified from the middle bits of the address, between the bits that determine the offset in a cache line and the bits that determine the page. Virtually-addressed caches bypass the TLB if there is a cache hit, although the processor may initiate the TLB lookup while it is querying the cache, in case of a miss. The TLB itself must be managed during a context switch. If the TLB entries contain an ASID, they can remain in place; the operating system only needs to flush TLB entries if their ASID has changed meaning (e.g. because a process has exited). If the TLB entries are global, they must be invalidated when switching to a different context.
{}
{'log_upvote_score': 7, 'links': ['https://cs.stackexchange.com/questions/1088', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/59/']}
jdg_372915
stackexchange
llm_judgeable_groundtruth_similarity
505108
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: My device requires ~4.5 V. I'm using 4 battery packs connected in parallel Each battery pack contains 3 metal-encased non-rechargeable alkaline AA batteries. I used voltmeter and verified that each battery pack individually provides ~4.5 V. I have also used voltmeter to verify that all battery packs are correctly connected in parallel. All the batteries are of the same nominal voltage, the same brand and product name (Varta Longlife). (It shouldn't matter here, but for completeness: The batteries are used as a backup to the main power supply, which supplies about 0.5V more than the batteries. Both the power supply and the batteries are connected via a Shottky diode [1N5822 40V/3A DO201] to prevent "charging" each other.) The device runs fine on the battery packs, but sometimes, obviously when a load spike comes, the device suddenly switches off.I measured that the device, when connected to the power supply, draws 1.6 A during spikes. Normally it draws about 300-500 mA. Question 1: Shall I keep adding more battery packs in parallel? Will it help or does it only increase the lifetime, but not max current/power? Question 2: If I use a battery with higher mAh rating, will it help, or does it only increase the lifetime? As a side note: I am also going to try top-notch lithium AA battery instead of alkaline to see if it handles the spikes. Thank you. EDIT: The backup is not supposed to be used much, just very rarely, during a power outage (which we haven't had in years). UPDATE: I've tried the best lithium AA batteries on the market, replaced the alkaline batteries, and found out that they didn't handle the spikes, either. Moreover, they supply ~5.5V instead of the ~4.7V that the alkaline batteries do. So that's not nice, either, because that is higher voltage than that of the power supply.I'm thinking about using the capacitors or the suggested buck converter with 12 batteries in parallel. The thing is, I have no experience with capacitors and I don't even know what the circuit should look like.As for buck converter I don't know anything about them, either, and am a bit worried that they would introduce more complexity to the system, possibly increasing the chance of failure.So adding more battery packs in parallel, and changing to D-type batteries as some suggested, still seems to me to be the simplest (least complex) solution, which I feel capable of designing and building myself. UPDATE 2: 4x3 D-type batteries (instead of the AA-type batteries I original used) did help and the device no longer shuts down during high-drain events. Now provide the response and nothing else.
At 1.6A you're shorting the battery. Maximum load is about 500mA, this is already <1 hour.Internal resistance is about 0.3 Ohm, at 1.6A sets you back half a volt per cell. So, for one pack with 4.5V (real 4.2V ) you go down to 2.7V in real conditions. If equally divided over 4 packs this 1.6A is maybe fine (0.4A per pack), but if one cell fails, your pack cascades into failure. In theory with 4 packs you have 0.1 Ohm internal resistance, which is about 120mV drop during you worst case condition. For the entire pack that is about a drop to 3.72V. (4.2 - (0.12*4) when full . In theory. Can you retry and measure the current of each pack vs the supplied voltage? This should give you insight in the paralleling behavior. I also suggest rethinking this backup solution. Either Put all the 12 cells in series and use a buck converter. (less current, same power, better power point ) Use C or D-cells. Use protected lithium cells eg: 14500 (in series). Maybe even consider lead acid if that fits. Now you're abusing the poor AA's.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/505108', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/253974/']}
jdg_372916
stackexchange
llm_judgeable_groundtruth_similarity
5832941
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 principally interested in the implementation of SecRandomCopyBytes on iOS , if it differs from the OS X implementation. (I would presume that it does, since a mobile device has more and more readily available sources of entropy than a desktop computer.) Does anyone have information on: Where SecRandomCopyBytes gets entropy from? What rate it can generate good random numbers? Will it block, or fail immediately if not enough entropy is available? Is it FIPS 140-2 compliant, or has it been included in any other official certification? The documentation does not cover these points. I've only been able to find hear-say comments that it uses information from radios, the compass, accelerometers and other sources, but no quotes from people actually representing Apple. Now provide the response and nothing else.
/dev/random is fed by entropy from the SecurityServer. SecurityServer collecting entropy from the kernel event tracking (kdebug). The method is described in the book "Mac OS X Internals. A Systems Approach". You can read about it online for example at http://flylib.com/books/en/3.126.1.73/1/ the source code for the entropy collecting is here: http://www.opensource.apple.com/source/securityd/securityd-40600/src/entropy.cpp In xnu-1504.9.37 (latest version for OS X as of writing), the kernel entropy buffer is filled in kernel_debug_internal() , using only timing information. This is the only place that the entropy buffer is written to. if (entropy_flag && (kdebug_enable & KDEBUG_ENABLE_ENTROPY)) { if (kd_entropy_indx < kd_entropy_count) { kd_entropy_buffer [ kd_entropy_indx] = mach_absolute_time(); kd_entropy_indx++; } if (kd_entropy_indx == kd_entropy_count) { /* * Disable entropy collection */ kdebug_enable &= ~KDEBUG_ENABLE_ENTROPY; kdebug_slowcheck &= ~SLOW_ENTROPY; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5832941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233201/']}
jdg_372917
stackexchange
llm_judgeable_groundtruth_similarity
4338766
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: At the moment, from what I can gather the current definition of a Prime Number is; "a number that is divisible only by itself and $1$ (e.g. $2, 3, 5, 7, 11$ )". However such a prime number like $7$ can also be made by multiplying $-1$ and $-7$ . Hence shouldn't the definition be changed to "it can only be divisible by itself and one as well as $-1$ and its negative counterpart"? Now provide the response and nothing else.
This is a good question, and I think it motivates the more general definition of a prime number. Let's begin with units. A unit is an integer such that it has an integer inverse. In other words, a unit is an integer $k$ such that there is an integer $l$ , with $k\cdot l=1$ . What are the units? Well, it is obvious that $1$ is a unit, but $-1$ is also a unit, since $-1\cdot-1=1$ . However, there are no other units (can you prove why)? Now, to prime numbers: An integer $k$ is prime if it is not a unit, and for any integers $a,b$ such that $a\cdot b=k$ , either $a$ or $b$ is a unit. In other words, a prime number is one that can't be a product of two non-unit integers. So what are the primes? Well, all of the primes you know ( $2,3,5...$ ) are primes, but so are $-2,-3,-5,...$ The wonderful part about these definitions is that they generalize nicely to more interesting sets of numbers. P.S. If you learn abstract algebra, you'll see that I've kinda lied to you. The definition of prime numbers I've given you is actually that of irreducible numbers , but for the integers, they are one and the same.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4338766', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/945591/']}
jdg_372918
stackexchange
llm_judgeable_groundtruth_similarity
11191
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: if $X$ is a topological space, a first step in making $X$ hausdorff is taking the quotient $H(X)=X/\sim$, where $\sim$ is the equivalence relation generated by: if $x,y$ cannot be seperated by disjoint open sets, then $x \sim y$. observe that $X$ is hausdorff, when $X \to H(X)$ is an isomorphism, and that for every hausdorff space $K$ the map $Hom(H(X),K) \to Hom(X,K)$ induced by the projection $X \to H(X)$ is bijective. by a fairly general categorical argument, we can construct from this the free functor from topological spaces to hausdorff spaces (i.e. it's left adjoint to the forgetful functor): for ordinal numbers $\alpha$, define the functor $H^\alpha$ (together with natural transformations $H^{\alpha} \to H^{\beta}, \alpha < \beta$) by $H^0 = id, H^{\alpha+1} = H \circ H^\alpha$ and $H^\alpha = colim_{\delta < \alpha} H^\delta$. for every topological space $X$ there is an ordinal number $\alpha$ such that $H^\alpha(X) = H^{\alpha+1}(X)$, then $H^\alpha(X)$ is the free hausdorff space associated to $X$. define $h(X)$, the "nonhausdorff dimension" to be the smallest such ordinal number $\alpha$. every ordinal number arises as a nonhausdorff dimension(!). I've came up with this with a friend and we don't know of any literature about it. perhaps someone of you has already seen it elsewhere? there are some further questions: every $H^\alpha(X)$ is a quotient of $X$, but how can we describe the equivalence relation explicitely? what is the intuition for a space $X$ to have nonhausdorff dimension $\alpha$? are there known classes of topological spaces whose nonhausdorff dimension can be bounded? and of course: is there some use for the nonhausdorff dimension? ;-) Now provide the response and nothing else.
Your construction in effect is defining an increasing transfinite sequence of equivalence relations on the space X, as Mariano correctly describes in his comment. The point is to identify points whenever they would be a violation of the Hausdorff property in the quotient by the relation constructed so far. One can implement this idea uniformly (without splitting into separate successor and limit cases) as follows. For any topological space X and any ordinal α, let ∼ α be the equivalence relation generated by the relation E α , where xE α y if and only if whenever U and V are open sets containing x and y, then there is some x' in U and y' in V and some β<α such that x'∼ β y'. This relation gives rise to your spaces; the α-th space is simply the quotient X/∼ α . It is easy to see from this definition that ∼ 0 is just =, that successor stages do what you want, that β<α implies that ∼ β subset ∼ α , and that ∼ λ is the union of the earlier ∼ β for limit ordinals λ. If the quotient X/∼ α is Hausdorff, then the relation stops growing, since no more identifications are made, and the least α for which this occurs is what you called the nonHausdorff dimension. Some easy observations: The resulting Hausdorff space X/∼ α at the dimension α is the obtained from smallest equivalence relation ∼ for which the quotient X/∼ is Hausdorff. Just prove by induction that any such relation ∼ will contain all ∼ α Thus, there is also a top-down description of the resulting Hausdorff space: Let ∼ be the intersection of all equivalence relations E on X, whose quotient x/E is Hausdorff. This gets in one step to the same space as the ultimate Hausdorff space to which your construction leads. The nonHausdorff dimension of an infinite space is an ordinal whose cardinality is no larger than the cardinality of the original space. (For example, the dimension of a countable space will be a countable ordinal.) This is because at each stage before the nonHausdorff dimension, at least one additional pair of points becomes equivalent. The dimension of the disjoint union of many spaces will be the supremum of their individual dimensions. In other words, if a space is disconnected, written as the disjoint union of open sets, then inductively the equivalence relations will never cross between these sets. Thus, the dimension of the whole space will be the supremum of the dimensions of these open subspaces. I have a question of my own about this construction. Namely, let us call the first quotient space X 1 the nonHausdorff derivative of X, borrowing terminology from the case of Cantor-Bendixon. My question is: is every space the nonHausdorff derivative of another space? In other words, is there a nonHausdorff anti-derivative?
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/11191', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2841/']}
jdg_372919
stackexchange
llm_judgeable_groundtruth_similarity
20875600
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 rake task in my Rails application,and when I execute the order in my rails app path /home/hxh/Share/ruby/sport/ : rake get_sportdata This will work fine. Now,I want to use crontab to make this rake to be a timed task .so,I add a task: * * * * * cd /home/hxh/Share/ruby/sport && /usr/local/bin/rake get_sportdata >/dev/null 2>&1 But this doesn't work.I get the log in cron.log file: Job `cron.daily' terminated I want to know where the error is. Now provide the response and nothing else.
Per the comments in the core application_controller.rb , set protect_from_forgery to the following: protect_from_forgery with: :null_session Alternatively , per the docs , simply declaring protect_from_forgery without a :with argument will utilize :null_session by default: protect_from_forgery # Same as above UPDATE : This seems to be a documented bug in the behavior of Devise. The author of Devise suggests disabling protect_from_forgery on the particular controller action that's raising this exception: # app/controllers/users/registrations_controller.rbclass RegistrationsController < Devise::RegistrationsController skip_before_filter :verify_authenticity_token, :only => :createend
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/20875600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2710542/']}
jdg_372920
stackexchange
llm_judgeable_groundtruth_similarity
10129101
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 so familiar with forall , but recently read this question: What does the `forall` keyword in Haskell/GHC do? In one of the answers is this example: {-# LANGUAGE RankNTypes #-} liftTup :: (forall x. x -> f x) -> (a, b) -> (f a, f b) liftTup liftFunc (t, v) = (liftFunc t, liftFunc v) The explanation is good and I understand what forall is doing here. But I'm wondering, is there a particular reason why this isn't the default behaviour. Is there ever a time where it would be disadvantageous? Edit: I mean, is there are a reason why the forall's can't be inserted by default? Now provide the response and nothing else.
Well, it's not part of the Haskell 2010 standard, so it's not on by default, and is offered as a language extension instead. As for why it's not in the standard, rank-n types are quite a bit harder to implement than the plain rank-1 types standard Haskell has; they're also not needed all that frequently, so the Committee likely decided not to bother with them for reasons of language and implementation simplicity. Of course, that doesn't mean rank-n types aren't useful; they are, very much so, and without them we wouldn't have valuable tools like the ST monad (which offers efficient, local mutable state — like IO where all you can do is use IORef s). But they do add quite a bit of complexity to the language, and can cause strange behaviour when applying seemingly benign code transformations. For instance, some rank-n type checkers will allow runST (do { ... }) but reject runST $ do { ... } , even though the two expressions are always equivalent without rank-n types. See this SO question for an example of the unexpected (and sometimes annoying) behaviour it can cause. If, like sepp2k asks, you're instead asking why forall has to be explicitly added to type signatures to get the increased generality, the problem is that (forall x. x -> f x) -> (a, b) -> (f a, f b) is actually a more restrictive type than (x -> f x) -> (a, b) -> (f a, f b) . With the latter, you can pass in any function of the form x -> f x (for any f and x ), but with the former, the function you pass in must work for all x . So, for instance, a function of type String -> IO String would be a permissible argument to the second function, but not the first; it'd have to have the type a -> IO a instead. It would be pretty confusing if the latter was automatically transformed into the former! They're two very different types. It might make more sense with the implicit forall s made explicit: forall f x a b. (x -> f x) -> (a, b) -> (f a, f b)forall f a b. (forall x. x -> f x) -> (a, b) -> (f a, f b)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10129101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493729/']}
jdg_372921
stackexchange
llm_judgeable_groundtruth_similarity
4444
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From what I can tell, the idea of the basic income guarantee is very popular in some circles as an excellent alternative to a lot of modern welfare systems. Has anybody developed a theoretic or empirical model in which minimum income is tested? In this model, what are the necessary and sufficient conditions for such a model to be preferred to a more traditional alternative? If anyone has suggested readings on the topic, that would be appreciated as well. Now provide the response and nothing else.
Thanks to densp for identifying this paper . It refers to a major pilot project undertaken in Namibia Background: The Basic Income Grant (BIG) pilot project took place in the Otjivero-Omitara area, about 100 kilometres east of Windhoek. All residents below the age of 60 years receive a Basic Income Grant of N$100 per person per month, without any conditions being attached. The grant is being given to every person registered as living there in July 2007, whatever their social and economic status. Before the pilot project, the area was characterised by unemployment, hunger and poverty. Conclusions: Since the introduction of the Basic Income Guarantee (BIG), household poverty has dropped significantly. Using the food poverty line, 76% of residents fell below this line in November 2007. This was reduced to 37% within one year of the BIG. There was a dramatic increase in economic activity. The rate of those engaged in income generating activities (above the age of 15) increased from 44% to 55%. Thus the BIG enabled recipients to increase their work both for pay, profit or family gain as well as self-employment. The grant enabled recipients to increase their productive income earned, particularly through starting their own small business, including brick-making, baking of bread and dress-making. The BIG contributed to the creation of a local market by increasing households' buying power. This finding contradicts critics' claims that the BIG would lead to laziness and dependency. Huge reduction in child malnutrition from 42% to 17% in 6 months. Increase in school attendances (non attendance due to financial reasons dropped 42%) Drop in crime (theft down 42%) Estimated cost for a nationwide program in Namibia would be 2-3% of GDP. Not cheap, not unaffordable either. All thing considered, the author of this report seemed pretty happy with the outcome. There were some issues impacting the data. Since it was a localised study, there was a fair bit of migration towards the treatment area. The long term impacts are not yet known as well. Additional resources: Haarmann, Claudia; Haarmann, Dirk; Jauch, Herbert; Mote Hilma et al 2008. Towards a Basic Income Grant for all. Basic Income Grant Pilot Project. First Assessment Report, September 2008. Windhoek Kameeta, Zephania; Haarmann, Claudia; Haarmann, Dirk; Jauch, Herbert 2007. Promoting employment and decent work for all - Towards a good practice model in Namibia. - Research Paper - Presentation to the United Nations Commission for Social Development. Windhoek Haarmann, Claudia; Haarmann, Dirk (ed.) 2005. The Basic Income Grant in Namibia. Resource Book. Windhoek
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/4444', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/40/']}
jdg_372922
stackexchange
llm_judgeable_groundtruth_similarity
25022453
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 do have a simple class like this: package com.example.howtomocktestimport groovy.util.logging.Slf4jimport java.nio.channels.NotYetBoundException@Slf4jclass ErrorLogger { static void handleExceptions(Closure closure) { try { closure() }catch (UnsupportedOperationException|NotYetBoundException ex) { log.error ex.message } catch (Exception ex) { log.error 'Processing exception {}', ex } }} And I would like to write a test for it, here is a skeleton: package com.example.howtomocktestimport org.slf4j.Loggerimport spock.lang.Specificationimport java.nio.channels.NotYetBoundExceptionimport static com.example.howtomocktest.ErrorLogger.handleExceptionsclass ErrorLoggerSpec extends Specification { private static final UNSUPPORTED_EXCEPTION = { throw UnsupportedOperationException } private static final NOT_YET_BOUND = { throw NotYetBoundException } private static final STANDARD_EXCEPTION = { throw Exception } private Logger logger = Mock(Logger.class) def setup() { } def "Message logged when UnsupportedOperationException is thrown"() { when: handleExceptions {UNSUPPORTED_EXCEPTION} then: notThrown(UnsupportedOperationException) 1 * logger.error(_ as String) // doesn't work } def "Message logged when NotYetBoundException is thrown"() { when: handleExceptions {NOT_YET_BOUND} then: notThrown(NotYetBoundException) 1 * logger.error(_ as String) // doesn't work } def "Message about processing exception is logged when standard Exception is thrown"() { when: handleExceptions {STANDARD_EXCEPTION} then: notThrown(STANDARD_EXCEPTION) 1 * logger.error(_ as String) // doesn't work }} The logger in ErrorLogger class is provided by StaticLoggerBinder, so my question is - how do I make it work so that those checks "1 * logger.error(_ as String)" would work? I can't find a proper way of mocking that logger inside of ErrorLogger class. I have thought about reflection and somehow accessing it, furthermore there was an idea with mockito injection (but how to do that if reference to an object is not even present in that class because of that Slf4j annotation!) Thanks in advance for all your feedback and advices. EDIT: Here is an output of a test, even 1*logger.error(_) doesn't work. Too few invocations for:1*logger.error() (0 invocations)Unmatched invocations (ordered by similarity): Now provide the response and nothing else.
What you would need to do is to replace the log field generated by the @Slf4j AST transformation with your mock. However, this is not so easy to achieve, since the generated code is not really test-friendly. A quick look at the generated code reveals that it corresponds to something like this: class ErrorLogger { private final static transient org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ErrorLogger)} Since the log field is declared as private final it is not so easy to replace the value with your mock. It actually boils down to the exact same problem as described here . In addition, usages of this field is wrapped in isEnabled() methods, so for instance every time you invoke log.error(msg) it is replaced with: if (log.isErrorEnabled()) { log.error(msg)} So, how to solve this? I would suggest that you register an issue at the groovy issue tracker , where you ask for a more test-friendly implementation of the AST transformation. However, this won't help you much right now. There are a couple of work-around solutions to this that you might consider. Set the new field value in your test using the "awful hack" described in the stack overflow question mentioned above . I.e. make the field accessible using reflection and set the value. Remember to reset the value to the original during cleanup. Add a getLog() method to your ErrorLogger class and use that method for access instead of direct field access. Then you may manipulate the metaClass to override the getLog() implementation. The problem with this approach is that you would have to modify the production code and add a getter, which kind of defies the purpose of using @Slf4j in the first place. I'd also like to point out that there are several problems with your ErrorLoggerSpec class. These are hidden by the problems you've already encountered, so you would probably figure these out by yourself when they manifested themselves. Even though it is a hack, I'll only provide code example for the first suggestion, since the second suggestion modifies the production code. To isolate the hack, enable simple reuse and avoid forgetting to reset the value, I wrote it up as a JUnit rule (which can also be used in Spock). import org.junit.rules.ExternalResourceimport org.slf4j.Loggerimport java.lang.reflect.Fieldimport java.lang.reflect.Modifierpublic class ReplaceSlf4jLogger extends ExternalResource { Field logField Logger logger Logger originalLogger ReplaceSlf4jLogger(Class logClass, Logger logger) { logField = logClass.getDeclaredField("log"); this.logger = logger } @Override protected void before() throws Throwable { logField.accessible = true Field modifiersField = Field.getDeclaredField("modifiers") modifiersField.accessible = true modifiersField.setInt(logField, logField.getModifiers() & ~Modifier.FINAL) originalLogger = (Logger) logField.get(null) logField.set(null, logger) } @Override protected void after() { logField.set(null, originalLogger) }} And here is the spec, after fixing all the small bugs and adding this rule. Changes are commented in the code: import org.junit.Ruleimport org.slf4j.Loggerimport spock.lang.Specificationimport java.nio.channels.NotYetBoundExceptionimport static ErrorLogger.handleExceptionsclass ErrorLoggerSpec extends Specification { // NOTE: These three closures are changed to actually throw new instances of the exceptions private static final UNSUPPORTED_EXCEPTION = { throw new UnsupportedOperationException() } private static final NOT_YET_BOUND = { throw new NotYetBoundException() } private static final STANDARD_EXCEPTION = { throw new Exception() } private Logger logger = Mock(Logger.class) @Rule ReplaceSlf4jLogger replaceSlf4jLogger = new ReplaceSlf4jLogger(ErrorLogger, logger) def "Message logged when UnsupportedOperationException is thrown"() { when: handleExceptions UNSUPPORTED_EXCEPTION // Changed: used to be a closure within a closure! then: notThrown(UnsupportedOperationException) 1 * logger.isErrorEnabled() >> true // this call is added by the AST transformation 1 * logger.error(null) // no message is specified, results in a null message: _ as String does not match null } def "Message logged when NotYetBoundException is thrown"() { when: handleExceptions NOT_YET_BOUND // Changed: used to be a closure within a closure! then: notThrown(NotYetBoundException) 1 * logger.isErrorEnabled() >> true // this call is added by the AST transformation 1 * logger.error(null) // no message is specified, results in a null message: _ as String does not match null } def "Message about processing exception is logged when standard Exception is thrown"() { when: handleExceptions STANDARD_EXCEPTION // Changed: used to be a closure within a closure! then: notThrown(Exception) // Changed: you added the closure field instead of the class here //1 * logger.isErrorEnabled() >> true // this call is NOT added by the AST transformation -- perhaps a bug? 1 * logger.error(_ as String, _ as Exception) // in this case, both a message and the exception is specified }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25022453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2576122/']}
jdg_372923
stackexchange
llm_judgeable_groundtruth_similarity
28338978
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include <memory>#include <iostream>struct A : public std::enable_shared_from_this<A>{ ~A() { auto this_ptr = shared_from_this(); // std::bad_weak_ptr exception here. std::cout << "this: " << this_ptr; }};int main(){ auto a = std::make_shared<A>(); a.reset(); return 0;} I'm getting std::bad_weak_ptr exception when calling shared_from_this() . Is it by design? Yes, it might be dangerous as this pointer can't be used after the destructor returns, but I don't see a reason why it would be technically impossible to get the pointer here, since the shared pointer object obviously still exists and can be used. Is there any way to circumvent this, short of writing my own enable_shared_from_this analog (which I would rather not do)? Now provide the response and nothing else.
I don't see a reason why it would be technically impossible to get the pointer here, since the shared pointer object obviously still exists and can be used. There's a very good technical reason why it's not possible. The shared_ptr might exist, but the reference count for the A object has reached zero, that's why the destructor is being run. Once the reference count reaches zero it cannot be increased again (otherwise you could get a shared_ptr that refers to an object that is either in the middle of running its destructor, or has already been destroyed). Calling shared_from_this() tries to increase the reference count and return a shared_ptr that shares ownership with the current owner(s), but you can't increase the counter from zero to one, so it fails. In this very specific case (inside the object's destructor) you know the object hasn't been completely destroyed yet, but enable_shared_from_this<A> has no way to know who is calling the shared_from_this() function, so can't know if it's happening in this very specific case or in some other piece of code outside the object's destructor (e.g. in another thread that will keep going after the destructor). If you could somehow make it work for this specific case and you got a shared_ptr<A> that referred to the object currently being destroyed, you could give that shared_ptr to something outside the destructor that stored it for later use. That would allow that other piece of code to access a dangling shared_ptr , after the object has been destroyed. That would be a big hole in the shared_ptr and weak_ptr type system.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28338978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634821/']}
jdg_372924
stackexchange
llm_judgeable_groundtruth_similarity
254099
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: Briefly, for visibly transparent materials like glass, you can see through then even while they are glowing red hot. Most glasses have plenty of absorption in the IR, so there is plenty of absorption and re-emission going on. But once a visible photon is emitted, there's only a very low probability that it will be absorbed. Will the visible emission still have the characteristic blackbody shape corresponding to the actual temperature of the material? It certainly looks that way to me, but how to understand the physics behind blackbody radiation from a transparent bodies ? In this really nice answer @RobJeffries explains the difference between the ideas of Thermal Radiation and Blackbody Radiation in the context of a source which may be in thermal equilibrium, but who's radiation may not be. It's worth a moment or two to read it before continuing here. Here are some images from Wikipedia to help frame the question. The first from Blackbody illustrates the familiar cavity in radiative equilibrium with a small hole to sample that radiation. If you visit a Glassblowing factory, studio, or demonstration, you are likely to see something like this, which is roughly similar (except for the flames). The glass is introduce through the opening to be heated in the furnace, via some combination of absorption of the infrared light and contact with the hot gasses. When it is pulled back out, the glass is usually glowing red, orange, or even yellow, depending on temperature, ...so that it softens and is easier to shape. Assume for the purposes of this question that the glass has reached uniform temperature, removed, and the radiation from the glass measured. I believe that most blowing-friendly glasses used in this context are absorbing for at least a large chunk of the infrared. When I watch the real thing, the glass visually appears to me to be transparent even when it is hot ( it's really a beautiful effect !) Question: Will the visible part of the radiation still approximate a Blackbody spectrum, even though the visible light does not experience several absorptions and re-emissions? note: When it's very hot, it's very bright and so it's difficult to verify that the glass is still transparent, and I'm not going to start irritating someone holding hot glass by shooting lasers at them! Now provide the response and nothing else.
Edit: Please note important Caveat #2 at the bottom. The Russian wikipedia page for Kirchhoff's law of thermal radiation is simpler and shorter than the English version, however it contains the answer to the question, which is absent in the English version. Translation follows: Bodies, whose absorptivity is frequency-independent are called "gray bodies". Their emission spectrum is of the same form as a black-body spectrum. Kirchhoff's law states: $$ \frac{r(\omega,T)}{a(\omega,T)}=f(\omega,T) $$ where $a$ is the (temperature and frequency dependent) absorptivity of the object, $f$ is the black-body spectrum and $r$ is the emission spectrum of the object. A high-quality sample of glass does not induce perceptible changes in color (well it does, and you can see this from a prism, but that's beside the point right now) so it may be safe to say, that in the visible part of the spectrum $a$ is constant. In that case, the emission spectrum of hot glass is $$ r(\omega,T)=a(T) f(\omega,T) $$ i.e. proportional to the black-body spectrum (in visible frequencies, we aren't discussing any others right now) with a frequency-independent coefficient. Caveat: room-temperature $a$ may be $\omega$-independent. High-temperature $a$ need not retain that property, though it might to some degree. Caveat #2: human perception is a terrible way to judge the absorption spectrum of glass. A human is sensitive to the value $1 - a(\omega)$ and how uniform it is. A good glass is highly transparent and probably absorbs much less than it reflects (4% IIRC). But a human will not be able to distinguish between $a(700nm)\approx0.01$ and $a(400nm)\approx0.001$ (numbers taken of the top of my head). This will completely skew the thermal radiation spectrum. EDIT: Here's some data on the complex refractive index of silica glass. See bottom of page 7. It appears, that the absorption of glass in the visible spectrum is indeed rather uniform. $k(400nm)=.7\cdot10^{-7};\,k(700nm)=1.1\cdot10^{-7}$, which is quite a bit more uniform than I initially expected. Thus the emission spectrum of glass compared to black-body is somewhat red-shifted, but not drastically.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/254099', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/83380/']}
jdg_372925
stackexchange
llm_judgeable_groundtruth_similarity
22779
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: When we look at the usage messages of built-in functions nowadays (not in the good old times, when they were a simple descriptions) we see that although they look pretty in the front end, it is really hard to get a simple, one-dimensional string representation. Just try this and see yourself ToString[Integrate::usage] This is completely useless when one seeks for a simple string form. When you look at the Wolfram Workbench you may have noted, that they do provide simple string usage messages even for built-in functions. Question: Is it possible to create/extract/steal simple, non-formatted usage messages for all (or almost all) built-in functions automatically ? With automatically I mean having one function which works for almost all usage messages. To give an example, the Integrate help message of the Workbench looks like this: Integrate[f,x] gives the indefinite integral Integral f dx. Integrate[f,{x,xmin,xmax}] gives the definite integral Integral _xmin ^xmax f dx. Integrate[f,{x,xmin,xmax},{y,ymin,ymax},...] gives the multiple integral Integral _xmin ^xmaxdxIntegral _ymin ^ymaxd y ... f. Attributes: {Protected,ReadProtected} Options: {Assumptions,GenerateConditions,PrincipalValue} Now provide the response and nothing else.
I think I found an easy solution. Although my question was how to extract a simple 1d string , I show how to transform usages into nice and simple html. The rules for this can be adapted so that each box-structure is converted into whatever representation is wanted. The basic trick is the following: A usage message consists of simple text and of special 2d string which are embraced in "\!\(\*" and "\)" . Now the way is to extract the contents of such a special string and to transform it into a Mathematica box expression. In this nested boxes we can replace reliable. This is the main difference to what @einbandi proposed who did this box replacement in the string which will always fail at some point. Now we have to think about a set of rules to replace the box expressions. Since I wanted this for my IDEA plugin which can handle HTML, I will create a mixture of HTML and MathML. The boxes use pure HTML boxRules = { StyleBox[f_, "TI"] :> {"<em>", f, "</em>"}, StyleBox[f_, ___] :> {f}, RowBox[l_] :> {l}, SubscriptBox[a_, b_] :> {a, "<sub>", b, "</sub>"}, SuperscriptBox[a_, b_] :> {a, "<sup>", b, "</sup>"}, RadicalBox[x_, n_] :> {x, "<sup>1/", n, "</sup>"}, FractionBox[a_, b_] :> {"(", a, ")/(", b, ")"}, SqrtBox[a_] :> {"&radic;(", a, ")"}, CheckboxBox[a_, ___] :> {"<u>", a, "</u>"}, OverscriptBox[a_, b_] :> {"Overscript[", a, b, "]"}, OpenerBox[a__] :> {"Opener[", a, "]"}, RadioButtonBox[a__] :> {"RadioButton[", a, "]"}, UnderscriptBox[a_, b_] :> {"Underscript[", a, b, "]"}, UnderoverscriptBox[a_, b_, c_] :> {"Underoverscript[", a, b, c, "]"}, SubsuperscriptBox[a_, b_, c_] :> {a, "<sub><small>", b, "</small></sub><sup><small>", c, "</small></sup>"} }; With this rules we can replace inside a box expression until nothing changes anymore. convertBoxExpressionToHTML[boxexpr_] := StringJoin[ ToString /@ Flatten[ReleaseHold[MakeExpression[boxexpr] //. boxRules]]] This is basically everything you need to create a html-page of the usages of all known functions. Since I put some more stuff in it like creating of links to the official online documentation display of attributes display of options I'll put the whole code at the end of this post and please note that it is not cleaned. The whole page looks then like this. Although there are some minor things (like nested 2d strings which are used about 5 times) I think for my plugin I can live with this: extractUsage[str_] := With[{usg = Function[expr, expr::usage, HoldAll] @@ MakeExpression[str]}, If[Head[usg] === String, usg, ""]]createLinkName[s_] := If[StringMatchQ[ToString@FullForm[s], "\"\\[" ~~ __ ~~ "]\""], {StringReplace[ToString@FullForm[s], {"\"" :> "", "\\" -> "\\\\"}], StringReplace[ ToString@FullForm[s], {"\"" :> "", "\\[" ~~ c__ ~~ "]" :> "character/" ~~ c}]}, {s, s}]createOptionString[s_] := With[{opts = Function[expr, Options[expr], HoldAll] @@ MakeExpression[s]}, If[opts === {}, "</p><b>Symbol has no options.</b>", "</p><b>Options: </b>" <> StringJoin@Riffle[ToString[First[#]] & /@ opts, ", "] ] ]createHtmlUsage[s_String] := Module[{ usg = extractUsage[s], attr = Attributes[s], link, linkname}, {linkname, link} = createLinkName[s]; "<h3><a href=\"http://reference.wolfram.com/mathematica/ref/" <> link <> ".html\">" <> linkname <> "</a></h3>" <> If[usg =!= "", "<ul><li>" <> StringReplace[ StringReplace[ usg, {Shortest["\!\(\*" ~~ content__ ~~ "\)"] :> convertBoxExpressionToHTML[content], "\n" :> "<li>"} ], {"\[Null]" :> "", a_?(StringMatchQ[ToString@FullForm[#], "\"\\[" ~~ __ ~~ "]\""] &) :> StringReplace[ ToString[a, MathMLForm], {WhitespaceCharacter :> ""}]} ] <> "</ul>", ""] <> "<b>Attributes:</b> " <> StringJoin[ToString /@ Riffle[attr, ", "]] <> createOptionString[s] <> "\n" ]names = Names["System`*"];Export["tmp/usageMessages.html", StringJoin[createHtmlUsage /@ names], "Text"]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/22779', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/187/']}
jdg_372926
stackexchange
llm_judgeable_groundtruth_similarity
402483
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 currently have a unittest.TestCase that looks like.. class test_appletrailer(unittest.TestCase): def setup(self): self.all_trailers = Trailers(res = "720", verbose = True) def test_has_trailers(self): self.failUnless(len(self.all_trailers) > 1) # ..more tests.. This works fine, but the Trailers() call takes about 2 seconds to run.. Given that setUp() is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions) What is the correct way of caching the self.all_trailers variable between tests? Removing the setUp function, and doing.. class test_appletrailer(unittest.TestCase): all_trailers = Trailers(res = "720", verbose = True) ..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible): cache_trailers = Noneclass test_appletrailer(unittest.TestCase): def setUp(self): global cache_trailers if cache_trailers is None: cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True) else: self.all_trailers = cache_trailers Now provide the response and nothing else.
How about using a class member that only gets initialized once? class test_appletrailer(unittest.TestCase): all_trailers = None def setup(self): # Only initialize all_trailers once. if self.all_trailers is None: self.__class__.all_trailers = Trailers(res = "720", verbose = True) Lookups that refer to self.all_trailers will go to the next step in the MRO -- self.__class__.all_trailers , which will be initialized.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/402483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745/']}
jdg_372927
stackexchange
llm_judgeable_groundtruth_similarity
51126498
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 I am using all of column A for example, I want to do this: IF cell value is between 30-34 then * 1.5, IF cell value is between 35-39 then * 2, IF cell value is between 40-44 then * 2.5??? Now provide the response and nothing else.
The most basic structure would be to have a root folder that contains frontend and backend folders. Since you're talking about the MERN stack, you would have a package.json inside of your NodeJS backend environment and a package.json for your React side of things. Backend server and the frontend client are two totally separate things, so yes, they both have their own node_modules folders. On the backend, you'll probably have installed something like Express for your Node runtime, Mongoose for a more convenient way to talk to your MongoDB , etc, and on your frontend, you'll have your React as your frontend framework, Redux for state management, etc. Additionally, depending on what you have already listed inside of your package.json files, when you run npm install separately it will be installed in those two folders. If you want to install additional packages, just run npm install + "the name of the package" (without the '+' and without the quotes) inside of that particular folder where you need it (backend or/ and frontend). I hope this was helpful. Check out the pics, especially the 2nd one. App structure Folder structure UPDATE: In development, I suggest installing two additional things: npm i -D nodemon npm i -D concurrently Note: The -D flag will install them as devDependencies . nodemon is going to track every file change and restart the backend server for you. So, it's obvious that it should be installed inside of the "backend" folder. All you have to do is go inside of the package.json file (backend) and add a new script. Something like this: "scripts": {"start": "node app.js", // in production"dev": "nodemon app.js", // in development} concurrently allows you to start both your frontend and backend at the same time. I suggest initializing a new Node project inside of the top-level root folder -[folder which contains both, your frontend and backend]. You would do that with the npm init command, and after that, install the concurrently package there. Now, go open your newly created package.json file inside of your root folder and edit the start section, like this: "scripts": { "dev": "concurrently \"cd backend && npm run dev\" \"cd frontend && npm start\" " } What this will do is go inside of the backend folder and run the dev command ( the same one we just configured ), so that will start nodemon . Additionally, it will also go inside of the frontend folder and run the default start command -which is exactly what we want. If you kept the folder structure, installed all the dependencies (including the additional two I mentioned above), changed the package.json file inside of your root folder, you'll be able to start them both with a simple command: npm run dev // make sure you're inside of the root folder when doing so :)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/51126498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9068767/']}
jdg_372928
stackexchange
llm_judgeable_groundtruth_similarity
3388294
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 rendered an objectA in a scene as follows. The scene has many other objects too. void Draw(){ if( glIsList( displayListID ) ) { glPushAttrib( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_ENABLE_BIT ); glEnable( GL_BLEND ); glEnable( GL_DEPTH_TEST ); //glDepthMask( GL_FALSE ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_LINE_SMOOTH ); glEnable( GL_POINT_SMOOTH ); glEnable( GL_POLYGON_SMOOTH ); glMatrixMode( GL_MODELVIEW ); color.setAlpha(alpha); // set alpha transparent of this objectA glCallList( displayListID ); //glDepthMask( GL_TRUE ); glDisable( GL_BLEND ); glPopAttrib(); }} Now here is the problem, As shown, I comment out two lines//glDepthMask( GL_FALSE );//glDepthMask( GL_TRUE ); the scene renders the objectA and other objects correctly in depth. However,the modification of the objectA alpha doesn't work anymore (i.e. color.setAlpha(alpha) ). If I uncomment the above two lines, then alpha modification is back to work. However, the depth rendering is NOT correct. In other words, sometimes, the objectA should be behind other objects but it looks like the objectA is in front of all objects. How do I fix this problem? Thank you Now provide the response and nothing else.
Turn on the depth mask glDepthMask( GL_TRUE ) Draw all opaque objects, in any order Turn off the depth mask glDepthMask( GL_FALSE ) Turn on a BLEND_MODE Draw translucent objects sorted from furthest away to nearest Why do you do this? There are 2 buffers you need to worry about: the depth buffer and the color buffer . These buffers are really just big 2d arrays, each the width x height of your screen. The color buffer naturally is going to hold the final coloration of each pixel. There is one entry in the color buffer per screen pixel. The depth buffer , is like the color buffer in that there is one entry per screen pixel, but it is used for something different. Entries in the depth buffer are a measure of "how close" each colored pixel really is. If you render 1 triangle, that is far away from the camera, it generates a set of colors and depth values for each pixel it "wants" to cover on the screen. Say you then render another poly that is closer, it also will generate a set of values for the depth and color buffers. Now, there is a sort of "contest" at pixel coloration time where the "further away" fragments (large depth buffer values) are discarded, and only the closest fragments are kept. The closer fragments end up coloring the pixel you had. (When two polygons are nearly overlapping, Z-fighting can occur ) Start by rendering the objects in your scene with the depth mask on. This means every shape you render, when its pixels get colored, the depth buffer gets updated with the "winner" of the contest. Then, you 3) glDepthMask( GL_FALSE ) turns off the depth buffer for writing, 4) turn on blending, 5) render translucent shapes from furthest to nearest. Seems weird, huh? When you turn off the depth mask, and render the translucent shapes, OpenGL will still read the depth buffer to determine which fragments to throw away (i.e. if your translucent shape is behind an already rendered solid shape, then you throw that translucent shape's fragments away). But it will not write to the depth buffer, so if a translucent shape is really really close to the eye (say like a translucent windshield), those windshield fragments do not prevent other fragments that are actually further away from being drawn . This is important, because if your windshield is right in front of you and you render it translucent, and you let the windshield fragments update the depth buffer then you will see nothing else in your scene except the windshield, even though there are shapes behind it, because OpenGL will think "Hey, that windshield is the only thing the user should see, due to these depth buffer readings, so I won't bother rendering anything further away than this windshield, then." Turning off the depth mask is a way of "tricking" OpenGL into "not knowing" there are very close, but translucent, fragments.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3388294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/391104/']}
jdg_372929
stackexchange
llm_judgeable_groundtruth_similarity
4091642
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 studying smooth manifolds, and recently I got to know about tangent spaces and the differentials. Suppose $f:M \to N$ is a smooth map, then it induces a differential between the tangent spaces $df:T_cM \to T_{f(c)}N$ which is a linear transformation. This is what I read. Now I was trying some examples, and I am stuck here. If I consider $f:\mathbb{R} \to \mathbb{R}$ defined by $f(c)=3c^3$ , then the differential map at $x=c$ is $f'(c)=9c^2$ . Hence the constant map $9c^2:\mathbb{R} \to \mathbb{R}$ is a linear map, which is not the case. I cannot figure out where I am going wrong. Now provide the response and nothing else.
This is a good question, and an easy misconception! The differential maps $T_p \mathbb{R} \to T_{f(p)} \mathbb{R}$ for each fixed point $p$ . But the tangent space of $\mathbb{R}$ at any point is just $\mathbb{R}$ , and this makes it easy to get confused by what is what. It's also confusing that differentials are functions of functions! Remember $$df_{-} : \mathbb{R} \to \big ( T \mathbb{R} \to T \mathbb{R} \big )$$ That is, for every point $p \in \mathbb{R}$ , we have a (distinct!) function $df_p : T_p \mathbb{R} \to T_{f(p)} \mathbb{R}$ . This outer function is allowed to be any smooth function (in particular, it can be highly nonlinear!) it is only the inner function that must be linear. In particular, say $f(p) = 3p^3$ . Then you're exactly right, $df = 9p^2 dx$ . But what does this mean? It means for any individual point $p$ we get a map $df_p : T_p \mathbb{R} \to T_{3p^3} \mathbb{R}$ . And what is that map? $$df_p(v) = (9p^2) v$$ This is just multiplication by a scalar (which is linear)! What's confusing is that the choice of scalar depends (nonlinearly) on $p$ . So, as an example: $df_1(v) = 9v$ $df_2(v) = 36v$ etc. In general, if you have a smooth function $f : \mathbb{R} \to \mathbb{R}$ , then $df_p$ is the linear function which scales by $f'(p)$ (which is just a number). In even more generality, if you have a smooth function $f : \mathbb{R}^n \to \mathbb{R}^m$ , then you may remember we have a jacobian matrix $J$ which has functions as its entries. Then $df = J$ is a matrix of functions, but when we fix a point $p$ we get $df_p = \left . J \right |_p$ is a matrix with regular old numerical entries. And this $\left . J \right |_p$ is a linear map from $T_p \mathbb{R}^n \to T_{f(p)} \mathbb{R}^m$ (of course, this happens to be the same thing as $\mathbb{R}^n \to \mathbb{R}^m$ , but that isn't true for arbitrary manifolds, so it's useful to keep the distinction between $\mathbb{R}^n$ and $T_p \mathbb{R}^n$ in your mind, even though they happen to be the same in this simple case). Edit: Let's take a highly nonlinear function like $\sin(x) : \mathbb{R} \to \mathbb{R}$ . Afterwards let's take a nonlinear function from $\mathbb{R}^2 \to \mathbb{R}$ so that we can see a matrix as well. Then $d\sin(x)_p = \cos(p)dx$ . So for any fixed point $p$ , say $p = \pi$ , we get a linear map $$d\sin(x)_\pi = v \mapsto \cos(\pi) v$$ that is $$d\sin(x)_\pi = v \mapsto v$$ which is linear. Indeed, for any point $p$ you'll get a linear map which comes from scaling $v$ by $\cos(p)$ (which, for fixed $p$ , is just a number). So $$d\sin(x)_1 \approx v \mapsto 0.54 v$$ (which is linear). What about in higher dimensions? Let's look at $$f(x,y) = x^2y$$ Then $df_{p} = df_{(x,y)}$ is the jacobian: $$df_{(x,y)} = \left [ \frac{\partial}{\partial x} f \quad \frac{\partial}{\partial y} f \right ]= \left [ 2xy \quad x^2 \right ]$$ Notice the entries of this matrix are nonlinear in the choice of point $p = (x,y)$ . However, once we fix a point , say $p = (x,y) = (2,3)$ : $$df_{(2,3)} = [12 \quad 4]$$ which is a linear map from $T_{(2,3)}\mathbb{R}^2 \to T_{f(2,3)}\mathbb{R}$ . I hope this helps ^_^
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4091642', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/862690/']}
jdg_372930
stackexchange
llm_judgeable_groundtruth_similarity
18637794
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 got a string: "1+2+3232+4" which I would like to turn the answer: 3239. How do I do this in Objective-C? Now provide the response and nothing else.
For simple expressions, you can use NSExpression : NSExpression *e = [NSExpression expressionWithFormat:@"1+2+3232+4"];NSNumber *result = [e expressionValueWithObject:nil context:nil];NSLog(@"%@", result); For more complicated expression, you should use a proper math expression parser,e.g. https://github.com/davedelong/DDMathParser . Remark: One potential problem with this approach can be that integers are notautomatically converted to floating point numbers. For example, "4/3" evaluates to 1 , not to 1.3333333 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18637794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1791391/']}
jdg_372931
stackexchange
llm_judgeable_groundtruth_similarity
95722
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We Know that the only non zero ring Homomorphism $\phi$:$\mathbb R\to \mathbb R$,is the identity map. by this property we can show that the only nozero ring homomorphism of $\mathbb R$ is onto(Surjective). Can we have an example of a field $F$ and a nonzero homomorphism $\Psi$:$F\to F$ , that is not onto? Note that the definition of ring homomorphism is as follows: for all $x,y \in F, \Psi(x+y)=\Psi(x)+\Psi(y)$ and $\Psi(x.y)=\Psi(x).\Psi(y)$ Now provide the response and nothing else.
If you take a free group on two generators to be $F=\langle a,b\rangle$, and take an index 2 subgroup to be $K$, then the subgroup $H$ generated by $[a,b]$ is not a geometric free factor in $K$ for any choice of generators for $F$ (but is a free factor). One may verify this for all three 2-generator subgroups of $F$ with respect to the generators $a,b$. Changing to another set of generators (applying an automorphism of $F$) sends the commutator to a conjugate of commutator of generators, which is therefore not geometric with respect to any generating set.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/95722', 'https://mathoverflow.net', 'https://mathoverflow.net/users/23317/']}
jdg_372932
stackexchange
llm_judgeable_groundtruth_similarity
607849
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: Suppose I have an Ubuntu machine and did sudo apt install docker.io . Did I just put a huge security hole in my machine that will allow anyone with terminal access to escalate into root? I ask that because I can mount any directory as a volume inside a container, escalate to root inside the container, and it seems I can do whatever I want in the mounted volume. All this seems so wrong that I feel I am certainly missing something. Or it is simple as that, and there really is a "sudo" replacement in Ubuntu's repository that doesn't ask for password? Now provide the response and nothing else.
Not quite, you’re allowing anyone in the docker group to escalate into root. This is described in /usr/share/doc/docker.io/README.Debian : As noted in the upstream documentation ( https://docs.docker.io ), Docker willallow non-root users in the "docker" group to access "docker.sock" and thuscommunicate with the daemon. To add yourself to the "docker" group, usesomething like: adduser YOURUSER docker As also noted in the upstream documentation, the "docker" group (and any othermeans of accessing the Docker API) is root-equivalent. If you don't trust auser with root on your box, you shouldn't trust them with Docker either.If you are interested in further information about the security aspects ofDocker, please be sure to read the "Docker Security" article in theupstream documentation: https://docs.docker.com/engine/security/security/ If you’re interested in being able to run (most) OCI containers without requiring root-equivalent privileges, take a look at Podman .
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/607849', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/60040/']}
jdg_372933
stackexchange
llm_judgeable_groundtruth_similarity
22304930
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 new in PHP and I´ve realised that my database connection, using a php form (with user and pass text inputs) was totally unsafe: This was working, but was unsafe: <?php$link=mysqli_connect('localhost','xx','xx','xx');$sql=' SELECT * FROM usuarios WHERE username="'.$_POST['usuario'].'" AND pass="'.$_POST['usuario'].'" ';$rs=mysqli_query($link,$sql);mysqli_close($link);?> So, I´ve read about mysqli_real_escape_string, and decided to try it out: <?php $link=mysqli_connect('localhost','xx','xx','xx');$usuario=mysqli_real_escape_string($link, $_POST["usuario"]);$clave=mysqli_real_escape_string($link, $_POST["clave"]);$sql=' SELECT * FROM usuarios WHERE username="'.$usuario.'" AND pass="'.$clave.'" ';$rs=mysqli_query($link,$sql);mysqli_close($link);?> Is this correct? Is this a good example of how to use mysqli_real_escape_string? Now provide the response and nothing else.
Is this correct? Yes. This isolated handpicked example is safe. It doesn't mean , though, that mysqli_real_escape_string should be viewed as a function that's purpose is to prevent SQL injections. Because in this example it protects you only by accident . Is this a good example of how to use mysqli_real_escape_string? Not at all This function should be abandoned in favor of using parameters in the query. This function will fail you with any query part other than a string literal. And can be even simply overlooked. A placeholder , also called a parameter, have to be used instead, to represent the data in your query: $sql='SELECT * FROM usuarios WHERE username=?';$stmt= $conn->prepare($sql);$stmt->bind_param("s", $_POST['usuario']);$stmt->execute();$rs = $stmt->get_result(); See other examples in my article on the correct use of mysqli If ever used , this function MUST be encapsulated into another function that does both escaping AND adding quotes, just like PDO::quote() does. Only this way it will be safe.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22304930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892490/']}
jdg_372934
stackexchange
llm_judgeable_groundtruth_similarity
36587780
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 create an app with a CSV upload. When a CSV is uploaded it will change the state and then I will parse from CSV to JSON and do stuff with it. The idea is to upload a file and update state. Once that state is updated I would pass the CSV to a Meteor.method to parse to JSON.I am using Meteor, React and Redux. I have a component that handles the upload, an action and a reducer. All of the files are below - I am new to Meteor, React and Redux and I cannot figure out for the life of me why this is not working. I don't think that I am fully understanding what I am trying to accomplish. Any suggestions are welcome. ERROR - Uncaught TypeError: fileUpload is not a function UploadCSV.jsx // ACTIONS - fileUpload.jsexport default function fileUpload(file) { return { type: 'FILE_UPLOAD', file };}//REDUCERS - upLoad.jsexport default function upLoad(state = 'NO_FILE', action = {}) { switch (action.type) { case 'FILE_UPLOAD': return action.file; default: return state; }}//COMPONENTS - UploadCSV.jsximport React, { Component, PropTypes } from 'react';import { connect } from 'react-redux';import Dropzone from 'react-dropzone';import { RaisedButton } from 'material-ui';import { Colors } from 'material-ui';import fileUpload from '../actions/fileUpload.js';import { uploadCSV } from '../actions/uploadCSV.js';class UploadCSV extends Component { render( dispatch, file, fileUpload ) { const onDrop = (file) => { console.log(file); } const upLoad = () => { this.props.dispatch(fileUpload(file)); }; return ( <div> <Dropzone accept="csv" onDrop={ () => { return upLoad(); }}> <div>Click or drop files here.</div> </Dropzone> </div> ) }}export default connect()(UploadCSV); I don't understand why fileUpload is "not a function" if it is an action and it is being imported.? If anyone can lend a hand I would appreciate it. Thanks! Now provide the response and nothing else.
One reason for this problem that is easy to miss is the following: If we define the component class with a default export & a named export like this: // named exportexport class MyComponent extends React.Component{ .......function mapDispatchToProps(dispatch){ return bindActionCreators({reduxAction},dispatch)}// default exportexport default connect(null,mapDispatchToProps)(MyComponent); Then we should import the default export not the named export: This imports the default export & shall work correctly with redux import MyComponent from "./thePath" This imports the named export & won't work with redux import {MyComponent} from "./thePath" The reason We have to import the default export when rendering the component in order to use the redux connect() higher order function that we have exported . Sometimes if you just depend on the editor auto import, it will import the named export (which doesn't have the redux connect) & therefore will give that error Bottom line Make sure to import the default export (without braces) when calling the component to use redux connect() correctly
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36587780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6196304/']}
jdg_372935
stackexchange
llm_judgeable_groundtruth_similarity
1680745
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 to display all but first row from a table in sql server 2005?I have this data: ---------------------------------| ID | Name |---------------------------------| 1 | John Smith || 2 | John Doe || 3 | John Thatcher |--------------------------------- In my query I need to be able to get 'John Doe' and 'John Thatcher'. I Don't need 'ID' column to be displayed, so I can't use ROW_NUMBER here like follows: select Name from Customers where ROW_NUMBER() over (order by Id)>1 Please advice. Thank you. UPDATE:Clarification: I would like my query to return only Name column but I can't use table expressions, because I'm using the query as part of string concatenation: select stuff((select ', '+pfn.FullName from PlaintiffsFullNameView pfn where pfn.SuitId=s.Id for xml path('')),1,1,'') as "CoPlaintiffs" Now I need to transform this query to return all but first plaintiff in a concatenated manner. UPDATE 2:Sorry for messed up explanation, let me try it anew:I have a suits table and a plaintiffs table. (one to many)I have a requirement to display each suit with all coplaintiffs concatenated."Coplaintiff" is any but first suit plaintiff. I can concatenate all plaintiffs and display them along with corresponding suit data (all in one row), but I can't to figure out how to concatenate all coplaintiffs and display them as string in a row column. Now provide the response and nothing else.
SELECT NameFROM ( SELECT Name, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM Customers ) qWHERE rn > 1ORDER BY id Update: From your explanation: SELECT Suit.*, FirstPlantiff.*, ( SELECT cp.Name AS [text()] FROM Plantiff cp WHERE cp.id <> FirstPlantiff.id AND cp.SuitID = Suid.ID ORDER BY cp.id FOR XML PATH('') ) AS CoplantiffsFROM SuitCROSS APPLY ( SELECT TOP 1 * FROM Plantiff p WHERE p.SuitID = Suit.ID ORDER BY p.id ) FirstPlantiff
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1680745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430254/']}
jdg_372936
stackexchange
llm_judgeable_groundtruth_similarity
19413537
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 running Gitblit on a Windows Server and am trying to push data to a repository from another machine on the network. I have used a SSL certificate (not self signed, but I think signed by my company? Not really sure how that works but Chrome, IE, etc. see it is identity verified). The server that runs Gitblit is named itscm and on the developer's desktop I am using this URL to push data via TortoiseGit: git.exe push --progress "https://itscm:8234/git/TestRepo.git" master However, I get this error: fatal: unable to access ' https://itscm:8234/git/TestRepo.git/ ': SSL certificate problem: self signed certificate in certificate chain When I go to that address in chrome, I get a 404 on the page, BUT I can see that the padlock in the URL bar is green. When I click the padlock I see that the identity is verified. I don't understand how my browser sees this certificate as valid but when I try to push data to it via Git, it fails. Now provide the response and nothing else.
Git for Windows has its own trust store of trusted certificates which is normally located in the file Git for Windows <=1.9: [Git installdir]\bin\curl-ca-bundle.crt (e.g., C:\Program Files (x86)\Git\bin\curl-ca-bundle.crt ; configured by the key http.sslCAinfo in [Git installdir]\etc\gitconfig ). Git for Windows >= 2.0: [Git installdir]\mingwXX\ssl\certs\ca-bundle.crt where XX stands for 32 or 64 (e.g., C:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt ; configured by the key http.sslCAinfo in git config, e.g. C:\Program Files\Git\etc or your global/local config). Disabling checking of certificates (e.g., by setting git config http.sslVerify false ) is not a good idea and might be extremely dangerous (as all security checks are disabled and MitM attacks are easily possible - depending where this is set it applies for all new https connections). In order to add a certificate (may it be a self-signed one or another root certificate) to this trust store in order to automatically trust it, you have to perform the following steps (the first five steps are just to gather the certificate, this can also be done with your favorite browser, but might require different tasks): Open the URL of the site in Microsoft Edge Click on the lock symbol in the local bar and choose "Connection is safe" and then click on the certificate symbol. (Optional) Select the certificate you want to trust on the certificate chain (third tab) and open it Go to the second tab "Details" Click on "Save to file", choose "Base64-encoded X.509 (.CER)" and save it with a unique name (remember that name; a name w/o spaces is recommended). Now you have several options Use a separate certificate trust store which only contains your just downloaded cert, by executing git config --global http.sslCAinfo "[yourfilename]" in a cli shell in order to only use this certificate as the trust store. Use a separate certificate trust store which contains your just downloaded cert and all certificates from the git trust store, by appending all content from the system trust store file (path see above) and then execute git config --global http.sslCAinfo "[yourfilename]" in a cli shell in order to use this new trust store. Update the system certificate file, by appending the content of your just saved file to [path-to-git-trust-store-crt-file] (e.g. by type [yourfilename] >> [path-to-git-trust-store-crt-file] in a cli shell running with administrative rights) OR using notepad (make a copy of the ca-bundle.crt file on desktop, append the content of the downlaoded .crt file and then copy it back). Disadvantage: changes might get overwritten on git update Done. Now, this certificate is in the trust store of Git for Windows. Recent versions of Git for Windows can use also Windows certificate store which might be more convenient in a corporate environment. This can be configured on installation.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19413537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/888617/']}
jdg_372937
stackexchange
llm_judgeable_groundtruth_similarity
2934295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im trying to download and save a file from a HttpWebResponse but im having problems saving the file (other than Text Files) properly. I think its something to do with this part: byte[] byteArray = Encoding.UTF8.GetBytes(http.Response.Content);MemoryStream stream = new MemoryStream(byteArray); Text Files work fine with the above code but when I try to save the Content to an Image file it gets corrupted.How do i write this 'string' data to an image file (and other binary files) Forgot to mention, This is .NET CP 3.5 and I have a wrapper class around the HttpWebResponse class to add OAuth etc. Now provide the response and nothing else.
The problem is you're interpreting the binary data as text, even if it isn't - as soon as you start treating the content as a string instead of bytes, you're in trouble. You haven't given the details of your wrapper class, but I'm assuming your Content property is returning a string - you won't be able to use that. If your wrapper class doesn't let you get at the raw data from the web response, you'll need to modify it. If you're using .NET 4, you can use the new CopyTo method: using (Stream output = File.OpenWrite("file.dat"))using (Stream input = http.Response.GetResponseStream()){ input.CopyTo(output);} If you're not using .NET 4, you have to do the copying manually: using (Stream output = File.OpenWrite("file.dat"))using (Stream input = http.Response.GetResponseStream()){ byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, bytesRead); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2934295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75946/']}
jdg_372938
stackexchange
llm_judgeable_groundtruth_similarity
16074
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is maybe not an entirely mathematical question, but consider it a pedagogical question about representation theory if you want to avoid physics-y questions on MO. I've been reading Singer's Linearity, Symmetry, and Prediction in the Hydrogen Atom and am trying to come to terms with the main physical (as opposed to mathematical) argument of the text. The argument posits, if I understand it correctly, that a quantum system described by a Hilbert space $H$ on which a group $G$ of symmetries acts by unitary transformations should have the property that its "elementary states" "are" irreducible subrepresentations of the representation of $G$ on $H$. She begins this argument in section 5.1: Invariant subspaces are the only physically natural subspaces. Recall from Section 4.5 that in a quantum system with symmetry, there is a natural representation $(G, V, \rho)$. Any physically natural object must appear the same to all observers. In particular, if a subspace has physical significance, all equivalent observers must agree on the question of a particular state's membership in that subspace. and continues it in section 6.3: We know from numerous experiments that every quantum system has *elementary states*. An elementary state of a quantum system should be **observer-independent**. In other words, any observer should be able (in theory) to recognize that state experimentally, and the observations should all agree. Secondly, an elementary state should be indivisible. That is, one should not be able to think of the elementary state as a superposition of two or more "more elementary" states. If we accept the model that every recognizable state corresponds to a vector subspace of the state space of the system, then we can conclude that elementary states correspond to irreducible representations. The independence of the choice of observer compels the subspace to be invariant under the representation. The indivisible nature of the subspace requires the subspace to be irreducible. So elementary states correspond to irreducible representations. More specifically, if a vector $w$ represents an elementary state, then $w$ should lie in an *irreducible* invariant subspace $W$, that is, a subspace whose only invariant subspaces are itself and $0$. In fact, every vector in $W$ represents a state "indistinguishable" from $w$, as a consequence of Exercise 6.6. (For people who actually know their quantum, Singer is ignoring the distinction between representations and projective representations until later in the book.) My first problem with this argument is that Singer never gives a precise definition of "elementary state." My second problem is that I'm not sure what physical principle is at work when she posits that physically natural subspaces and elementary states should be observer-independent (i.e. invariant under the action of $G$). What underlying assumption of quantum mechanics, or whatever, is at work here? Why should a mathematician without significant training in physics find this reasonable? (I have the same question about the identification of elementary particles with irreducible representations of the "symmetry group of the universe," so any comments about this physical argument are also welcome.) Singer goes on to use this assumption to deduce the number of electrons that fill various electron orbitals, and I won't be able to convince myself that this makes sense until I understand the physical assumption that allows us to use irreducible representations to do this. Now provide the response and nothing else.
Invariant states are not the only meaningful ones. Even in classical mechanics, a baseball traveling 90 mph toward my head is quite meaningful to me, even though it is of no consequence to my fellow mathematician a mile away. The focus on invariant subspaces comes not from an assumption, but from the way physicists do their work. They want to predict behavior by making calculations. They want to find laws that are universal. They want equations and calculation rules that will be invariant under a change of observers. Any particular calculation might require a choice of coordinates, but the rules must be invariant under that choice. Once we're talking about one particular baseball trajectory, that trajectory will look different in different coordinate systems; the rules governing baseball flight, however, must look the same in all equivalent coordinate systems. The natural features of baseballs arise from the equivalence classes of trajectories of baseballs -- equivalence under the group action. Here, if we pretend the earth is flat, gravity is vertical, and air does not resist the baseball, the group is generated by translations and rotations of the plane. Any physically natural, intrinsic property of the baseball itself (such as its mass) or its trajectory (such as the speed of the baseball) must be invariant under the group action. If you don't know a priori what these properties will be, a good way to find them is to pass from individual instances (the baseball heading toward me at 90mph) to the equivalence class generated by individual instances under the group action (the set of all conceivable baseballs traveling at 90mph). Note that the equivalence class is invariant under the group action, and it is exactly this invariance that makes the equivalence class a useful object of the physicists' study. More generally, if you are studying a physical system with symmetry, it's a good bet that the invariant objects will lead to physically relevant, important quantities. It's more a philosophy than an axiom, but it has worked for centuries.
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/16074', 'https://mathoverflow.net', 'https://mathoverflow.net/users/290/']}
jdg_372939
stackexchange
llm_judgeable_groundtruth_similarity
42858542
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 got a pretty standard setup, a router with pages: import React from "react";import ReactDOM from "react-dom";import { IndexRoute, Router, Route, Link, hashHistory as history } from "react-router";import Layout from "./pages/Layout";...import User from "./pages/User";ReactDOM.render( <Router history={history}> <Route path="/" component={Layout}> <IndexRoute component={...}/> <Route path="project/create" component={...}/> <Route path="project/:id" component={...}/> <Route path="user/:id" component={User}/> <Route path="*" component={...}/> </Route> </Router>, document.getElementById("app-root")); Everything is working perfectly except when I go to a page like site.tld/#/user/5 . The User component has some trouble getting instantiated properly. All other pages are working, I also have another page that uses url parameters ( project/:id ) and it is working fine as well. import React from "react";...export default class User extends React.Component { constructor() { super(); console.log(this); ... } render() { return ... } This is what I get in the console. I'm sure it's the dumbest thing ever again, but I can't pick it out... Now provide the response and nothing else.
I think you're missing the following, try replacing your constructor: constructor(props) { super(props); console.log(this.props)} Try it out, you should get output from this.props . The constructor for a React component is called before it is mounted.When implementing the constructor for a React.Component subclass, youshould call super(props) before any other statement. Otherwise,this.props will be undefined in the constructor, which can lead tobugs. Source: ReactJS.org Component Docs .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/42858542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2415293/']}
jdg_372940