source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0046530285.txt" ]
Q: Retrieve response headers from including external javascript file I am looking for a way to include an external .js file and receive the response headers from that request. <script src="external/file.js?onload=callback"> function callback(data) { data.getAllResponseHeaders(); } </script> Obviously, this doesn't seem to work. How do I get the response header from including the javascript? It can not be a second request. In your answer, please avoid using jQuery. Thanks for any help. WORKING EXAMPLE Thanks to gaetanoM oXmlHttp.withCredentials = true; is for CORS oXmlHttp.responseType = 'text'; is for DOM input? Here is the code I use now; <script> function loadScript(url) { var oXmlHttp = new XMLHttpRequest(); oXmlHttp.withCredentials = true; oXmlHttp.responseType = 'text'; oXmlHttp.open('GET', url, true); oXmlHttp.onload = function () { if( oXmlHttp.status >= 200 || oXmlHttp.status == XMLHttpRequest.DONE ) { var x = oXmlHttp.getAllResponseHeaders(); console.log(x); if(oXmlHttp.responseText !== null) { var oHead = document.getElementsByTagName('HEAD').item(0); var oScript = document.createElement("script"); oScript.language = "javascript"; oScript.type = "text/javascript"; oScript.defer = true; oScript.text = oXmlHttp.responseText; oHead.appendChild(oScript); } } } oXmlHttp.send(); } loadScript("http://url/to/file.js"); </script> A: getAllResponseHeaders(): The XMLHttpRequest.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string, or null if no response has been received. If a network error happened, an empty string is returned. That means you need to load the external js with a XMLHttpRequest: Moreover, in this way you load only one time the file. function loadScript(url) { var oXmlHttp = new XMLHttpRequest(); oXmlHttp.onreadystatechange = function () { if (oXmlHttp.readyState == XMLHttpRequest.DONE) { if (oXmlHttp.status == 200) { var x = oXmlHttp.getAllResponseHeaders(); console.log(x); if (oXmlHttp.responseText != null) { var oHead = document.getElementsByTagName('HEAD').item(0); var oScript = document.createElement("script"); oScript.language = "javascript"; oScript.type = "text/javascript"; oScript.text = oXmlHttp.responseText; oHead.appendChild(oScript); } } else { console.log("Error", oXmlHttp.statusText) } } } oXmlHttp.open('get', url); oXmlHttp.send(); } loadScript("11.js?onload=callback");
[ "stackoverflow", "0012023688.txt" ]
Q: Error in controller. Unexpected $end, expecting keyword_end My controller by nifty generators is having some block related problems. I'm quite new to rails, so no doubt it's a simple problem. Here is my error: /home/forrest/.rvm/gems/ruby-1.9.2-p320@global/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `require': /home/forrest/code/luxeldb/app/models/maintenance_record.rb:16: syntax error, unexpected $end, expecting keyword_end (SyntaxError) and here is my controller: class MaintenanceRecordsController < ApplicationController def index @maintenance_records = MaintenanceRecord.find(:all) end def show @maintenance_record = MaintenanceRecord.find(params[:id]) end def new @maintenance_record = MaintenanceRecord.new end def create @maintenance_record = MaintenanceRecord.new(params[:maintenance_record]) if @maintenance_record.save redirect_to @maintenance_record, :notice => "Successfully created maintenance record." else render :action => 'new' end end def edit @maintenance_record = MaintenanceRecord.find(params[:id]) end def update @maintenance_record = MaintenanceRecord.find(params[:id]) if @maintenance_record.update_attributes(params[:maintenance_record]) redirect_to @maintenance_record, :notice => "Successfully updated maintenance record." else render :action => 'edit' end end def destroy @maintenance_record = MaintenanceRecord.find(params[:id]) @maintenance_record.destroy redirect_to maintenance_records_url, :notice => "Successfully destroyed maintenance record." end end A: Reading directly from the error message, the syntax error is in your /home/forrest/code/luxeldb/app/models/maintenance_record.rb file, not the controller. You've missed an end keyword out, which Ruby spotted because it reached the end of the file ($end) when it was still waiting for an end keyword
[ "stackoverflow", "0059802129.txt" ]
Q: How do you insert a column into an existing csv file? I'm a complete newb to Python and need some direction on how to go about inserting a column into an existing csv file with data=today's date included. I would appreciate any guidance/insight you may provide. Thank you in advance! AJ A: You should do a little background search on working with csv's in Python. There is a bunch of good articles / tutorials. Most use the csv module as a convenience and for features, but it isn't necessary. The basic schema to modify (as suggested above in comments) is to: open the file you want to read open another file that will hold the modified results walk through the file being read line-by-line either compute the new value if you need to, or just append it to the line write it to the new file close both files Here is an example using csv module: import csv input_file = 'data.csv' output_file = 'data_mod.csv' with open(output_file, 'w') as target: target_writer = csv.writer(target) # open the source with open(input_file, 'r') as source: source_reader = csv.reader(source) # now both are "open and ready" # fix the header row, assuming there is one by reading 1 line header = source_reader.__next__() # csv reader returns a list for the rows read, so header is a list, # we can just add to it header.append('sum') # write to the modified file target_writer.writerow(header) # now use loop to update all remaining rows for row in source_reader: sum = int(row[0]) + int(row[1]) row.append(sum) target_writer.writerow(row) # if you use the 'with' command structure, it will close the files automatically print('done') The original file: value 1,value 2 1,2 3,4 -2,2 the modified file, data_mod.csv: value 1,value 2,sum 1,2,3 3,4,7 -2,2,0
[ "stackoverflow", "0053501252.txt" ]
Q: While executing my project in angular6 its executing only index.html page only, what are the reasons? I had created one project for login form, here am attaching screenshot of program, while am executing my project it is showing only index page and waited for some time but still showing only index page, here am attaching output screenshot, A: If you want to display a login page as a default page when user serves the application then you have to configure your app.module.ts to handle these type of URL. So the changes that you required is as: In app.module.ts: Import RouterModule from angular/router: import { RouterModule } from '@angular/router'; and in imports Array add RouterModule.forRoot([ { path: '', redirectTo: '/login', pathMatch: 'full' }, { path: 'login', component: LoginComponent } ]) and in app.component.html: <router-outlet></router-outlet>
[ "stackoverflow", "0045966832.txt" ]
Q: Selectlist binding for multiple rows of data in asp.net mvc I have an issue where I have a list of objects: List<MenuProduct> MenuProducts; Where the MenuProduct consists of: public class MenuProduct { public int MenuProductID { get; set; } public int LoginID { get; set; } public int ContractTypeID { get; set; } public int? ContractID { get; set; } public string Title { get; set; } public decimal? Factor { get; set; } public int OrderNum { get; set; } public System.DateTime DateCreated { get; set; } public int UserCreated { get; set; } public decimal DiscountedRate { get; set; } public decimal? JointFactor { get; set; } } And the (partial) model: public List<MenuProduct> MenuProducts { get; set; } public SelectList ContractTypes { get; set; } public SelectList Contracts { get; set; } And I am binding them in the view like this: @for (int i = 0; i < Model.MenuProducts.Count(); i++) { <tr> <td>@Html.TextBoxFor(x => x.MenuProducts[i].Title, new { @class = "form-control" })</td> <td>@Html.TextBoxFor(x => x.MenuProducts[i].Factor, new { @class = "form-control" })</td> <td>@Html.TextBoxFor(x => x.MenuProducts[i].JointFactor, new { @class = "form-control" })</td> <td>@Html.DropDownListFor(x => x.MenuProducts[i].ContractTypeID, Model.ContractTypes, new { @class = "form-control" })</td> <td>@Html.DropDownListFor(x => x.MenuProducts[i].ContractID, Model.Contracts, new { @class = "form-control" })</td> </tr> } The issue that I am having is that when the data is loaded, because I am using shared lists for Contracts and ContractTypes, the SelectLists are never selected with the proper values. If I move each item to a partial view like this: @for (int i = 0; i < Model.MenuProducts.Count(); i++) { @Html.RenderPartial("_MenuProductItemPartialView", new MenuProductItemModel() { Item = Model.MenuProducts[i], ContractTypes = Model.ContractTypes, Contracts = Model.Contracts}) } With this model: public MenuProduct Item { get; set; } public SelectList ContractTypes { get; set; } public SelectList Contracts { get; set; } The values in the select lists are correct, but then I can't have a button on the outer page that updates all the rows at once - at least, I don't know how to do that. So my question is: how do I get the select lists to work the first way (where I can post back the List<MenuProduct>) OR how do I collect all of the updated data from each partial the second way? Because there could be data that has changed from any row or many rows. A: You can construct a SelectList on the fly for each row with your selected value and it should work. @Html.DropDownListFor(x => x.MenuProducts[i].ContractTypeID, new SelectList(Model.ContractTypes, "Value", "Text", Model.MenuProducts[i].ContractTypeID), new { @class = "form-control" })
[ "stackoverflow", "0029202775.txt" ]
Q: php://input found on url I am running my website under IIS with asp.net as my language. errors encountered in my site are sent to me via email when I found something containing php://input like MySite/Page?id=php://input my questions are, what does php://input do? can php queries be executed on IIS Servers? Thanks for your answers and time A: This looks most likely like an automated hacking attempt looking for injection vulnerabilities of a PHP application. Nothing you need to be concerned of with ASP.net. Basically PHP allows some URLs in file names. So the idea of the hack is to use one of those URLs to see if the input strings are used unvalidated.
[ "stackoverflow", "0044691792.txt" ]
Q: Filtering list of objects I rendered a list using Redux and there is a search field to find movies that include the search keyword. My list is an object not an array and if user types: "The" it should filter the list that has 'The' in the title. {'1': { 'title': 'A Name' },'2': { 'title': 'The Name' },'3': { 'title': 'The Second Name' }} So the result after filter should be {'2': { 'title': 'The Name' },'3': { 'title': 'The Second Name' }} How would you do that? Using lodash is a bonus. Thanks A: You cay use _.pickBy() as a filter for objects, check if each sub object title _.includes() the search word: const data = {'1': { 'title': 'A Name' }, '2': { 'title': 'The Name' }, '3': { 'title': 'The Second Name' }}; const result = _.pickBy(data, (v) => _.includes(v.title, 'The')); console.log(result); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
[ "aviation.stackexchange", "0000036060.txt" ]
Q: How is the camber calculated? In this picture, how do you determine the amount of the camber? Is it the average difference in the distances between the mean camber line and the chord line from the leading edge all the way down to the trailing edge? A: The mean camber line is the locus of points halfway between the top surface and the bottom surface (which are sometimes referred as upper and lower cambers). For a symmetrical airfoil, it is merged with the chord line. This curve is described by a polynomial function at each point along the chord axis. An airfoil may have a camber line which changes direction at one or more point, and which possibly crosses the chord. All measures are taken perpendicular to the chord which is considered having a length of 1 or 100%. Adapted from Wikipedia. What you ask for is the maximum camber, which is determined by the value of the maximum difference between chord and mean camber line, and the distance from the leading edge. Adapted from Wikipedia.
[ "serverfault", "0000859698.txt" ]
Q: Active / Passive HA Proxy : Floating IP not "floating" I am setting up HA Proxy in Active/Passive mode. haproxy-a : 172.29.240.172 haproxy-b : 172.29.240.173 Floating IP (VIP) : 172.29.240.188 Before any config : [root@haproxy-a/b ~]# cat /etc/redhat-release Red Hat Enterprise Linux Server release 7.3 (Maipo) [root@haproxy-a ~]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 00:50:56:9b:22:86 brd ff:ff:ff:ff:ff:ff inet 172.29.240.172/26 brd 172.29.240.191 scope global ens160 valid_lft forever preferred_lft forever [root@haproxy-b keepalived]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 00:50:56:9b:2b:a6 brd ff:ff:ff:ff:ff:ff inet 172.29.240.173/26 brd 172.29.240.191 scope global ens160 valid_lft forever preferred_lft forever Steps that Ive done. Configure keepalived on both servers haproxy-a/b # yum install -y keepalived [root@haproxy-a ~]# cat /etc/keepalived/keepalived.conf vrrp_script chk_haproxy { script "killall -0 haproxy" interval 1 weight -90 } vrrp_instance VI_1 { interface ens160 #interface to monitor state MASTER virtual_router_id 51 priority 100 # highest priority wins the election of master virtual_ipaddress { 172.29.240.188 } track_script { chk_haproxy } } [root@haproxy-b ~]# cat /etc/keepalived/keepalived.conf vrrp_script chk_haproxy { script "killall -0 haproxy" interval 1 weight -10 } vrrp_instance VI_1 { interface ens160 #interface to monitor state BACKUP virtual_router_id 51 priority 50 # highest priority wins the election of master virtual_ipaddress { 172.29.240.188 } track_script { chk_haproxy } } I then start the keepalived service on both nodes. firewalld & iptables is stopped and no other configurations were changed on the OS level. Once keepalived is up, I do not see the floating IPs assigned to either system. System logs on both nodes say : Jul 6 13:26:51 haproxy-a Keepalived_vrrp[1862]: ip address associated with VRID not present in received packet : 172.29.240.188 Jul 6 13:26:51 haproxy-a Keepalived_vrrp[1862]: one or more VIP associated with VRID mismatch actual MASTER advert Jul 6 13:26:51 haproxy-a Keepalived_vrrp[1862]: bogus VRRP packet received on ens160 !!! Jul 6 13:26:51 haproxy-a Keepalived_vrrp[1862]: VRRP_Instance(VI_1) Dropping received VRRP packet... A: Each logical node in keepalived must have it's own unique virtual_router_id on broadcast domain.
[ "stackoverflow", "0017024846.txt" ]
Q: Confluence: Accessing multiple values from param I am trying to create a user macro in confluence that creates a number of links (can be however many) based on user input. The 2 params I use look like this: ## @param LNK:title=Link|type=string|required=true|multiple=true ## @param TTL:title=Title|type=string|required=true|multiple=true The user will input something like this: Link: link_1, link_2, link_3 Title: title_1, title_2, title_3 The macro should then create a list of links like this: <a href="http://mysite.com/link_1">title_1</a>; <a href="http://mysite.com/link_2">title_2</a>.... My question is: how can I access the content of the LNK/TTL param so that I can retrieve link_1, link_2, etc.? I need to get some kind of index so that I can correctly link LNK[1] to TTL[1]. Any help is welcomed! Thank you! A: Ok, so I found a way (which seems a bit complicated) to do what I needed. Here's the code: ## @param VTP:title=VTP Number|type=string|required=true|multiple=true|desc=VTP number from JIRA (ex: VTP-1) ## @param TCI:title=Test Case Identifier |type=string|required=true|multiple=true|desc=Test Case Identifier (ex: IN_TC01) #set ($LVTP = []) #set ($LTCI = []) #set ($VTP = $paramVTP.split(";")) #set ($TCI = $paramTCI.split(";")) #foreach ($element in $VTP) #set ($xxx = $LVTP.add($element)) #end #foreach ($element in $TCI) #set( $xxx = $LTCI.add($element)) #end #set ($end = ($LVTP.size() - 1)) #foreach ($i in [0..$end]) [<a href="http://myconfluence.com/browse/$LVTP.get($i)" target="_blank">$LTCI.get($i)</a>] #end I had to do this since it seems that the only way to access the content of an array ($VTP and $TCI in my case) in Confluence if through the #foreach loop. Things like arrays.asList didn't work for me. If anyone has a more elegant solution, please let me know.
[ "stackoverflow", "0009894360.txt" ]
Q: C# Math.pow(x, 0.333) private double f(double x, double zn = 1) { double X = - zn; X *= x * x * (x + 1); X *= Math.Pow((x - 2), 0.333); return funct ? x : X; } I have this code. When I try to find Math.Pow((x-2), 0.333) - i have NaN. How to solve it? Why NaN? Rewritten... private double f(double x, double zn = 1) { double answer = - zn; answer *= x * x * (x + 1); answer *= Math.Pow((x - 2), 0.333); return answer; } A: My guess is that you're taking the cube root of a negative number. That seems the most likely cause, but your code is really hard to read due to having both x and X as local variables... After closer examination, as you're not actually modifying x at any point, it really depends on the incoming value of x. If it's a finite value greater than or equal to 2, it should be fine. But if x is smaller than 2, it will fail (well, return NaN) for reasons of simple maths... A: You can see there all 3 cases when Math.Pow returns NaN: http://msdn.microsoft.com/en-us/library/system.math.pow.aspx public static double Pow(double x, double y) 1) x or y = NaN. 2) x < 0 but not NegativeInfinity; y is not an integer, NegativeInfinity, or PositiveInfinity. 3) x = -1; y = NegativeInfinity or PositiveInfinity.
[ "stackoverflow", "0061027875.txt" ]
Q: How to test all possible combinations with True/False Statement in python? I have two DataFrames where each column contain True/False statements. I am looking for a way to test all possible combinations and find out where "True" for each row in df1 also is "True" in the corresponding row in df2. In reference to the data below, the logic would be something like this: For each row, starting in column "Main1", test if row is equal to True and if row in column "Sub1" also is True. Next, test if row in "Main1" is equal to true and if rows in column "Sub1" is True and column "sub2" also is True. In this case, if all values are True, the output would be True. Then repeat for all columns and all possible combinations. df1: Main1 Main2 Main3 0 True False True 1 False False False 2 False True True 3 False False True 4 False True True 5 True True True 6 True False False df2: Sub1 Sub2 Sub3 0 False False True 1 False True False 2 True False True 3 False False False 4 True True False 5 False False False 6 True True True The output would be similar to something like this. Of course, I could do this manually but it would be timely as well as there would be rooms for errors. Main1Sub1 Main1Sub1Sub2 ... Main3Sub2Sub3 Main3Sub3 0 False False ... False True 1 False False ... False False 2 False False ... False True 3 False False ... False False 4 False False ... False False 5 False False ... False False 6 True True ... False False [7 rows x 18 columns] Any help on how to tackle this problem is appreciated! A: You can use the combinations() function in itertools to extract all the possible combinations of the columns of the 2 data frames, and then use the product() function in pandas to identify the rows where all the columns in the considered combination are equal to True. I included an example below, which considers all combinations of either 2 or 3 columns. import pandas as pd from itertools import combinations df1 = pd.DataFrame({"Main1": [True, False, False, False, False, True, True], "Main2": [False, False, True, False, True, True, False], "Main3": [True, False, True, True, True, True, False]}) df2 = pd.DataFrame({"Sub1": [False, False, True, False, True, False, True], "Sub2": [False, True, False, False, True, False, True], "Sub3": [True, False, True, False, False, False, True]}) df3 = df1.join(df2) all_combinations = list(combinations(df3.columns, 2)) + \ list(combinations(df3.columns, 3)) for combination in all_combinations: df3["".join(list(combination))] = df3[list(combination)].product(axis=1).astype(bool) df3.drop(labels=["Main1", "Main2", "Main3", "Sub1", "Sub2", "Sub3"], axis=1, inplace=True) df3 Main1Main2 Main1Main3 ... Main3Sub2Sub3 Sub1Sub2Sub3 0 False True ... False False 1 False False ... False False 2 False False ... False False 3 False False ... False False 4 False False ... False False 5 True True ... False False 6 False False ... False True
[ "superuser", "0000095736.txt" ]
Q: Is there a POSIX pathname that can't name a file? Are there any legal paths in POSIX that cannot be associated with a file, regular or irregular? That is, for which test -e "$LEGITIMATEPOSIXPATHNAME" cannot succeed? Clarification #1: pathnames By "legal paths in POSIX", I mean ones that POSIX says are allowed, not ones that POSIX doesn't explicitly forbid. I've looked this up, and the are POSIX specification calls them character strings that: Use only characters from the portable filename character set [a-zA-Z0-9._-] (cf. http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap03.html#tag_03_276); Do not begin with -; and Have length between 1 and NAME_MAX, a number unspecified for POSIX that is not less than 14. POSIX also allows that filesystems will probably be more relaxed than this, but it forbids the characters NUL and / from appearing in filenames. Note that such a paradigmatically UNIX filename as lost+found isn't FPF, according to this def. There's another constant PATH_MAX, whose use needs no further explanation. The ideal answer will use FPFs, but I'm interested in any example with filenames that POSIX doesn't expressly forbid. Clarification #2: impossibility Obviously, pathnames normally could be bound to a file. But UNIX semantics will tell you that there are special places that couldn't normally have arbitrary files created, like in the /dev directory. Are any such special places stipulated in POSIX? That is what the question is getting after. A: Testing for a filename with the null character in it should always fail. POSIX reserves '/' and null from filenames. This is sensible: one is the directory separator, and one is a string terminator. To support that point, Wikipedia says ext2, ext3, and ext4 allow all bytes in filenames except null and the forward slash. NTFS, whether or not in POSIX-compatibility mode, disallows little more than that; and FAT variants also disallow null. In theory, it really depends on the file system. But I wouldn't hold my breath trying to find a case where null finds its way into a filename. A: Since the final question is whether there are special places that couldn't normally have a file, like in the /dev directory stipulated in POSIX, then the andswer is YES. The complete list of pre-determined files and directories is given in chapter 10, POSIX Directory Structure and Devices, of the IEEE Open Group Base Specifications Issue 6: The following directories shall exist on conforming systems and conforming applications shall make use of them only as described. Strictly conforming applications shall not assume the ability to create files in any of these directories, unless specified below. / The root directory. /dev Contains /dev/console, /dev/null, and /dev/tty, described below. The following directory shall exist on conforming systems and shall be used as described: /tmp A directory made available for applications that need a place to create temporary files. Applications shall be allowed to create files in this directory, but shall not assume that such files are preserved between invocations of the application. The following files shall exist on conforming systems and shall be both readable and writable: /dev/null An infinite data source and data sink. Data written to /dev/null shall be discarded. Reads from /dev/null shall always return end-of-file (EOF). /dev/tty In each process, a synonym for the controlling terminal associated with the process group of that process, if any. It is useful for programs or shell procedures that wish to be sure of writing messages to or reading data from the terminal no matter how output has been redirected. It can also be used for applications that demand the name of a file for output, when typed output is desired and it is tiresome to find out what terminal is currently in use. The following file shall exist on conforming systems and need not be readable or writable: /dev/console The /dev/console file is a generic name given to the system console (see System Console). It is usually linked to an implementation-defined special file. It shall provide an interface to the system console conforming to the requirements of the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
[ "stackoverflow", "0062198049.txt" ]
Q: How to create a Flutter background service that works also when app closed I am developing a Flutter app for academic purposes in university. Now, I need to run a sort of "always on" background service in order to use Bluetooth and most importantly to get periodic updates from external REST APIs. I've already checked those two libraries from pub.dev (this and this) without finding the perfect solution that works out-of-the-box (as expected...). I also saw something native with Kotlin (here). What I would to know is what is the best option in order to achieve my goals (in terms of best practices, completeness and with simplicity in mind). Have a look at the following image for a more schematic view: A: For this kind of things you have to rely on native mechanisms. The most efficient way to deal with APIs in an "always existent" background component is to implement a push notification service. Using that kind of tech a remote server is capable of starting communication with your app, awaken it and then perform whatever task needs to be performed. Also, in Android, you have foreground services which will run even if the app is closed.
[ "networkengineering.stackexchange", "0000005344.txt" ]
Q: Cisco: storm-control unicast Within a typical service provider environment I can see how broadcast and multicast storm control can be useful. I am confused regarding unicast storm control though. Reading the Cisco docs online they give examples such as protecting against port flooding if the destination MAC of an incoming frame isn't in the CAM tables. This makes good sense to me. So does storm-control unicast only measure the pps rate (or bps rate) of frames that are for destinations not in the CAM tables, or all destinations that aren't a broadcast or multicast address (so just the total number of unicast frames)? I'm worried that configuring such a feature could shut a port down that shouldn't be shut down simply because it has a high pps rate. An example of this is ports with voice services attached that have high frame rates but are low bpp rates of unicast frames. Is this feature only measuring the frame/packet rate of unknown destination addresses or all unicast frames, what are the dangers here? A: So does storm-control unicast only measure the pps rate (or bps rate) of frames that are for destinations not in the CAM tables, or all destinations that aren't a broadcast or multicast address (so just the total number of unicast frames)? I have to confess that I mistakenly trusted the Nexus doc below which said only unknown unicast is rate-limited; however, that's definitely wrong for Cisco IOS. The reality is (at least on IOS platforms) that unicast storm control affects all unicast traffic; the Cisco Nexus doc I quoted said it only affected traffic that was unknown unicast. I will endeavor to test on Nexus at a later date. In an effort to atone for my mistake, I built a quick screencast of what happens when I: Configure a Cisco IOS switch with unicast storm-control to throttle at 1Mbps. Use speedtest_cli.py to start a unicast download from speedtest.net Reconfigure the switch without unicast storm control Download from speedtest.net again... Hit your refresh button to restart the screencast at the beginning Bottom line Unicast storm-control affects all unicast traffic in Cisco IOS Unicast storm-control is applied on traffic inbound to the switchport My Original quote from the Nexus docs, which I applied to the OP's Cisco 2960 Quoting the Nexus Storm Control Docs (emphasis mine): "You can use the traffic storm control feature to prevent disruptions on Layer 2 ports by a broadcast, multicast, or unknown unicast traffic storm on physical interfaces. " Storm control operates the same way across Cisco platforms; if the destination-mac-address is not in the CAM table, then then the switch must flood it out all ports in the Vlan (except the one it came in on). Suffient quantities of this kind of traffic would trigger your Unicast Storm Control thresholds.
[ "stackoverflow", "0014722010.txt" ]
Q: Remove extra part in remoteClientAddress string in .xslt in MULE server 3.3.0 CE? In my configuration.xml in MULE server 3.3.0 CE, I pass MULE_REMOTE_CLIENT_ADDRESS to .xslt file, below I copied my codes : <logger message="#[message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS']]" level="INFO" doc:name="Logger"/> To pass IP address to XSLT, store it in a variable and pass that. <set-variable variableName="remoteClientAddress" value = "#[message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS']]"/> Pass it to XSLT as: <xm:xslt-transformer xsl-file="xsltFileName.xslt"> <xm:context-property key="remoteClientAddress" value="#[remoteClientAddress]"/> </xm:xslt-transformer> In my XSLT, declared a param variable <xsl:param name="remoteClientAddress" /> and then use this variable as <xsl:value-of select="$remoteClientAddress" /> But in configuration.xml file I use this : <logger message="Remote client address is------> #[remoteClientAddress]" level="INFO" doc:name="Logger"/> for checking IP-Address, but in my MULE Console I saw this statement : /127.0.0.1:51708 while I need to 127.0.0.1 I don't need / before ip-address and :51708 at the end of my ip-address. How can I remove these extra parts in Configuration.xml in mule and then just send ip-address to .xslt file ? A: I don't know anything about Mule, but you could just do this: <xsl:param name="remoteClientAddress" /> <xsl:variable name="remoteClientAddressTrimmed" select="substring-before(substring-after($remoteClientAddress, '/'), ':')" /> and then later <xsl:value-of select="$remoteClientAddressTrimmed" />
[ "webmasters.stackexchange", "0000086313.txt" ]
Q: Does 'thin-content' content on some pages affect overall site SEO? I have an UGC Q&A site. Due to it's nature is inevitable to see some 'thin' or low quality content in some posts. Will there be any sitewide impact in SEO for the other high quality pages? If yes which will be the best way to handle this to mitigate the impact? A: There is the potential for site wide impact but more often than not you will find a page specific impact occurring first. With any website with user generated content you need to invest your time in moderation or establish some community driven moderation (like Stack Exchange) in order to quickly catch out content that is of low quality and could affect your ranking. As a basic rule of thumb if poor quality content is identified and removed within a few hours it is unlikely to cause a substantial hit to your site as Google does encourage moderation of user generated content. If we use Stack Exchange as an example there are a large number of poor quality posts that come up on any given day and yet Stack Exchange sites still rank extremely highly within Google, and the reason for this is proactive moderation, in effect every member of the site is a moderator as anyone (starting from a very low rep level) can flag content for moderator attention and beyond a certain reputation users are deemed to have been part of the community long enough to know what belongs and what doesn't belong and so they are given access to a range of moderation tools.
[ "stackoverflow", "0040720619.txt" ]
Q: How to perform join on MySQL (JDBC) with Spark? I would like to read data from MySQL through Spark. The API which I saw is able to read data from specific table. something like, val prop = new java.util.Properties prop.setProperty("user", "<username>") prop.setProperty("password", "<password>") sparkSession.read.jdbc("jdbc:mysql://????:3306/???", "some-table", prop) Now, I would like to perform a query for join tables. Does anyone know how to do it (on the database side, not with Spark SQL) ? Thanks, Eran A: You'll need to use the "table " argument as a query: val table = "(SELECT foo JOIN bar ON foo.id = bar.id) as t" spark.read.jdbc("jdbc:mysql://????:3306/???", table, prop) You should note that giving an alias to your query is important or this won't work.
[ "stackoverflow", "0058258537.txt" ]
Q: Converting function to promise chain in Lambda I am trying to convert my lambda code to run in a promise chain, but I'm not certain of the proper method to approach this. I am trying to modify my current code to run these actions, send email -> add to newsletter list if checkbox is checked, but my email portion runs successfully and then throws an error after I try to chain the add to newsletter function after generateResponse(result, 200) Here is my error: TypeError: generateResponse(...).then is not a function Here is the code: Main function: module.exports.sendEmail = async event => { const { body } = event; const data = JSON.parse(body); try { const result = await messageContent(data); return generateResponse(result, 200) .then(function(){ if(data.subscribe == "on"){ return addToNewsletter(data.from, data.topic) .then(function(result){ return generateResponse(result, 200); }); } }); } catch(err) { console.log(err) } }; generateResponse: const generateResponse = (body, statusCode) => { console.log("generateResponse") console.log(body) return { headers: { "access-control-allow-methods": "POST", "access-control-allow-origin": "*", "content-type": "application/json" }, statusCode: statusCode, body: `{\"result\": ${body.message}}` }; }; addToNewsletter: const addToNewsletter = (email, topic) => { const mg = mailgun({apiKey: API_KEY, domain: NEWSLETTER_DOMAIN}); const list = mg.lists(`newsletter@{DOMAIN}`); console.log(list) const subscriber = { address: email, vars: { topic: topic }, subscribed: "yes", upsert: "yes" }; console.log(subscriber); return list.members().create(subscriber, function(err, data){ console.log(data); console.log(err); }); } A: You are not returning any promise from generateResponse function. Hence the error .then() is not a function. Try changing your function to return a promise like below. const generateResponse = (body, statusCode) => { console.log("generateResponse") console.log(body) return Promise.resolve({ headers: { "access-control-allow-methods": "POST", "access-control-allow-origin": "*", "content-type": "application/json" }, statusCode: statusCode, body: `{\"result\": ${body.message}}` }); };
[ "stackoverflow", "0006785731.txt" ]
Q: Alter table column to add constraint and where column is not null I have this: alter table supplier add constraint supplier_unique unique (supplier_id) where supplier_id is not null; but I am getting an error. The resulting definition should be: CREATE UNIQUE INDEX supplier_unique ON supplier (supplier_id) WHERE (supplier_id IS NOT NULL) Thanks. A: A unique constraint in PostgreSQL doesn't have a WHERE clause so you're getting a syntax error at "where". In any case, supplier_id is not null is not necessary with a unique constraint: In general, a unique constraint is violated when there is more than one row in the table where the values of all of the columns included in the constraint are equal. However, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard, ... So all you need is this: alter table supplier add constraint supplier_unique unique (supplier_id); And your unique constraint will be added, you can have multiple rows with supplier_id IS NULL, and you'll get your index as a side effect of the unique constraint. However, if you want to create the index directly you can create a partial index with a predicate: When the WHERE clause is present, a partial index is created. A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table. [...] Another possible application is to use WHERE with UNIQUE to enforce uniqueness over a subset of a table. But in the case of NULLs, a partial index for supplier_id IS NOT NULL won't do anything for the uniqueness because PostgreSQL unique constraints already allow multiple NULL values (probably because of the standard and because x = NULL is false for all x). So if your intent is too limit the uniqueness to non-NULL values then you don't need your partial index; but, if you just want to avoid indexing NULL values then you could do it through CREATE INDEX (but not ALTER TABLE). I don't know if leaving NULLs out of your index would have any noticeable effect though. I think part of the confusion (yours and mine) is that UNIQUE is both a constraint and an index. You can include a WHERE when you create it as an index but not when you create it as a constraint. This is certainly inconsistent.
[ "gis.stackexchange", "0000157445.txt" ]
Q: Share FME workflows with other organizations Can we publish FME Workbenches to GitHub, to enable sharing these with other organizations.A custom transformer might be a solution? A: You can publish to fme store. This would allow other fme users to directly access the workbench. Safe also has their own github. So the short answer is yes. But using your own other users would not have a way to discover you as easily as if you use the Safe methods.
[ "security.stackexchange", "0000127502.txt" ]
Q: Can a .DER be converted to a .PFX / .P12 ? Burp-Suite's http://burp/cert:8080 web-interface for downloading the CA Certificate only provides a .der encoded certificate, but for a particular use-case scenario I require a PKCS#12 .pfx/.p12. I can find a lot of information regarding the conversion from .der to .pem and also the conversion from .pem to .pfx/.p12, but nothing for converting directly from .der to .pfx/.p12: .der > .pem openssl x509 -inform der -in certificate.der -out certificate.pem .pem > .pfx/.p12 openssl pkcs12 -export -in certificate.pem -out certificate.p12 Can I convert directly from .der to .pfx/.p12? Do I need a .key (not provided via http://burp/cert:8080) in order to do the conversion? Will the .pfx/.p12 even be of any use to me (and Burp-Suite) without the .key rolled in? A: Can I convert directly from a .der to a .pfx/.p12? I don't think so because Openssl uses PEM encoding for certificates by default unless you set it explicitly using -inform or -outform arguments. There is no such option listed in the pkcs12 command. Do I need a .key (not provided via http://burp/cert:8080) in order to do the conversion? You don't have to provide a key for PKCS12 command if you use -nodes option. With this option openssl do not use encryption for the file created. Will the .pfx/.p12 even be of any use to me (and Burp-Suite) without the .key rolled in? In your case, Yes. Because that you will only store your certificates in that file you do not need it to be encrypted. Note that, PKCS12 file format is generally used to store private keys with their corresponding certificates in a single file format. In that case, you should use a key to keep your private keys in an encrypted file.
[ "math.stackexchange", "0001133536.txt" ]
Q: orientable manifold Let $M$ be an orientable manifold and let $f:M \to R$ be a smooth map. Show that if $0$ is a regular value of $f$ then ${f^{ - 1}}(0) \subseteq M$ is also an orientable manifold. A: The preimage $K$ is a manifold by the implicit function theorem. (Alternatively: this is one case of Lemma 4 in Milnor's "Topology from the differentiable viewpoint.") The gradient of $f$ is nonzero at every point of $K$ (because $0$ is a regular value). You can put an orientation on $K$ by saying that a frame $v_1, \ldots, v_{n-1}$ is "positively oriented" in $K$ iff $v_1, \ldots, v_{n-1}, \nabla f$ is positively oriented in $M$.
[ "mathoverflow", "0000359692.txt" ]
Q: Model categories and chain complexes I'm fairly new to thinking about homological algebra and chain complexes in their own right, i.e outside of isolated examples such as for constructing simplicial homology, or for computing $Ext$ groups for some Hopf algebroid. Given an abelian category $\mathscr{A}$ with a category of chain complexes $Ch(\mathscr{A})$, the homotopy category $K(\mathscr{A})$ is defined as the naive homotopy category (i.e. replace chain maps with chain homotopy classes of chain maps) but with quasi-isomorphisms inverted (these are the maps which induce isomorphisms on homology). This is obviously the result of placing some kind of model structure on $Ch(\mathscr{A})$. This leads me to consider a few obvious questions. Are there alternate, interesting model structures for $Ch(\mathscr{A})$? (How) has the advancement of model category theory impacted the study of things such as chain complexes, and perverse sheaves for example? Are there any good treatments of homological algebra which makes use of the rich theory of model categories? A: I'll take your question as license to advertise a relatively recent paper in a slightly more specialized but concretely calculational direction: http://nyjm.albany.edu/j/2014/20-53p.pdf. Its title is Six model structures for DG-modules over DGAs: Model category theory in homological action. The theme is how different model structures can illuminate concrete calculations. I had computed the cohomology of various homogeneous spaces, way back in the 1960's, using some strange looking explicit cochain complexes. Tobi Barthel, Emily Riehl and I found that those turn out to be explicit examples of a variant kind of cofibrant approximation. A: Yes, there are zillions of model structures on Ch(A), corresponding to whatever class of projectives you choose to use for your homological algebra. This is all spelled out in the paper "Quillen model structures for relative homological algebra" by Christensen and Hovey. More generally, the theory of cotorsion pairs builds model structures in many algebraic settings (including quasi-coherent sheaves; I'm not sure about perverse sheaves, not even if they satisfy bicompleteness as a category). Hovey's seminal paper is here. A great survey by Gillespie is here. This material has also appeared in books. A recent one by Marco Perez is here.
[ "stackoverflow", "0057046022.txt" ]
Q: Cannot properly read from file into struct member using InFile I have a program assignment to write a program that reads students’ names followed by their test scores. The program should output each student’s name followed by the test scores and the relevant grade. It should also find and print the highest test score and the name of the students having the highest test score. I use functions and structs, with arrays to accomplish this, and of course the expected InFile mechanics. However, I'm having issues storing the content from the file into the appropriate member, and cannot get anything stored at all. I've tried rewriting the function and placing it before and after the main function, to no avail, and renaming and restructuring my struct. My code is as follows. #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; struct studentType { string studentFName(); string studentLName(); int testScore(); char grade(); }; void getData(ifstream& inFile, studentType sList[], int listSize); void calculateGrade(studentType sList[], int listSize); int highestScore(const studentType sList[], int listSize); void printResult(ofstream& outFile, const studentType sList[], int listSize); int main() { //Variable Declaration const int STUDENTCOUNT = 20; ifstream inData; ofstream outData; studentType studentList[STUDENTCOUNT]; //Open file inData.open("Ch9_Ex2Data.txt"); //Call functions getData(inData, studentList, STUDENTCOUNT); calculateGrade(studentList, STUDENTCOUNT); printResult(outData, studentList, STUDENTCOUNT); system("PAUSE"); return 0; } //Data from Ch9_Ex2Data.txt function void getData(ifstream& inFile, studentType sList[], int listSize) { for (int i = 0; i < listSize; i++) inFile >> sList[i].studentFName >> sList[i].studentLName >> sList[i].testScore; } void calculateGrade(studentType sList[], int listSize) { int score; for (int i = 0; i < listSize; i++) if (score >= 90) sList[i].grade() = 'A'; else if (score >= 80) sList[i].grade() = 'B'; else if (score >= 70) sList[i].grade() = 'C'; else if (score >= 60) sList[i].grade() = 'D'; else sList[i].grade() = 'F'; } int highestScore(const studentType sList[], int listSize) { int score[100]; int highscore = score[0]; for (int i = 0; i < listSize; i++) { if (score[i] > highscore) { highscore = score[i]; } } } void printResult(ofstream& outFile, const studentType sList[], int listSize) { int maxScore = highestScore(sList, listSize); int i; outFile << "Student Name " << "Test Score" << "Grade" << endl; for (i = 1; i < listSize; i++) outFile << left << sList[i].studentLName() + ", " + sList[i].studentFName << right << " " << s List[i].testScore << " " << sList[i].grade << endl; outFile << endl << "Highest Test Score: " << maxScore << endl; outFile << "Students having the highest test score:" << endl; for (i = 1; i < listSize; i++) if (sList[i].testScore() == maxScore) outFile << sList[i].studentLName() + ", " + sList[i].studentFName << endl; } i = 1; i < listSize; i++) if (sList[i].testScore() == maxScore) outFile << sList[i].studentLName() + ", " + sList[i].studentFName << endl; } These are the error codes I'm receiving main.cpp: In function ‘void getData(std::ifstream&, studentType*, int)’: main.cpp:42:10: error: invalid use of non-static member function ‘std::__cxx11::string studentType::studentFName()’ inFile >> sList[i].studentFName >> sList[i].studentLName main.cpp:9:16: note: declared here string studentFName(); ^~~~~~~~~~~~ main.cpp: In function ‘void calculateGrade(studentType*, int)’: main.cpp:51:27: error: lvalue required as left operand of assignment sList[i].grade() = 'A'; ^~~ main.cpp:53:27: error: lvalue required as left operand of assignment sList[i].grade() = 'B'; ^~~ main.cpp:55:27: error: lvalue required as left operand of assignment sList[i].grade() = 'C'; ^~~ main.cpp:57:27: error: lvalue required as left operand of assignment sList[i].grade() = 'D'; ^~~ main.cpp:59:27: error: lvalue required as left operand of assignment sList[i].grade() = 'F'; ^~~ main.cpp: In function ‘int highestScore(const studentType*, int)’: main.cpp:73:5: warning: no return statement in function returning non-void [-Wreturn-type] } ^ main.cpp: In function ‘void printResult(std::ofstream&, const studentType*, int)’: main.cpp:82:45: error: passing ‘const studentType’ as ‘this’ argument discards qualifiers [-fpermissive] outFile << left << sList[i].studentLName() + ", " + sList[i].studentFName << right << " " << sList[i].testScore << " " << sList[i].grade << endl; ^ main.cpp:10:16: note: in call to ‘std::__cxx11::string studentType::studentLName()’ string studentLName(); ^~~~~~~~~~~~ main.cpp:82:54: error: invalid use of non-static member function ‘std::__cxx11::string studentType::studentFName()’ outFile << left << sList[i].studentLName() + ", " + sList[i].studentFName << right << " " << sList[i].testScore << " " << sList[i].grade << endl; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~ main.cpp:9:16: note: declared here string studentFName(); ^~~~~~~~~~~~ main.cpp:86:27: error: passing ‘const studentType’ as ‘this’ argument discards qualifiers [-fpermissive] if (sList[i].testScore() == maxScore) ^ main.cpp:11:13: note: in call to ‘int studentType::testScore()’ int testScore(); ^~~~~~~~~ main.cpp:87:38: error: passing ‘const studentType’ as ‘this’ argument discards qualifiers [-fpermissive] outFile << sList[i].studentLName() + ", " + sList[i].studentFName << endl; ^ main.cpp:10:16: note: in call to ‘std::__cxx11::string studentType::studentLName()’ string studentLName(); ^~~~~~~~~~~~ main.cpp:87:47: error: invalid use of non-static member function ‘std::__cxx11::string studentType::studentFName()’ outFile << sList[i].studentLName() + ", " + sList[i].studentFName << endl; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~ main.cpp:9:16: note: declared here string studentFName(); ^~~~~~~~~~~~ /bin/bash: line 4: ./a.out: No such file or directory A: struct studentType { string studentFName(); // function declaration string studentLName();// function declaration int testScore();// function declaration char grade();// function declaration }; You've just declared 4 methods in your struct. It should be: struct studentType { string studentFName; string studentLName; int testScore; char grade; };
[ "stackoverflow", "0021136623.txt" ]
Q: Wildcard search that retains wildcard match I'm trying to parse a text file in notepad++ to find any instance of a group ID: id=group00001 ... with the intention of adding a newline after each. As group IDs are different each time (but always 5 characters) I gather I need to use regular expression searches for wildcards. But I'm struggling to find a way to do so without wiping out the ID. For instance, a find and replace as follows: Find: id=group..... Replace: id=group.....\r\n Finds all of them, but replaces the ID with ".....". I can't get my head around the more complicated regular expression stuff that would solve my problem - can anyone point me in the right direction? Cheers! A: Try this: Find what:(group[\d]{5}) Replace with: \1\r\n What I'm saying is: Find every word group followed by a digit with five characters([\d]{5}) and then replace by all regex group 1 (which is the sentence inside the parenthesis) plus \r\n
[ "stackoverflow", "0021011044.txt" ]
Q: Django: Show reverse object relationship in templates In the templates page, when I want to cycle through the variables of an object related by a foreign key, I use the set.all function. For example: {% for object2_info in object1.object2_set.all %} {[object2_info.something}} {% endfor %} What I don't get is how can I do this in reverse? You would think it would be something like this: {% for object1_info in object2.object1_set.all %} {[object1_info.something}} {% endfor %} but, that's not the case. Any help would be appreciated. A: This depends on your model definitions. Let's assume you have the following many-to-many-relationship: class Autor(models.Model): name = models.CharField(max_length=42) class Entry(models.Model): title = models.CharField(max_length=21) authors = models.ManyToManyField(Author) Here, we can access the entries like in your first example, assuming we pass as Author object to our template: {% for entry in author.entry_set.all %} {{ entry.title }} {% endfor %} But there is no author_set on Entry, because we explicitly named it: authors. {% for author in entry.authors.all %} {{ author.name }} {% endfor %} You can read more about this in the official documentation.
[ "stackoverflow", "0032593788.txt" ]
Q: Retrieve name of output arguments within a function It is possible to use the function inputname to retrieve the workspace variable name passed in the call to the currently executing function. However, is there any equivalent function to obtain the name of the output arguments specified in the call to the currently executing function? Imagine I have the following function: function [a,b,c] = test(x) disp([ouputname(1),ouputname(2),ouputname(3)]) end When running this function: [my,name,is] = test(x) The expected result should be: mynameis A: Simply: no there isn't. Complicated: Matlab code is "compiled" on run-time, and there is no way, that it knows [my,name,is] before it returns the result of test(x). Workaround: if you want to ensure, that the strings used within the function are equal to the variables returned to the workspace, you can do the following using assignin: function test(x, varnames) a = 1; outputname{1} = varnames{1}; assigin('base', outputname{1}, a) ... c = 3; outputname{3} = varnames{3}; assigin('base', outputname{3}, c) disp([outputname{:}]) end and call your function like: text(x,{'my','name','is'}) and you will have exactly this variables in your workspace afterwards and your function output: "mynameis"
[ "stackoverflow", "0036481886.txt" ]
Q: jQuery find elements then make into comma separated list I have numerous text boxes on my page, and I want to add the values from them to another element when a button is clicked. However, my current code outputs the values like this: Value oneValue twoValue three I would much prefer for them to come out like this instead: Value one, Value two, Value three my current JS is like this: var textInput = $(".random-input").text(); $(".output-box").append(textInput); A: The issue is because the elements are all being interpreted together. To fix that you can map() the text values to an array and join() it: var textInput = $(".random-input").map(function() { return $(this).val(); }).get().join(', '); $(".output-box").text(textInput); Working example The above is assuming .output-box is a standard element. If it's another textbox, you'd need to use val(textInput). A: You can iterate through each input and then using join var textInput = []; $(".random-input").each(function() { textInput.push(this.value) }); $(".output-box").append(textInput.join(', ')); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' class='random-input' value='val1' /> <input type='text' class='random-input' value='val1' /> <input type='text' class='random-input' value='val1' /> <input type='text' class='random-input' value='val1' /> <input type='text' class='random-input' value='val1' /> <input type='text' class='random-input' value='val1' /> <input type='text' class='random-input' value='val1' /> <div class='output-box'></div>
[ "stackoverflow", "0015496939.txt" ]
Q: UIBarButtonItem with UIImage too wide I have a UINavigationBar and a UIToolbar (in separate views) which contain buttons and flexible space. The UIBarButtonItems' background is set like this: bgImage = [[UIImage imageNamed:@"MyBackgroundImage.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)]; [self setBackgroundImage:bgImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; Within the UINavigationBar, the items look just fine, optimal size and all. BUT, within the UIToolbar, the items are always stretched to at least the width of bgImage (100 points in this case): Any ideas why, or how to solve that? Please tell me if you need more info. A: This appears to be a bug in UIToolbar. I gave it a try and the only "fix" that worked for me was to manually set the width of the UIBarButtonItem: barButtonItem.width = 40f; This will work fine for buttons with images, but not for text buttons as the size of the text may vary due to localization.
[ "stackoverflow", "0003701987.txt" ]
Q: jQuery - unique control over a class using onChange I'm using jQuery colorpicker on an app. When a color is selected and being selected, the color is displayed in a span class ".swatch". However, when there are two color select options on a single page, the span.swatch will both display the same color as the color is being selected. (see screenshot). Screenshot here: http://cl.ly/2MUU Here is the code I'm using jQuery('.colorselect').ColorPicker({ onSubmit: function ( hsb, hex, rgb, el ) { jQuery(el).val(hex); jQuery(el).ColorPickerHide(); }, onBeforeShow: function () { jQuery(this).ColorPickerSetColor(this.value); }, onChange: function (hsb, hex, rgb) { jQuery('.swatch').css('backgroundColor', '#' + hex); } }) A: Try this $.each($('.colorselect'),function(){ var $target = $(this); $(this).ColorPicker({ onSubmit: function ( hsb, hex, rgb, el ) { jQuery(el).val(hex); jQuery(el).ColorPickerHide(); }, onBeforeShow: function () { jQuery(this).ColorPickerSetColor(this.value); }, onChange: function (hsb, hex, rgb) { $target.find('.swatch').css('backgroundColor', '#'+hex); } }); });
[ "stackoverflow", "0036615528.txt" ]
Q: didFinishLaunchingWithOptions not called but app is running and faced with crash I had seen lots of iPhone apps that running on iPad with buttons name x1 and x2. I have an application that first I developed it as a universal app but now I changed it to iPhone and expect to run it on iPad with that x1 and x2 style but when I run it on the iPad I see this core data error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Settings'' *** First throw call stack: (0x187b6659c 0x1987cc0e4 0x18781d278 0x100110984 0x100110ab8 0x100110494 0x1000f4cdc 0x1000d2644 0x1000d2720 0x18c835544 0x18c318844 0x18c3187b0 0x18c834fbc 0x18c832ce8 0x18c344788 0x18c5af238 0x18c5aecec 0x18c5aec44 0x18c5a2578 0x18c5a1fe0 0x18fdb1edc 0x18fdc162c 0x187b1ea28 0x187b1db30 0x187b1c154 0x187a490a4 0x18c3833c8 0x18c37e3c0 0x100108098 0x198e3aa08) libc++abi.dylib: terminating with uncaught exception of type NSException It is working right on iPhone but I see this crash in iPad? I have this code in my didFinishLaunchingWithOptions that initialize core data - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //--------- Initialize appearance and database ------------// [[BRCoreRepository instance] initializeDatabase:self.managedObjectContext]; // Othe ui codes is here return YES; } In iPad version the didFinishLaunchingWithOptions it is not calling so the app do not pass the initialize phase of core data and the before showing the viewController it crashes. Please notice that it is working perfect in iPhone and the problem exist in iPad This is the stack trace in iPad simulator: *** First throw call stack: ( 0 CoreFoundation 0x000000010d11dd85 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x000000010c280deb objc_exception_throw + 48 2 CoreData 0x000000010cc6448b +[NSEntityDescription entityForName:inManagedObjectContext:] + 251 3 APMB 0x000000010bb8f0e4 -[BRSettingsRepository getAllRowsInSettings] + 100 4 APMB 0x000000010bb8f24b -[BRSettingsRepository loadDataFromDB] + 43 5 APMB 0x000000010bb8ec3c +[BRSettingsRepository instance] + 332 6 APMB 0x000000010bb7333e -[BRLanguageManager language] + 46 7 APMB 0x000000010bb4e084 brAppFontWithSize + 68 8 APMB 0x000000010bb4e145 +[UIFont(SystemFontOverride) systemFontOfSize:] + 37 9 UIKit 0x000000010e5e031d -[UIZoomViewController loadView] + 86 10 UIKit 0x000000010e191560 -[UIViewController loadViewIfRequired] + 138 11 UIKit 0x000000010e191cd3 -[UIViewController view] + 27 12 UIKit 0x000000010e5dfcd0 -[UIZoomViewController init] + 82 13 UIKit 0x000000010e5dd85e -[UIClassicController _setupWindow] + 582 14 UIKit 0x000000010e5dd52b +[UIClassicController sharedClassicController] + 246 15 UIKit 0x000000010e0162b5 -[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:] + 557 16 UIKit 0x000000010e015dde -[UIApplication _handleApplicationLifecycleEventWithScene:transitionContext:completion:] + 508 17 UIKit 0x000000010dff48a0 __70-[UIApplication scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke + 159 18 UIKit 0x000000010dff452d -[UIApplication scene:didUpdateWithDiff:transitionContext:completion:] + 843 19 UIKit 0x000000010dff2bca -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 591 20 FrontBoardServices 0x00000001123d32af __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 265 21 FrontBoardServices 0x00000001123eb8c8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24 22 FrontBoardServices 0x00000001123eb741 -[FBSSerialQueue _performNext] + 178 23 FrontBoardServices 0x00000001123ebaca -[FBSSerialQueue _performNextFromRunLoopSource] + 45 24 CoreFoundation 0x000000010d043301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 25 CoreFoundation 0x000000010d03922c __CFRunLoopDoSources0 + 556 26 CoreFoundation 0x000000010d0386e3 __CFRunLoopRun + 867 27 CoreFoundation 0x000000010d0380f8 CFRunLoopRunSpecific + 488 28 UIKit 0x000000010dff1f21 -[UIApplication _run] + 402 29 UIKit 0x000000010dff6f09 UIApplicationMain + 171 30 APMB 0x000000010bb86e2f main + 111 31 libdyld.dylib 0x00000001108b592d start + 1 32 ??? 0x0000000000000001 0x0 + 1 ) I am wondering how it is possible that didFinishLaunchingWithOptions is not calling but the view is going to show. And where is the best place to initialize the core data and initialize methods to do not face this problems?? A: Finally I found that it is because of UIFont+SystemFontOverride class. I use this class to override system font of my application: #import "UIFont+SystemFontOverride.h" @implementation UIFont (SystemFontOverride) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" + (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize { //return My Custom Bold Font; } + (UIFont *)systemFontOfSize:(CGFloat)fontSize { //return My Custom Normal Font; } #pragma clang diagnostic pop @end it seem that when we are using iPad with ZoomViewController the method are calling before didFinishLaunchingWithOptions and the problem was that In implementation of boldSystemFontOfSize and systemFontOfSize I was using a repository that is initializing at didFinishLaunchingWithOptions
[ "stackoverflow", "0002060492.txt" ]
Q: How hard is it to upgrade from Rails 1.2.3 to 2.3.5? Is it even worth it? I'm working on assessing a legacy code base for a client -- the source code has been largely untouched since 2007 and it's built with Rails 1.2.3. My Rails experience began at version 2.1 -- the code is fairly stock/scaffold like and devoid of meaningful tests -- I was curious to even see if I could get it running locally -- but, I'm not even sure where to start. Right off it doesn't even know what 'rake db:create' means. Ha! Is it going be a major pain to even getting it running in 2.3.5? Should I bother? Would love to hear your thoughts. Thanks A: If you're going to be actively developing the site, then yes, it is worth sinking the time into the project to bring it up to date. A lot has happened since Rails 1.2 which will make development a much more pleasant experience. Life without named scopes or RESTful resources is really difficult. If you're just patching the odd thing here and there, it may be worth leaving it mostly as-is and just dealing with the eccentricities. Since 1.2.3 is just prior to the releases building up to 2.0 where a lot of warnings and deprecation notices were introduced, you could have quite a chore. Some things to keep an eye out for: Migrations are now date-tagged, not numbered, but are at least backwards compatible Many vendor/plugins may not work, have no 2.x compatible version, or need to be upgraded The routing engine has changed, and the name of many routes may have changed, so see what rake:routes says and get ready for a lot of search-and-replace
[ "stackoverflow", "0022736895.txt" ]
Q: github account changing on windows I am using github on windows. I am new at github, so I am a bit confused about accouts. I set up github some times ago (4 months). And I have two github account on github.com username1, [email protected] username2, [email protected] I am creating a repository on github.com with username1 account. Repository name is test. And I am pushing my files to repository. commands: git remote add github [email protected]:username1/test.git git push origin master And I am opening my github username1 account on github.com web site, and opening tets repository page, but index content modified by username2 I changed username, email from console but username2 is appearing yet. Is it about ssh? What can I do? I am new. A: The GitHub user account which owns a particular repository can be different from the user that makes commits. (You can make commits in someone else's repository if they give you permission, right?). My bet is that your local user (which makes commits) is username2. You're able to make commits on a repo owned by username1 because you have authorization to do so (you own it ). You can check what your local git configuration is using for a username by either a) Running git config --global --list OR b) Opening ~/.gitconfig in an editor. To update your global user name (applies for future commits in ALL local repositories) run, git config --global user.name <username>. I can see what the next question is going to be: "What if I want my local git user to change depending on which repository is checked out?" You need to add git configurations per repository. In your repo run git config user.name <username> (Note the absence of the global flag). You might also want to add git config user.email <email> or any other repo specific settings you want.
[ "stackoverflow", "0022227686.txt" ]
Q: alpha-numeric identifier causing problems I am using a basic identifier which uses a unix timestamp with an appended alphanumeric section appended to it. Everything has been working fine until recently - a couple of identifiers fail to update in the database. I have noticed that the failing id's have all numbers and the letter E. EG 1386953039E87 which is being transcribed as 1.386953039e+96 I am far from being a mathematician but feel that the original value is being treated as a number. I have tried using the toString() function but this has not worked for me. A: Calling toString is too late because outputting 1386953039E87 has already created it as a number (or JavaScript's best guess at a number). Try modifying your server-side code to output it surround in quotes instead, so that it gets created as a string instead of a number. This could also be a side-effect of using jQuery's data() function. They mention in their api docs that it doesn't alter their value but it seems like your situation is proving otherwise: Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. So it seems you need to use the attr() instead of data() for this
[ "stackoverflow", "0023230277.txt" ]
Q: PhoneGap not loading google fonts or jquery? PhoneGap won't load the Google font or the jQuery lib. Here is the code <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200' rel='stylesheet' type='text/css'> and here is the HTML <span style="font-size:24px;">Featured Items</span> A: You don't specify the font-family anywhere. <span style="font-family:'Source Sans Pro',sans-serif; font-size:24px;">Featured Items</span> Note that inline styles should be avoided when possible.
[ "math.stackexchange", "0002197949.txt" ]
Q: How many 4-digit positive integers are there for which there are no repeated digits, or for which there may be repeated digits, but all are odd? Problem Statement: How many 4-digit positive integers are there for which there are no repeated digits, or for which there may be repeated digits, but all are odd? My original understanding of the problem was that all repeated digits must be odd. I later came to think that the author actually meant to say all digits (not just the repeated ones) must be odd. This is my solution for my initial understanding: For the first part, there are $9 \cdot 9 \cdot 8 \cdot 7$ $4$-digit integers that don't contain any repeated digits. (We start with $9$ because we can't place $0$ in the first position.) And now the second part. For the sake of symmetry, let's assume $0$ is allowed as the first digit. This means that there are $10^4 - (9 \cdot 9 \cdot 8 \cdot 7)$ $4$-digit integers with at least one repeated digit. We chose to allow $0$ as the first digit, so that we can have an equal number of $4$-digit integers with odd digits repeated as $4$-digit integers with even digits repeated. We know we are only allowed odd repeated digits so we must divide $10^4 - (9 \cdot 9 \cdot 8 \cdot 7)$ by $2$. In addition, we also have to notice that there are some $4$-digit integers that contain both odd repeated digits and even repeated digits. Those integers have this form: "aabb", "abba", "abab", "baba". To be consistent, we'll allow these integers to start with $0$ as well, but this is not a problem since we'll ignore the integers that contain repeated even digits. Each "a" can be one of $5$ odd digits and each "b" can be one of $5$ even digits. This means we have an extra $(5 \cdot 5) \cdot 4$, $4$-digit integers with even digits repeated. We've already removed half of them (when we divided by $2$) so we only need to remove another half. So the final result is $$9 \cdot 9 \cdot 8 \cdot 7 - \frac{10^4 - 9 \cdot 9 \cdot 8 \cdot 7}{2} - \frac{5 \cdot 5 \cdot 4}{2} = 7218$$ My first question is: Given my potentially flawed assumption, is this solution correct? And if it is correct, can you think of an easier way to go about it? The solution for what I think the author actually asked (If the integers contain repeated digits all the digits in the integer must be odd): There are $9 \cdot 9 \cdot 8 \cdot 7$ $4$-digit integers that don't contain any repeated digits. We have $5^4$ $4$-digit integers that can have odd digits repeated. There is a set that intersects the previously mentioned sets. That is the set formed by all the $4$-digit integers with odd digits that don't repeat. So the final result is: $9 \cdot 9 \cdot 8 \cdot 7 + 5^4 - 5 \cdot 4 \cdot 3 \cdot 2 = 5041$. As for my second question: Is this solution correct and is this what you understood from the problem statement as well? Mention: This problem comes from The Book of Proof (Section 3.5 problem 2) A: Since this problem appears in a section on the Inclusion-Exclusion Principle, your first interpretation is almost certainly not what the author intended. As N. Shales pointed out, one interpretation could be: How many four-digit positive integers are there in which no digit is repeated or are odd numbers that contain repeated digits? As you correctly calculated, the number of four-digit positive integers with no repeated digits is $9 \cdot 9 \cdot 8 \cdot 7 = 4536$. The number of odd four-digit integers is $9 \cdot 10 \cdot 10 \cdot 5 = 4500$ since there are five choices for the units digit (which must be odd), nine choices for the thousands digit (since zero is excluded), and ten choices each for the hundreds and tens digits. The number of odd numbers with no repeated digits is $8 \cdot 8 \cdot 7 \cdot 5 = 2240$ since we have five choices for the units digit, eight choices for the thousands digit (which can be neither zero nor equal to the units digit), eight choices for the hundreds digit (which cannot be equal to the thousands digit or the units digit), and seven choices for the tens digit (which cannot be equal to the thousands digit, hundreds digit, or units digit). By the Inclusion-Exclusion Principle, there are $$9 \cdot 9 \cdot 8 \cdot 7 + 9 \cdot 10 \cdot 10 \cdot 5 - 8 \cdot 8 \cdot 7 \cdot 5 = 4536 + 4500 - 2240 = 6796$$ four-digit positive integers in which no digit is repeated or are odd numbers that contain repeated digits. How many four-digit positive integers are there in which no digit is repeated or are numbers in which all the digits are odd and repeated digits may appear? This is your second interpretation. You correctly calculated that there are $$9 \cdot 8 \cdot 7 \cdot 6 + 5^4 - 5 \cdot 4 \cdot 3 \cdot 2 = 4536 + 625 - 120 = 5041$$ such numbers. We can confirm this by calculating the number of four-digit positive integers consisting of only odd digits that contain a repeated digit. This is a bit messy. We consider cases: Exactly one digit is used in all four positions: There are $5$ such numbers since there are $5$ odd digits. Exactly two digits are used, with one used three times and the other once: There are $5$ choices for the repeated digit, $4$ choices for the remaining digit, and $4$ choices for the placement of the digit that is used exactly once, so there are $$5 \cdot 4 \cdot 4 = 80$$ such numbers. Exactly two digits are used, with each used twice: There are $\binom{5}{2}$ ways of choosing the two odd digits and $\binom{4}{2}$ ways to select the positions occupied by the larger of these two digits. Hence, there are $$\binom{5}{2}\binom{4}{2} = 60$$ such numbers. Exactly three digits are used, with one number used twice: There are five ways of selecting the repeated digit, $\binom{4}{2}$ ways of selecting the positions occupied by these digits, four ways of filling the leftmost open position, and three ways of filling the remaining position. Hence, there are $$5 \cdot \binom{4}{2} \cdot 4 \cdot 3 = 360$$ such numbers. Thus, in total, there are $$5 + 80 + 60 + 360 = 505$$ four-digit integers consisting of only odd digits that contain repeated digits. Adding this to the $4536$ four-digit integers that do not contain repeated digits yields the $$4536 + 505 = 5041$$ numbers you found more easily by using the Inclusion-Exclusion Principle. How many four-digit positive integers are there in which no digit is repeated or in which the only digits that are repeated are odd numbers? This is your first interpretation. You calculated this incorrectly. Before I explain why, let's calculate the number of four-digit positive integers in which the only repeated digits are odd numbers. Exactly one odd digit is used in all four positions: As explained above, there are $5$ such numbers. Exactly two digits are used, with an odd digit used in three of the four positions: We have to consider cases, depending on whether the thousands place is occupied by the repeated digit. If the thousands place is not occupied by the repeated digit, there are eight choices for the thousands place (since it cannot be zero or the repeated digit) and five choices for the repeated digit. Hence, there are $8 \cdot 5 = 40$ such numbers. If the thousands place is occupied by the repeated digit, there are $\binom{3}{2}$ ways of selecting the other two positions of that digit, five ways of choosing the digit, and $9$ ways of filling the remaining position. Hence, there are $$\binom{3}{2} \cdot 5 \cdot 9 = 135$$ such numbers. In total, there are $40 + 135 = 175$ four-digit positive integers in which exactly two digits are used and one odd digit is used in three of the four positions. Exactly two digits are used, with two odd digits each filling two of the four positions: There are $\binom{5}{2}$ ways of selecting two of the five odd digits and $\binom{4}{2}$ ways of choosing which two of the four positions will be filled by the larger of them. Hence, there are $$\binom{5}{2}\binom{4}{2} = 60$$ such numbers. Exactly three digits are used, with one odd digit used twice: We have to consider cases, depending on whether the repeated digit is used in the thousands place. If the thousands place is not occupied by the repeated digit, there are eight ways to fill the thousands place (since it cannot be zero or the repeated digit). There are five choices for the repeated digit, $\binom{3}{2}$ ways of selecting which two of the remaining three positions it will fill, and eight choices for the remaining digit (since it cannot be the repeated digit or the thousands digit). Hence, there are $$8 \cdot 5 \cdot \binom{3}{2} \cdot 8 = 960$$ such numbers. If the thousands place is occupied by the repeated digit, there are five ways to fill the thousands place (since it must be odd), three ways to select the other digit occupied by the repeated digit, nine ways to fill the leftmost open position, and eight ways to fill the remaining open position. Hence, there are $$5 \cdot 3 \cdot 9 \cdot 8 = 1080$$ such numbers. In total, there are $960 + 1080 = 2040$ four-digit positive integers using exactly three digits in which one odd digit is repeated. Total: Adding these cases yields $$5 + 175 + 60 + 2040 = 2280$$ four-digit positive integers containing repeated digits in which the only digits that are repeated are odd digits. Your tried to use the Inclusion-Exclusion Principle to do this. Let's see what went wrong. As you noted, there are $10^4$ four-digit strings. However, the number of such strings with no repeated digits is $10 \cdot 9 \cdot 8 \cdot 7 = 5040$. Hence, there are $$10^4 - 10 \cdot 9 \cot 8 \cdot 7 = 1000 - 5040 = 4960$$ such strings with repeated digits. You attempted to use symmetry to eliminate those that contain repeated even digits by dividing by $2$. Doing so yields $2480$. As you realized, we are still counting strings with two even and two odd digits. There are actually $$5 \cdot 5 \cdot \binom{4}{2} = 150$$ such strings since there are five choices of even digit, five choices of odd digit, and $\binom{4}{2}$ ways of selecting the positions of the even digit. Half of these were eliminated when we divided by $2$, leaving $75$ more to be eliminated. This leaves us with $$2480 - 75 = 2405$$ four-digit strings which contain only repeated odd digits. However, not all these strings are four-digit positive integers since the first digit may be zero. We must eliminate these. Three-digit positive integers in which a single odd digit is used in all three positions: There are $5$ such numbers since there are five odd digits. Three-digit odd positive integers in which exactly two digits are used and an odd digit is repeated: Notice that we have already eliminated numbers in which a zero appears since it would be a repeated even digit (as zero also occupies the thousands place). There are five ways of choosing the repeated digit, $\binom{3}{2}$ ways of selecting two of the three locations for that digit, and eight ways to fill the remaining digit. Hence, there are $$5 \cdot \binom{3}{2} \cdot 8 = 120$$ such numbers. Hence, there are $$\frac{10^4 - 10 \cdot 9 \cdot 8 \cdot 7}{2} - \frac{5 \cdot 5 \cdot \binom{4}{2}}{2} - 5 - 5 \cdot \binom{3}{2} \cdot 8 = 2480 - 75 - 5 - 120 = 2280$$ four-digit positive integers in which the only repeated digits are odd, which agrees with the result we obtained above. Thus, there are a total of $$4536 + 2280 = 6816$$ four-digit positive integers in which no digit is repeated or the only digits that are repeated are odd numbers.
[ "math.stackexchange", "0000639112.txt" ]
Q: Is $2^\alpha=2^\beta\Rightarrow \alpha=\beta$ a $\sf ZFC$-independence result? In a lecture recently one of my lecturers was proving something to do size of basis or something (I can't remember exactly) and somewhere near the end of the proof we had the following: $2^\alpha=2^\beta\Rightarrow \alpha=\beta$ Now this was just in a proof about finite (or possibly countable) things so everything is cool here but this rang a bell a a results that may be independent of ZFC or something which I couldn't quite recall. I had a look but I couldn't find anything about it? Thanks for the help A: Yes, this is very much independent of the axioms of $\sf ZFC$. It is a consequence of $\sf GCH$, but not equivalent. It is possible to have $2^{\aleph_0}=2^{\aleph_1}$. On the other hand, we can have that for finite $n$, $2^{\aleph_n}=\aleph_{n+3}$, and otherwise $2^{\aleph_\alpha}=\aleph_{\alpha+1}$. In that case, clearly $2^\kappa=2^\lambda\implies\kappa=\lambda$, but $\sf GCH$ fails.
[ "stackoverflow", "0052571879.txt" ]
Q: Use dplyr to add a new column of based on max row value? I've got a large database that has a series of columns with numerical. I would like to use dplyr to add a new column, mutate, which has as its values the names of the column that has the maximum value. So, for the example below set.seed(123) data_frame( bob = rnorm(10), sam = rnorm(10), dick = rnorm(10) ) # A tibble: 5 x 3 bob sam dick <dbl> <dbl> <dbl> 1 -0.560 1.72 1.22 2 -0.230 0.461 0.360 3 1.56 -1.27 0.401 4 0.0705 -0.687 0.111 5 0.129 -0.446 -0.556 the new column would be equal to c('sam', 'sam', 'bob', 'dick', 'bob') because they have the maximum values of the columns in the dataset. Any thought? A: This will work fine: df$result = names(df)[apply(df, 1, which.max)]
[ "stackoverflow", "0007364369.txt" ]
Q: Opening a File Pathway in C# I am having trouble with winform opening a drawing. The error I am getting says NullReferenceException was unhandled and is highlighting the pathway. any help is appreciated. Thanks private void button2_Click(object sender, EventArgs e) { //Open Solidworks Drawing ModelDoc2 swModel = default(ModelDoc2); DocumentSpecification swDocSpecification = default(DocumentSpecification); string sName = null; long longstatus = 0; long longwarnings = 0; // Drawing document path and name swDocSpecification = (DocumentSpecification)swApp.GetOpenDocSpec("C:\\location\\????.slddrw");//File Location sName = swDocSpecification.FileName; // Sheet name swDocSpecification.SheetName = "BOM"; //Open to the BOM sheet swDocSpecification.DocumentType = (int)swDocumentTypes_e.swDocDRAWING; swDocSpecification.ReadOnly = true; swDocSpecification.Silent = false; // Open the specified sheet in the specified drawing document swModel = swApp.OpenDoc7(swDocSpecification); longstatus = swDocSpecification.Error; longwarnings = swDocSpecification.Warning; } A: There are two possibilities as to why you're getting the NullReferenceException swApp is null and calling anything inlcuding GetOpenDocSpec won't work Something inside GetOpenDocSpec isn't written the way it supposed to, and its not doing the correct checking. And so its throwing a null exception It should pretty easy to just check if swApp == null using your debugger. Using the autos or watch windows, hovering over the variable, ?swApp == null from the command window, etc.
[ "stackoverflow", "0024434112.txt" ]
Q: How to explain the performance of Cypher's LOAD CSV clause? I'm using Cypher's LOAD CSV syntax in Neo4J 2.1.2. So far it's been a huge improvement over the more manual ETL process required in previous versions. But I'm running into some behavior in a single case that's not what I'd expect and I wonder if I'm missing something. The cypher query being used is this: USING PERIODIC COMMIT 500 LOAD CSV FROM 'file:///Users/James/Desktop/import/dependency_sets_short.csv' AS row MATCH (s:Sense {uid: toInt(row[4])}) MERGE (ds:DependencySet {label: row[2]}) ON CREATE SET ds.optional=(row[3] = 't') CREATE (s)-[:has]->(ds) Here's a couple of lines of the CSV: 227303,1,TO-PURPOSE-NOMINAL,t,73830 334471,1,AT-LOCATION,t,92048 334470,1,AT-TIME,t,92048 334469,1,ON-LOCATION,t,92048 227302,1,TO-PURPOSE-INFINITIVE,t,73830 116008,1,TO-LOCATION,t,68204 116007,1,IN-LOCATION,t,68204 227301,1,TO-LOCATION,t,73830 334468,1,ON-DATE,t,92048 116006,1,AT-LOCATION,t,68204 334467,1,WITH-ASSOCIATE,t,92048 Basically, I'm matching a Sense node (previously imported) based on it's ID value which is the fifth column. Then I'm doing a merge to either get a DependencySet node if it exists, or create it. Finally, I'm creating a has edge between the Sense node and the DependencySet node. So far so good, this all works as expected. What's confusing is the performance as the size of the CSV grows. CSV Lines Time (msec) ------------------------------ 500 480 1000 717 2000 1110 5000 1521 10000 2111 50000 4794 100000 5907 200000 12302 300000 35494 400000 Java heap space error My expectation is that growth would be more-or-less linear, particularly as I'm committing every 500 lines as recommended by the manual, but it's actually closer to polynomial: What's worse is that somewhere between 300k and 400k rows, it runs into a Java heap space error. Based on the trend from previous imports, I'd expect the import of 400k to take a bit over a minute. Instead, it churns away for about 5-7 minutes before running into the heap space error. It seems like I could split this file into 300,000-line chunks, but isn't that what "USING PERIODIC COMMIT" is supposed to do, more or less? I suppose I could give Neo4J more memory too, but again, it's not clear why I should have to in this scenario. Also, to be clear, the lookups on both Sense.uid and DependencySet.label are indexed, so the lookup penalty for these should be pretty small. Here's a snippet from the schema: Indexes ON :DependencySet(label) ONLINE (for uniqueness constraint) ON :Sense(uid) ONLINE (for uniqueness constraint) Any explanations or thoughts on an alternative approach would be appreciated. EDIT: The problem definitely seems to be in the MATCH and/or CREATE part of the query. If I remove lines 3 and 5 from the Cypher query it performs fine. A: I assume that you've already created all the Sense labeled nodes before running this LOAD CSV import. What I think is going on is that as you are matching nodes with the label Sense into memory and creating relationships from the DependencySet to the Sense node via CREATE (s)-[:HAS]->(ds) you are increasing utilization of the available heap. Another possibility is that the size of your relationship store in your memory mapped settings needs to be increased. In your scenario it looks like the Sense nodes have a high degree of connectivity to other nodes in the graph. When this happens your relationship store for those nodes require more memory. Eventually when you hit 400k nodes the heap is maxed out. Up until that point it needs to do more garbage collection and reads from disk. Michael Hunger put together an excellent blog post on memory mapped settings for fast LOAD CSV performance. See here: http://jexp.de/blog/2014/06/load-csv-into-neo4j-quickly-and-successfully/ That should resolve your problem. I don't see anything wrong with your query.
[ "stackoverflow", "0019249180.txt" ]
Q: custom message fired from bean method I have a command button on my page. <h:commandButton id="makeSearch" value="#{msg.makeWycena}"> <f:ajax event="click" render="@all" listener="#{searchBean.makeSearch()}"/> </h:commandButton> makeSearch() method first checks value from database, and if this value is null it performs some logic. But when the value isn't null, then I would like to display an error message. I thought about making <h:outputtext rendered = {not null XXX}/> and make special variable XXX for that reason, but I'm pretty much sure it can be done with plain <h:message /> form, but can't find how. My code looks like this : else { FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(null , new FacesMessage("XXXXXXXX")); return null; } I want the message XXXXXXXXX to be displayed in: <h:message for="makeSearch" globalOnly="true" style="color:red;margin:8px;"/> next to command button I posted before. Right now it's rendered at the bottom of a page After few changes my code looks like this right now : <h:form id="detailsForm" prependId="false"> <h:commandButton id="makeSearch" value="#{msg.makeWycena}"> <f:ajax event="click" render="@all" listener="#{searchBean.makeSearch()}"/> </h:commandButton> <h:message for="makeSearch" id ="makeSearchError" style="color:red;margin:6px;left-margin:10px;"/> and bean code : else {FacesContext.getCurrentInstance().addMessage("detailsForm:makeSearchError" , new FacesMessage("XXXXXXXXXXXX")); } but still. message don't render in h:message. I tried also detailForm:makeSeach and it didn't help either A: The facesContext.addMessage(null, message) ends up in a <h:messages globalOnly="true">, not in a <h:message for="...">. Note that globalOnly="true" is not supported on <h:message>. So, replace <h:message for="makeSearch" globalOnly="true" style="color:red;margin:8px;"/> by <h:messages globalOnly="true" style="color:red;margin:8px;"/> As to your attempt with a fixed message client ID as per the comments, that's also invalid. You should specify the client ID of the component to which the message is associated by its for attribute, not the message component itself. So, you should not have used facesContext.addMessage("detailsForm:makeSearchError", message); but instead facesContext.addMessage("detailsForm:makeSearch", message); After all, that's unnecessary if you just fix the <h:message> to be a true <h:messages>.
[ "spanish.meta.stackexchange", "0000002656.txt" ]
Q: Usuario sin registrar (con 1 punto de reputación) hizo comentario en mi pregunta En el siguiente enlace podrán ver el comentario de un usuario que, según su perfil, está sin registrar. Este es el comentario del nuevo usuario: Tenía entendido que solo con puntuación de 50 se puede generar comentarios en las preguntas y repuestas de otros usuarios. ¿Esta situación acaso fue un error? Solo para aclarar, no estoy presentando alguna queja sobre el contenido del comentario, sino que me resulta curioso que un usuario nuevo "sin registrar" haya hecho un comentario en mi pregunta - sin tener aún el privilegio concedido según su reputación. A: Este usuario respondió originalmente a la pregunta con un post-respuesta (con exactamente ese mismo contenido), no con un comentario. Es cierto que no habría tenido suficiente reputación para comentar. Revisando las contribuciones nuevas vi esta respuesta y evalué que su contenido es un comentario, no una respuesta, ya que no responde (ni siquiera lo intenta) a la pregunta original: ¿Cuál es el origen de la expresión "paquete chileno"? Por eso, haciendo uso de las herramientas de moderador migré su respuesta a comentario. Con reputación suficiente (2000) se pueden ver los post eliminados, en cuyo caso podrías ver algo como la siguiente imagen Normalmente dejamos una serie de comentarios a los usuarios nuevos, a aquellos que no responden realmente a la preguntas planteadas o a aquellos cuyas contribuciones son de muy baja calidad, para animarles a mejorar sus contribuciones, mostrarles links de referencia útiles (como las secciones, tour, How to ask, how to answer o el centro de ayuda) y para dar la bienvenida, ofrecer ayuda, etc. En el caso de este usuario, dado que Es un usuario no registrado, como bien indicas No muestra ningún interés en responder a la pregunta original Hace referencia a "Pinocho" (entiendo que por Pinochet), dando un tono "jocoso" en el mejor de los casos, y el contenido de su contribución es claramente un "comentario rápido" aclaratorio no me molesté en dejar el comentario de "bienvenida + por-favor-mejora-tu-post" asumiendo que este usuario nunca va a volver para mejorar esa contribución (si lo hiciese podría editar su respuesta y luego levantar un flag para que un moderador hiciese un undelete). Al migrar un post de respuesta a comentario se pueden migrar también como comentarios (o no) cualesquiera comentarios que ese post respuesta tenga asociados, a opción del moderador realizando la tarea de "limpieza". Los comentarios también se pueden migrar a chat. No es raro que usuarios que no saben cómo funciona la filosofía de los stacks posteen como respuestas cosas que debieran ser comentarios (por desconocimiento o porque por falta de reputación suficiente para comentar deciden abusar el sistema publicando un post-respuesta). Todos los usuarios está invitados a participar en las tareas de moderación. Con reputación suficiente se accede además a las colas de revisión. La funcionalidad para migrar posts solo está disponible a moderadores.
[ "stackoverflow", "0062604519.txt" ]
Q: Cumulative sum of values without calculating repeated values in a column I have a data like this in R x <- c(1,2,2,3,4,4,7,8) y <- c(300,200,200,150,100,100,30,20) df <- data.frame(x, y) The cumulative with the dataset is cum_df <- data.frame(x, y, Y) > cum_df x y Y 1 1 300 300 2 2 200 500 3 2 200 700 4 3 150 850 5 4 100 950 6 4 100 1050 7 7 30 1080 8 8 20 1100 The cumulative of "y" using cumsum(y) is: Y <- cumsum(y) > Y [1] 300 500 700 850 950 1050 1080 1100 Instead, I want the cumulative of "y" to be like this > Y [1] 300 500 500 650 750 750 780 800 In essence, it does not compute repeated values of y. How do I go about this in R? I have tried different functions but it seem not to work. I want the answer to look like this > ans x y Y 1 1 300 300 2 2 200 500 3 2 200 500 4 3 150 650 5 4 100 750 6 4 100 750 7 7 30 780 8 8 20 800 A: We can get the distinct rows, do the cumsum and then do a join library(dplyr) df %>% distinct() %>% mutate(Y = cumsum(y)) %>% right_join(df) # x y Y #1 1 300 300 #2 2 200 500 #3 2 200 500 #4 3 150 650 #5 4 100 750 #6 4 100 750 #7 7 30 780 #8 8 20 800 Or without any join by replacing the duplicated values in 'y' with 0, and then do the cumsum df %>% mutate(Y = cumsum(y * !duplicated(y))) # x y Y #1 1 300 300 #2 2 200 500 #3 2 200 500 #4 3 150 650 #5 4 100 750 #6 4 100 750 #7 7 30 780 #8 8 20 800 Or in base R df$Y <- with(df, cumsum(y * !duplicated(y)))
[ "stackoverflow", "0022322796.txt" ]
Q: java.lang.NullPointerException in two related java class I implemented two java classes to solve the percolation problem but it throws the following exception java.lang.NullPointerException at PercolationStats.<init>(PercolationStats.java:24) at PercolationStats.main(PercolationStats.java:54) Program: public class PercolationStats { int t=0; double[] sample_threshold; Percolation B; int N1; public PercolationStats(int N, int T) { t=T; N1 = N; int number_of_open=0; for(int i=0;i<T;i++) { B=new Percolation(N1); while(!B.percolates()) { double r1 = Math.random(); int open_i = (int)(r1*N1); double r2 = Math.random(); int open_j = (int)(r2*N1); B.open(open_i,open_j); } for(int k=0;k<N1;k++) { for(int j=0;j<N1;j++) { if(B.isOpen(k, j)) number_of_open++; } sample_threshold[i] = (number_of_open*1.0)/N1; } } } public double mean() { double sum = 0.0; for(int i=0;i<N1;i++) { sum += sample_threshold[i]; } return sum/t; } public double stddev() { double sum = 0.0; double u = mean(); for(int i=0;i<N1;i++) { sum += (sample_threshold[i]-u)*(sample_threshold[i]-u); } return sum/(t-1); } public double confidenceLo() { return mean()-((1.96*Math.sqrt(stddev()))/(Math.sqrt(t))); } public double confidenceHi() { return mean()+((1.96*Math.sqrt(stddev()))/(Math.sqrt(t))); } public static void main(String[] args) { int N = Integer.parseInt(args[0]); int T = Integer.parseInt(args[1]); PercolationStats C=new PercolationStats(N,T); double mean=C.mean(); double stddev = C.stddev(); double confidenceLo = C.confidenceLo(); double confidenceHi = C.confidenceHi(); System.out.println("mean = "+mean); System.out.println("stddev = "+stddev); System.out.println("95% confidence interval = "+confidenceLo+", "+confidenceHi); } } A: You never initialized double[] sample_threshold;. Hence it is null. A: Java will indeed fill a double[] with 0.0 once it is initialized to a known size. You must initialize the array first: public PercolationStats(int N, int T) { t=T; N1 = N; sample_threshold[i] = new double[T]; // add this line int number_of_open=0; for(int i=0;i<T;i++) { B=new Percolation(N1); while(!B.percolates()) { double r1 = Math.random(); int open_i = (int)(r1*N1); double r2 = Math.random(); int open_j = (int)(r2*N1); B.open(open_i,open_j); } for(int k=0;k<N1;k++) { for(int j=0;j<N1;j++) { if(B.isOpen(k, j)) number_of_open++; } sample_threshold[i] = (number_of_open*1.0)/N1; } } }
[ "english.meta.stackexchange", "0000009845.txt" ]
Q: Is it possible for me to know which questions have gained or lost protection by me? In my "activities", I don't see an option for this. Also, couldn't find a meta post for this. Being relatively new to the "protect" tool, I might've misused it. Now, having learned about it, I'll properly use it. A: It is almost certainly only available via a query on the database. The available dataset is updated weekly on Sundays. Here's one query: http://data.stackexchange.com/english/query/449043/my-unprotected-questions Its two authors are both moderators, which lends support to the view that the data is not available by other means. You'll need to enter a user id in the box before pressing "Run Query": yours is 50044. A: The new feature was introduced on Nov. 18, 2016 and you can review a list of protected questions as indicated in the Meta SE post, Show 10kers a larger list of recently protected questions. As of this morning (Nov. 18), there is a new 10k tool under /tools that provides a list of protected questions. It's impossible to review unprotected questions unless you use SEDE. You can get some help in the following link, an answer to Where can I find the list of questions I (un-)protected? on Stack Overflow Meta. Note: The following feature request is still pending. Please add the list of questions (un-)protected to the profile page
[ "stackoverflow", "0008373330.txt" ]
Q: What is this UI Element? Is this a built in UI Element? I see it used in the address book, mail app, and other 3rd party apps but I can't find the object in Xcode anywhere... A: That is a UIActionSheet. Basically, it's intended to replace what would be commonly accomplished with a Combo Box in a traditional setting.
[ "ux.stackexchange", "0000093904.txt" ]
Q: Measure Wow-factor metric I am looking into some software development metrics. Does anyone have a clear tried and tested strategy to measure the Wow-factor of a web-application? A set of properties belonging to an object that pleasantly surprise a watcher. From commercials to cool electronics, the wow factor is an important thing to consider when designing it. A: Well, co-incidentally, I was thinking on the same lines couple years ago. I happened to design a sort of metric that pointed to the line of thoughts at that point of time - it being of qualitatively defining a user interface. Here is the complete blog post. Few excerpts from that blog post - Lets call it FGF Score. 1) F for Focus – Very important, and can be easily judged by seeing the site/interface. If the site is supposed to sell oranges, it should first focus on getting that done and then try baby diapers. Weight of Focus being – 4 out of 10. 2) G for Good Arrangement – This leads to clarity. If there is lot of clutter then a user gets disturbed and probably does not ‘feel nice’. Weight being – 4 out of 10. 3) F for Fonts – This I suppose is very crucial, although might not place in many UX books/texts. Font selection, I believe can make or break your design. Hence this needs good importance, and is one of the first things you see on a website. Weight being 2 out of 10. So, FGF Score(10 points) made out of –Focus(4 points) + Good Arrangement(4 points) + Fonts(2 points) You could call it a little naive, but at that time it was an attempt to structure some thoughts around this bubbling question. Hope it serves as some food for thought. A: I assume that you are referring to the "Delighters" in the Kano Model. There are a couple of articles that go into a lot more details, such as the Folding Burritos website that you can read about to get more details. You can also refer to previous questions on the subject: Is the Kano model adaptable for measuring user experience? How do I get KPIs within an enterprise environment? Does anyone have statistics on usage of the Kano Model?
[ "stackoverflow", "0039918799.txt" ]
Q: Angular filter doesnt return the expected result I am trying to filter this json by the first name. I am expecting the result to be A1, but I am doing something wrong. $filter('filter')('[{ "ID": 1, "FirstName": "A1", "L1": "Sabrina" }, { "ID": 2, "FirstName": "A2", "LastName": "L2" }]', 'A1'); A: I don't think you can use $filter with pure JSON. var arr = JSON.parse('[{ "ID": 1, "FirstName": "A1", "L1": "Sabrina" }, { "ID": 2, "FirstName": "A2", "LastName": "L2" }]'); var a1 = $filter('filter')(arr, 'A1'); Returns the expected result.
[ "stackoverflow", "0050948524.txt" ]
Q: Angular unit tests TypeError: this.http.get(...).pipe is not a function I'm following this example to make a unit test for service (get request coming from spring app backend) https://angular.io/guide/testing#testing-http-services Service class : @Injectable() export class TarifService { constructor(private messageService: MessageService, private http: HttpClient) { } public getTarifs(): Observable<Tarif[]> { return this.http.get<Tarif[]>(tarifffsURL).pipe( tap(() => {}), catchError(this.handleError('getTarifs', [])) ); } } Unit Test describe('TarifService', () => { let tarifService: TarifService; let httpClientSpy: { get: jasmine.Spy }; let expectedTarifs; beforeEach(() => { TestBed.configureTestingModule({ imports: [ToastrModule.forRoot(), HttpClientModule, HttpClientTestingModule], providers: [TarifService, HttpClient, MessageService] }); httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); tarifService = new TarifService(<any> MessageService,<any> httpClientSpy); }); it('should be created', inject([TarifService], (service: TarifService) => { expect(service).toBeTruthy(); })); it('should return expected tarif (HttpClient called once)', () => { const expectedTarifs: Tarif[] = [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }]; httpClientSpy.get.and.returnValue(expectedTarifs); tarifService.getTarifs().subscribe( tarifs => expect(tarifs).toEqual(expectedTarifs, 'expected tarifs'), fail ); expect(httpClientSpy.get.calls.count()).toBe(1, 'one call'); }); }); When running the tests, I keep having this error TarifService should return expected tarif (HttpClient called once) TypeError: this.http.get(...).pipe is not a function what could be the cause of this? A: The problem is that when your spy is being called, it is returning an Array, and Array does not have a pipe function. You need to return an Observable from your spy, something like this const expectedTarifs: Tarif[] = [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }]; httpClientSpy.get.and.returnValue(Observable.of(expectedTarifs)); See how the returnValue is Observable.of(expectedTarifs). Observable.of creates an Observable that emits some values you specify as arguments, immediately one after the other, and then emits a complete notification. See the docs In the latest versions of rxjs we can use the of operator import { of } from 'rxjs'; //... omitting some code here for brevity const expectedTarifs: Tarif[] = [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }]; httpClientSpy.get.and.returnValue(of(expectedTarifs)); Hope it helps
[ "rpg.stackexchange", "0000154730.txt" ]
Q: How do you calculate the range of an attack when attacking diagonally? I was recently in a situation where I had to make a crossbow attack on an enemy that is in the opposite corner of the room from where I was. It looked a bit like this: For the sake of simplicity, let's assume my weapon has a range of 25 feet, and that each square is 5 feet wide. If I count the diagonal squares, the enemy would just be in range. But if I calculate it mathematically with Pythagoras' theorem, the enemy would be 35 feet away, and thus not be in range. The PHB only states about the Range weapon property: Range. A weapon that can be used to make a ranged attack has a range shown in parentheses after the ammunition or thrown property. The range lists two numbers. The first is the weapon's normal range in feet, and the second indicates the weapon's long range. When attacking a target beyond normal range, you have disadvantage on the attack roll. You can't attack a target beyond the weapon's long range. I know there is a rule for diagonal movement where your first diagonal square costs 5 feet, the second 10 feet, and so on... I don't know where this rule is written, I just heard it somewhere. How is the range of an attack determined, by RAW? Just count the squares? Calculate the diagonal, which would amount to 7 feet for each square? Use the movement rules? A: Let's get one thing out of the way first: Playing on a grid is a variant to the normal rules. These variant rules can be found in the green insert/sidebar on page 192 of the Player's Handbook. To calculate range using these rules you count squares as though you were moving: To determine the range on a grid between two things—whether creatures or objects—start counting squares from a square adjacent to one of them and stop counting in the space of the other one. Count by the shortest route. In these rules diagonal squares are treated as 5 ft. apart. To enter a square, you must have at least [5 feet] of movement left, even if the square is diagonally adjacent to the square you're in. This rule "sacrifices realism for the sake of smooth play." The Dungeon Master's Guide (p. 252) includes the additional variant rule1 that every second diagonal counts as 5 additional feet. When measuring range or moving diagonally on a grid, the first diagonal square counts as 5 feet, but the second diagonal square counts as 10 feet. 1: Yo dawg, I heard you liked variant rules...
[ "stackoverflow", "0003900963.txt" ]
Q: Insert statement whith unknown number of values extracted from a string I have a stored procedure in a sql server 2008 db. This stored procedure takes a parameter that is a list of max 5 comma separated integer values. This string is passed through a php sript and formatted like this: 01,02,03,14,15 These values should go in this table: Id | Type id ------------- 1 | 1 1 | 2 1 | 3 1 | 14 1 | 15 ...where id is the same and type id is one of the comma separated values. Obviously, I could have a string like "01,02,03" with only 3 values. So I need a way to insert only 3 rows in the above table resulting in: Id | Type id ------------- 1 | 1 1 | 2 1 | 3 I could modify either the php script or the stored procedure, so I'm open to all kinds of suggestion. A: I would pass XML into SQL server, which can then easily be processed as nodeset (like a table) using OPENXML or using the nodes() function on the xml datatype. It works very well and it's quite performant, almost always faster than any handmade string processing code. DECLARE @x xml; SET @x = '<id>01</id><id>02</id><id>03</id><id>14</id><id>15</id>'; SELECT x.id.value('.', 'int') FROM @x.nodes('id') AS x(id);
[ "electronics.stackexchange", "0000132010.txt" ]
Q: Troublshooting noisy smps I had a working design of a buck switching regulator based on a TPS62125. It worked fine, with minimal (<100mVpp) noise. I made some changes to my design, seemingly unrelated to the switcher. The result is audible noise from the switcher (a high pitch whine, that gets louder as draw increases), as well as this lovely waveform: Here's my current layout: The only changes I made to the switcher directly is adding room for a 250uF electrolytic cap (problem persists with and without it), adding a .2mF supercap elsewhere in the design, but off this power rail (problem also persists with and without), and adding a footprint for C33, but not populating. The amplitude of the noise does not seem to be affected by load. Where do I go from here? How do I troubleshoot this? I thought I spotted a short between the two pins of the IC that lead to the two pads for the inductor. It doesn't look like there's an actual bridge while looking with a loupe, but could this be the source of the problem (pins are too close because of excess solder, creating some sort of stray capacitance)? The only other thing I can think of is that it's possible that I installed a wrong capacitor for the input or output caps (did this by hand). Would that produce these results? Could it be a bad inductor? A: Just maybes: If any of these prove useful I'll come back and tidy up the answer. Otherwise no great value. You've got a lovely pickup loop across R16 - why are FB R's across other side from both Vout and FB pin? | C22 is in middle of that loop - noise filtered by C22 MAY be inductively coupled into loop. Install C33 (small). Temporarily move C22 physically and tack on in next best locn away from FB loop. IP and OP caps could cause problems if well off values shown. Data sheet does NOT say so but possible it is unstable if output cap ESR does not fall in a certain range. Varies with load. Check. What sort on in & out caps? Ceramic? C33 = transient response speedup. Diagm says DNP. Is it populated? Try it. What happens with small C33? What is load. How does op waveform and amplitude change with load?
[ "stackoverflow", "0017767034.txt" ]
Q: SPL Autoload and namespaces After looking through the web I have managed to build a working SPL_Autoload and use namespaces in it. It does work but it also looks a bit strange to me compared to all of the examples I was looking at and the documentation. Am I using everything and understanding it correctly? $class looks up a class called subdir\timer and since it cannot find it goes to the SPL_autoload $class = new subdir\timer; The SPL_autoload is suppose to look for a file in the folder 'subdir' with a file 'timer' ending in either .php or .class.php (thanks to the SPL_extensions) Now I am not really sure what is going on in register and SPL_autoload. When I tried register by itself it was not using the _extensions but when i added spl_autoload it worked fine. Only thing is I have never seen it setup like this in any examples so I really question this part spl_autoload_extensions(".php,.class.php"); spl_autoload_register(function($class){ spl_autoload("$class"); }); What do you think, any things that cam be improved on or that I did wrong? A: I've tested it and it works for me: set_include_path(__DIR__.'PATH_TO_LIB'); spl_autoload_extensions('.php,.class.php'); spl_autoload_register(); So you've set the correct include_path? Further for namespaces and classnames there is a standard called PSR-0. https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md They also have a SplClassLoader which is a little bigger but also more flexible, although I wonder that you can only set one file extension. Well but search for PSR-0 autoloader and you'll find more implementations. By the way there are also the standards PSR-1 and PSR-2 which are worth to know..
[ "stackoverflow", "0001716790.txt" ]
Q: Getting the full url for an image in webpage I would like to get the full url of an image in a web page. The image is used as a background image. I was using Firebug's inspect feature. In the CSS view, it shows url(/images/myimage.gif) for the background-image element. Is there a way to display the full url? A: Right click the path in FireBug's style inspector and select 'Copy Image Location.'
[ "stackoverflow", "0019705246.txt" ]
Q: Case sensitive CSS formatting I am generating an html table using a PHP code to grab the content from a .csv table. Now I would like the format of every specific cell to be depending on it's content. My (probably terrible) attempt in pseudocode: if (cell content == "green") use #green-css-style if else (cell content == "blue") use #blue-css-style and so on. I only want it to "listen" for a limited amount of different contents (approx. 5). This is my PHP table-generator: <?php $hasTitle = true; echo '<table id="dataTable" class="table">'; $handle = fopen("data.csv", "r"); $start = 0; ; while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { echo '<tr>' . "\n"; for ( $x = 0; $x < count($data); $x++) { if ($start == 0 && $hasTitle == true) echo '<th title="ignore_case">'.$data[$x].'</th>' . "\n"; else echo '<td>'.$data[$x].'</td>' . "\n"; } $start++; echo '</tr>' . "\n"; } fclose($handle); ; echo '</table>' . '<br style="clear: both;">'; ?> Any help on this is very welcome, additional details available on request! :) A: Just add a class to the td element in your php code. You cant access the content of an element in css. switch($data[x]) { case 'green': $class = 'green'; break; case 'blue': $class = 'blue'; break; //... default: $class = ''; break; } echo '<td class="'.$class.'">'.$data[$x].'</td>' . "\n"; You can then for example use the following css code: td.green { color: green; } td.blue { color: blue; }
[ "math.stackexchange", "0003050208.txt" ]
Q: I calculated $\sin 75^\circ$ as $\frac{1}{2\sqrt{2}}+\frac{\sqrt{3}}{2\sqrt{2}}$, but the answer is $\frac{\sqrt{2}+\sqrt{6}}{4}$. What went wrong? I calculated the exact value of $\sin 75^\circ$ as follows: $$\begin{align} \sin 75^\circ &= \sin(30^\circ + 45^\circ) \\ &=\sin 30^\circ \cos 45^\circ + \cos 30^\circ \sin 45^\circ \\ &=\frac12\cdot\frac{1}{\sqrt{2}} + \frac{\sqrt{3}}{2}\cdot\frac{1}{\sqrt{2}} \\ &= \frac{1}{2\sqrt{2}} + \frac{\sqrt{3}}{2\sqrt{2}} \end{align}$$ The actual answer is $$\frac{\sqrt{2} + \sqrt{6}}{4}$$ My main confusion is how the textbook answer is completely different from mine, even though if I compute $\sin 30^\circ \cos45^\circ + \cos 30^\circ \sin 45^\circ$, it will be approximately the same value of $\sin 75^\circ$. I think I'm having difficulty adding and subtracting the radicals. So, if someone can demonstrate to me how they got that answer, it will be helpful. Thanks. A: They’re the same value. Multiply the numerator and denominator of your answer by $\sqrt 2$ to see why. $$\frac{1+\sqrt 3}{2\sqrt 2} = \frac{\sqrt 2}{\sqrt 2}\cdot\frac{1+\sqrt 3}{2\sqrt 2} = \frac{\sqrt 2+\sqrt 6}{4}$$ You can also use $\sin 45 = \cos 45 = \frac{\sqrt 2}{2}$ (rationalizing $\frac{1}{\sqrt 2}$) to get the answer more easily.
[ "math.stackexchange", "0001335143.txt" ]
Q: Presheaf that do not satisfy: If $\{U_i\}$ is an open cover of $U \subseteq X$ and $s \in \mathcal{F}(U)$, then $s=0$ iff $s|_{U_i}=0$ $\forall i$ Let $X$ be a topological space. Find an example of a presheaf $\mathcal{F}$ that do not satisfy: If $\{U_i\}_{i \in I}$ is an open cover of $U \subseteq X$ and $s \in \mathcal{F}(U)$, then $s=0$ if and only if $s|_{U_i}=0$ $\forall i \in I$. Find an example of a presheaf $\mathcal{F}$ that do not satisfy: If $\{U_i\}_{i \in I}$ is an open cover of $U \subseteq X$ and $\{s_i\}_{i \in I}$ is a colection of sections $s_i \in \mathcal{F}(U_i)$ such that $s_i|_{U_i \cap U_j}=s_j|_{U_i \cap U_j}$, then there exists $s \in \mathcal{F}(U)$ such that $s|_{U_i}=s_i$ $\forall i \in I$. I know that if $X=\mathbb{R}^n$, then $\mathcal{F}(U)=\{\varphi:U \rightarrow \mathbb{R} \quad \text{constant function}\}$ is a presheaf but not a sheaf. I think that this example for 2. is the simpliest. However I can't find a simple example for 1. Some help here would be appreciated. Thanks! A: Define a presheaf on $\mathbb R$ with $F(\mathbb R) = \mathbb Z$, $F(U) = \{0\}$ for every proper open $U$, and the restriction morphisms are the zero morphism : $r_U^V : F(V) \to F(U), s \mapsto 0$ (or the identity if $U=V$). Now pick a non-zero section $s \in F(\mathbb R)$, and take any proper cover $\{ U_i\}_{i \in I}$ of $\mathbb R$ (here proper means for all $i$, $U_i \neq \mathbb R$). Then, $r_{U_i}^{\mathbb R}(s) = 0$ for all $i$ but $s \neq 0$. A: Let $X$ be a topological space and let $\mathcal F(U)$ be the space of maps $U\to\mathbb R$ modulo constant maps. Let $X=\{1,2\}$, $U_1=\{1\}$, $U_2=\{2\}$. Then $\mathcal F(X)\cong \mathbb R$ wheras $\mathcal F(U_1)\cong \mathcal F(U_2)\cong 0$ so that the restrictions of a nonzero glocbal section are zero. You can do the same with any other not connected space $X$ Let $X=S^1$ and cover it by at least three open arcs, e.g., $U_1=\{\,(x,y)\in S^1\mid x>0\,\}$, $U_2=\{\,(x,y)\in S^1\mid y>0\,\}$, $U_3=\{\,(x,y)\in S^1\mid x+y<0\,\}$. For each arc, we can define a continuous branch of $\arg(z)$; these conincide (up to constant, which we modded out) on the intersections, but there is no global continuous $\arg$ function.
[ "judaism.stackexchange", "0000095360.txt" ]
Q: Must the top of a sukkah be level? I saw this question about a portable sukkah and I immediately thought of those pop-up canopies that you sometimes see at picnics and the like. The canopy has a metal or plastic frame that folds up and a (usually plastic) cover over the top. I've seen ones where the cover can be removed. This seems like a reasonable basis for a portable sukkah except for one thing: these canopies have a peak in the center (to shed rain). That would make it difficult to have the s'chach level with the ground: And that made me wonder: Is the s'chach required to be level? Or is a sukkah allowed to have a peaked or pointed roof? Assume, for purposes of this question, kosher supporting materials and a means of attaching s'chach to a slanted frame; I'm just asking about the legality of the shape. (A similar question arises with a palapa, a temporary structure with a convex roof but does not question the validity of the slanted roof rather the validity of the structure itself if perched in a place that will destroy the succcah e.g sea shore.) A: This is addressed in Shulchan Aruch Orach Chaim 631,10: סוכה שאין לה גג כגון שהיו ראשי הדפנות דבוקות זו בזו כמין צריף או שסמך ראש הדופן של סוכה לכותל פסולה ואם היה לה גג אפילו טפח או שהגביה הדופן הסמוך לכותל מן הקרקע טפח הרי זו כשרה. הגה: וצריך שיהיה בה שבעה טפחים על שבעה בגובה עשרה טפחים (טור) A Succah without a flat roof at all e.g the entire walls slant and meet in the middle like a tent, alternatively one wall is slanted against a straight wall is Invalid. But if there was a section of roof flat roof even a Tefach (Hand-breadth )alternatively the slanted wall(s) rested on a vertical wall with a length of a tefach form the ground this is Kosher. Rema: But we need a volume of 7 by 7 tefachim with a height of 10 tefachim within these slanted walls (that have a tefach horizontal roof with sechach or vertical wall). So yes your gazebo has straight walls much larger than 1 tefach (and the volume of a gazebo is much larger than 7x7x10), so putting the Sechach on the slanted sections of the roof makes it Kosher with 3 walls.
[ "math.stackexchange", "0002351859.txt" ]
Q: Can 38012 460109 621768 889218 be expressed as a sum of two fourth powers? Is 38012 460109 621768 889218 the sum of two fourth powers? I suspect that this number is the sum of two fourth powers. Can anyone use Wolfram Mathematica or SAGE to check whether this number is the sum of two fourth powers ? The complete factorization of this number is given by : 38012 460109 621768 889218 = 2 × 41 × 1217 × 21529 × 27617 × 640 650529 Notice that all the factors are of the form 16n+1 or 16n+9 . Hence this number may be the sum of two fourth powers. A: The answers to the questions asked are "No" and "Yes" respectively. By inspection of the factorization, the number is the double of an odd number. Therefore, we cannot have $(2x)^4+(2y)^4$ or $(2x)^4+(2y+1)^4$, as these both produce the wrong number of factors of $2$. Therefore the form we must have is $(2x+1)^4+(2y+1)^4$. We can rewrite this as $(10x+a)^4+(10y+b)^4$ for $a,b\in\{1,3,5,7,9\}$. From this we get that $a^2,b^2\in\{1,5,9\}\mod 10$ and further that $a^4,b^4\in\{1,5\}\mod 10$. Using a simplification of the binomial theorem, we get $(10x+a)^4+(10y+b)^4=10q+a^4+10r+b^4$, and since $a^4,b^4\in\{1,5\}\mod 10$, we get $a^4+b^4\in\{0,2,6\}\mod 10$, and so the specified number cannot be the sum of two fourth powers. A: The fourth power of any integer ends in $0,1,5$,or $6$, so you can't add two of these to get your number which ends in $8$. Also, here is the relevant Wolfram Alpha query which confirms there are no integer solutions.
[ "ell.stackexchange", "0000240579.txt" ]
Q: "is broken" "does not work" "is not working" In one of my posts ("get it repaired" vs. "repair it") I said My phone is broken Actually, what I suffered is that my phone repeatedly restart by itself. Is it appropriate to describe that problem as "broken"? Or, only the following status is called "broken". If it is, is "repeatedly restart by itself" called "does not work" or "is not working"? A: "The phone is broken" is appropriate for any disfunction, as well as for what is pictured. To really express what is in the picture, though, you might want to say "My phone got smashed!". As for repeatedly restarting, while "is broke" applies, it's not very specific. If you are sending it in for repair, you will need to be more specific. "Is broken" can apply to any device or machine that doesn't work as it should.
[ "stackoverflow", "0023377730.txt" ]
Q: How do I turn .Any into a for loop? I'm having some trouble turning the following code into a for loop. The purpose of the code is to check if the string has both a letter and a number in it. else if (!string.Any(Char.IsLetter) || !string.Any(Char.IsDigit)) { return false; } Any ideas? A: Do you mean something like this? bool anyLetter = false; bool anyDigit = false; foreach(var ch in str) { if(char.IsLetter(ch)) anyLetter = true; if(char.IsDigit(ch)) anyDigit = true; if(anyLetter && anyDigit) break; } return anyLetter || anyDigit; Note that if this string should contain at least one digit and one letter, you need to use && instead of ||
[ "stackoverflow", "0013205507.txt" ]
Q: Jquery Scroll text with middle pause I have a <div> with lists (ul, li). I want a Jquery plugin to do the text scrolling from left faster and pause during few second in the middle of the <div>. Then the text scroll to right and disappear. Do you have plugin names? Thanks. EDIT : After help of mrtsherman, I successful create the script. There is the solution : $(document).ready(function() { $('#affichage_titreSemaine > span').css('opacity', '0'); function TitresSemaine() { // get the item that currently has the 'show' class var current = $('#affichage_titreSemaine .show'); var next = current.next().length ? current.next() : $('#affichage_titreSemaine span :first'); // fade out the current item and remove the 'show' class current.animate( {opacity: "1.0", marginLeft: 465 - (current.width())/2}, 500, 'swing'); current.delay(2000).animate( {opacity: "0.0", marginLeft: 930 - current.width()}, 500, 'swing', function(){ $(this).animate({marginLeft : 0}, 10, 'swing'); $(this).hide(); next.addClass("show"); next.show(); }).removeClass("show"); // repeat by calling the textloop method again after 3 seconds setTimeout(TitresSemaine,4000); } TitresSemaine(); }); A: I think you are looking for something like this. I don't know of a plugin that does it, but pretty easy to code yourself using animation callbacks. http://jsfiddle.net/ABaEE/ $('span').animate( {marginLeft:0}, 1500, 'swing', function() { $(this).delay(2000).animate( {marginLeft:250}, 1500, 'swing'); });
[ "stackoverflow", "0033368870.txt" ]
Q: How can I use an existing .target file in Eclipse? I would like to develop plugins for an RCP Applicaction. Now, they provide a .target file for development. I tried to read on several Eclipse pages but I could not find out how to use that file. Do I have to load it somewhere? Do I have to add it at a specific location? I'm sure, I missed something... Please give me a hint. A: Use the target definition editor to open the target file. You will need to have the Plug-in development tools (PDE) installed to develop plug-ins for RCP applications. PDE can be installed into an existing IDE from the projects download page. Or you can download an Eclipse package that contains PDE. This page gives an overview which package contains what. However, I recommend to choose the Eclipse for RCP and RAP develoipers If you have PDE installed and the target file is located in the workspace, it is the default editor (i.e. you can simply doiuble click the respective entry in the package explorer). Use the Set as target platform in the top right corner of the target editor to make it the current target platform. The current target platform constitutes the plug-ins which your workspace will be built and run against. It describes the platform that you are developing for. Once a target platform is known to the IDE it can also the changed through the Plug-in Development > Target Platform preference page. There is also an option to show the name of the current target platform in the status bar on the Plug-in Development preference page.
[ "stackoverflow", "0023414236.txt" ]
Q: Get specific iFrame class with jQuery (or get CKEditor value) I am getting an iFrame this way currently: $('body', window.parent.frames[0].document) This is for CKEditor, the WYSIWYG html editor. However, I believe it dynamically adds certain other frames (not sure how). So I rather just get a specific frame by a class name that I know will always be there (unlike the above method which will only get the first instance). The class name is: cke_wysiwyg_frame How can I do this? (The reason is I am saving the content to my database with a button; the button needs to know where the CKEditor content is. So far the way I am doing it is unreliable.) Edit: I decided to do it the correct way using the Ckeditor API and not my requested hack above. A: To get the value from an editor instance, you can reference the instance and use getData CKEDITOR.instances.editorId.getData();
[ "stackoverflow", "0017997808.txt" ]
Q: PayPal API - How to keep the payment process on my website? I run a small marketplace with multiple sellers where buyers can buy items and pay with PayPal. The problem is, when someone makes a payment, they are then displayed the "Payment Confirmation" on the PayPal website and are given a choice to either return to their PayPal account, or return to the website. Is there any way to keep the payment flow on my website, except for the payment part? I notice when buying on Etsy for example, the buyer goes to PayPal to make the payment and is then immediately returned to Etsy for the payment confirmation. They never see the PayPal payment confirmation page. I assume it could be because Etsy and PayPal have a special arrangement that isn't available to other sites? Or am I missing something in the API? Right now, with the normal PayPal API, this is what buyers see: NAME, you've just completed your payment. Your transaction ID for this payment is: XXXXXXXXXXXXXXXXXXXX. We'll send a confirmation email to [email protected] Go to PayPal account overview. Go back to "[email protected]". I can't even figure out how to change the "Go back to..." link to my website name in the hidden fields. PayPal just chooses to display the seller's (the person that received the payment) email address. Is there any way to at least set a website name for them to return to with hidden variables? Keep in mind that I have different sellers, so it's not something I could set inside each seller's PayPal account. Thank you :) A: I assume you are using Express Checkout with Set/Get/Do EC API integration. Please check the below document for experience options available with Express Checkout API. https://developer.paypal.com/webapps/developer/docs/classic/express-checkout/integration-guide/ECCustomizing/ The 'useraction=commit' in the PayPal payment auth url triigers the 'Buy' button. If you do not send that request paramter then it will show 'continue' button and you can complete rest of the process on your site. However, if you are using Paypal Payment Standard product then you need to use Express Checkout to accomplish the outcome you are seeking.
[ "law.stackexchange", "0000039101.txt" ]
Q: What is the effect of a pardon by the President of the United States? An answer to a recent question stated: In modern, peacetime U.S. practice, the main use of the pardon power has been to restore the civil rights of people who admit to having committed crimes and have served their sentences and reformed, so that they can, for example, apply for a job not available to felons, or vote, or get a hunting license and use a firearm. Only a tiny share of modern pardons are granted to people who are currently serving sentences for the crimes of which they were convicted or to people who have not yet been convicted of crimes. My understanding is that a pardon only effects that you no longer must bear the consequences of a conviction, it does not remove the conviction. Thus I want to ask for clarification on the part where it states that pardoned individuals "apply for a job not available to felons, or vote, or get a hunting license and use a firearm". I figure the three options are either: I am not entirely correct about what a pardon by the President does. The prohibitions on felons to applying for jobs not available to felons, voting, get a hunting license and using a firearm are part of the pardon The statement is not correct. What are the actual legal effects of pardons issued by the President of the United States? A: It depends on your location. A felony conviction can limit your rights in various ways, and those rights may or may not be restored at the state level. See this article for discussion of federal convictions and collateral civil disabilities. The Dept. of Justics says that "a presidential pardon will restore various rights lost as a result of the pardoned offense and should lessen to some extent the stigma arising from a conviction, it will not erase or expunge the record of your conviction", and "most civil disabilities attendant upon a federal felony conviction, such as loss of the right to vote and hold state public office, are imposed by state rather than federal law, and also may be removed by state action". This article surveys civil disabilities of convicts on a state by state basis, as well as at the federal level. For example, voting rights are set at the state level, so a state has to have statutes restoring rights upon a pardon if you are to get your voting rights back. Service on a federal jury would be restored per 28 USC 1865(b)(5); the federal felon in possession crime has an exception encoded in it in the definition of "crime punishable by imprisonment for a term exceeding one year" which says What constitutes a conviction of such a crime shall be determined in accordance with the law of the jurisdiction in which the proceedings were held. Any conviction which has been expunged, or set aside or for which a person has been pardoned or has had civil rights restored shall not be considered a conviction for purposes of this chapter, unless such pardon, expungement, or restoration of civil rights expressly provides that the person may not ship, transport, possess, or receive firearms. So if you are a state felon, you need a state pardon (or other state procedure) and if you are a federal felon, a state pardon does no good, you need a federal pardon. However, 21 USC 862 makes mandatory the ineligibility for federal benefits after a third conviction for drug trafficking (either state of federal law), and there is no "rights restoration" clause that restores such rights after a pardon even if the convictions are all federal. I have not located any case law establishing whether federal benefits rights restoration for federal convictions flows automatically from a federal pardon (not many 3-time drug dealers get federal pardons). A federal felony conviction can also be used as a factor in granting a security clearance (applicable to certain jobs), and current law does not say that a pardoned conviction cannot be considered in deciding on a clearance.
[ "matheducators.stackexchange", "0000017693.txt" ]
Q: Lack of intuition, retention while self studying I am a first year undergraduate student, currently in second semester. So basically I learnt most of the first year stuff in high school, so I have a lot of free time in this year (currently in second semester), and thus I'm self studying math in the free time. In the first sem I tried reading some measure theory and lebesgue integration, some galois theory and some algebraic topology (I think I had the prequisites -- I did half of baby Rudin, most of Artin and Topology, Willard in high school). So here are my problems: I tend to pick up very little "big picture" intuition while self studying. I was learning measure theory from Stein Shakarchi, and my experience - it's hard to describe in words - was like I can follow the theorems as a standalone basis, I don't have much difficulty solving the exercises but I was heavily bogged down in the details so I could neither see the big picture nor any non-trivial/deep connection between what's done in a page and what was done say three pages ago. I have an extremely terrible memory. My memory is so bad is that while I recall working on an abstract algebra book till Fundamental theorem of Galois Theory around in October, now I forgot what's a simple field extension (or even worse, I forgot the exact statement of Fundamental Theorem of Galois theory ! Only thing I remember is that under some conditions on $K \subset L$ it gave a one to one correpsondence between intermediate fields between $K$ and $L$ and the subgroups of $Gal(L/K)$, and one direction is not hard but the other requires linear independence of characters)! This is extremely frustrating, when you forget what you learn one/two months ago completely. I was a relatively good problem solver in high school (did quite well in national/regional math olympiads) but my problems solving skills don't seem to be that good in college level math. For example, I tried proving Hilbert's Weak Nullstellensatz (when I was studying it from Artin) couldn't prove it even though the proof is "short". If you say it's short but tricky -- well I couldn't even prove the fact that the characters are linearly independent (I recall trying for like 30 minutes and then being frustrated since it seemed a pretty easy proof and then seeing the proof). Due to #2 and lack of mathematical maturity, I tend to give a shot at the proof of some theorem myself before seeing the solution, but this way consumes a huge amount of time and also I fail to prove the theorems when it's nontrivial in most of the cases. So basically I still have plethora of time in this semester (just started; four months long) and I plan to self study some complex analysis, manifolds and algebraic number theory but the points above are heavily discouraging me to self study math or pursue math in general. Whenever I start to read a book I feel depressed as the pointlessness of me studying a book since (a) I will not have any big-picture understanding of it and (b) I will forget what I did after a while anyway (if I don't use it). Also I am currently the topper of my batch (which consists of one IMO medalist and many national olympians) -- but that's solely because I knew most of the course materials beforehand so I didn't need to put in too much effort outside the class to understand the stuff. As I mentioned in the points above, it's hard for me to get used to and not forget new and hard math so sometimes I feel insecure about performing extremely terribly in the upper division courses which I didn't know a priori (basically I wouldn't have any edge in those courses), so this is discouraging me more to study maths. Am I making any obvious mistake while self studying ? Is there any global change which I should make to end up with much better understanding/retention of the material ? Would be a wise choice for me to not stay in academia and move on to CS/other applied math courses ? Note: People can suggest actually sitting in the lectures of the courses I want to self study, but that's not feasible for me: While most profs are friendly towards second year people or higher auditing any course (basically sitting in the lecture w/o crediting it), they're mostly cold towards first year people sitting in the lectures. [Crossposted from Math SE] A: Perhaps you should seek texts that emphasize the high-level viewpoint that you are missing in the details of the more advanced texts. Three examples: (1) Bressoud, David M. A radical approach to Lebesgue's theory of integration. Cambridge University Press, 2008. MAA Review. (2) Hajime Sato. Algebraic Topology: An Intuitive Approach. Transl: Kiki Hudson. Transl. of Math. Mono., V. 183. AMS, 1999. MAA Review. (3) Ghrist, Robert W. Elementary applied topology. Vol. 1. Seattle: Createspace, 2014. AMS Review If you grasp "the big picture," then perhaps your retention will improve, as then the concepts are pinned to a mental map rather than floating free. A: You need to pick pedagogically appropriate texts. Not the Rudin ballbusters. Pick ones that have explanations and were written for students with occasional imperfections in their previous knowledge. Don't go too much off of what people say on the net is teh ultimate book to use. SINCE IT ISN'T WORKING FOR YOU. Find other texts that you can handle. Obviously the tougher texts will be made more accessible if you know some of the material already and then only have to deal with the shitty pedagogy. Also, you need to have a source of problems that includes more progression (some easy problems, not just the skullcrackers, at least a section of easy, section of medium, section of hard). As a self studier, it is important to have the answers to the problems as well. (Ideally, worked solutions, but at a minimum answers...so you have a feedback loop.) I also question moving straight into real analysis versus doing other topics first (e.g. differential equations). At a minimum, I think you'd find it easier and thus a better choice to self study. Could then do real analysis with the benefit of instruction. You don't read math, you work it. As far as memory and concepts and the like, this is related to (1) and (4). You are doing insufficient drill problems, particularly insufficient basic ones. Saying "I got it" is not sufficient, if you don't "got it" a few days later. Grind the groove in. You need to be Umbridge's pen and your mind needs to be Harry Potter's hand. A: Your question sounds to me like: I have a terrible memory I can't intuitively understand some of the new things i come across I've seen this plenty of times, but not in maths. I've seen this in linguistics. Languages as a whole, aren't built from logic. They just kind of happened, and we attributed some logic to them. Due to this, any adult language learner, trying to learn a second language for the first time will have to Memorize thousands of root words before reaching a good deal of fluency. How can someone memorize so much? The solution : Spaced Repetition. https://www.fluentin3months.com/spaced-repetition/ When it comes to the question of how often, I prefer short doses, with long breaks between them, on a daily basis. A soft rule is an hour a day : 15 minutes in the morning, 30 minutes in the afternoon and 15 minutes in the evening. Personally, i believe that one can only be fluent in a language when they understand it intuitively. That, is less a question of intelligence and good memory, and more a question of practicing the above, for a length of time. How much time : About 2-3 months. Personally, from studying Japanese over the past 2 years, i found words and characters become intuitive after 3(ish) months. Between you and me, i believe that intuition and habits stem from the same thing, as both are reflexive behaviors. Here's a solid article on habit formation: https://jamesclear.com/new-habit I like to think of a new piece of knowledge like a single piece of grain: Plant it in the spring, tend to it during the summer, harvest it in the autumn. Never harvest too early and never expect to harvest without tending to the crops. Finally, how do language learners study new words and phrases : Flashcards. https://apps.ankiweb.net/ You need to make flashcards that are 1 to 1. Questions need to have a single output. For example, in english, the word 'set' can have 464 meanings. Sticking all of those into the back of one card would be terrible. However, creating 464 cards, with 464 situations where the word set is used to convey it's meaning, that'd be better. After learning all 464, you may not know the exact linguistic description of the word, but you would end up with an intuitive understanding. Now, do take this all with a pinch of salt, as this is completely from my own experience.
[ "mathematica.stackexchange", "0000175245.txt" ]
Q: Import specific columns from a large amount of CSV files I'm looking to import the 4th column of data from a few hundred CSV files that I have stored in various folders. I have been able to import all CSV files from a given directory through use of: allFiles = Filenames[".csv","/filepath/"]; and list1 = Import[#,"Dataset"]&/@allFiles; However, I haven't been able to extract the 4th column of data from the lists once the files have been imported. Is there an easier way to do this? A: TL; DR Import[#, {"CSV", "Data", All, 4}] & Import specific columns Notice in the documentation for Import and for CSV that it explicitly states that you can do Import["file.csv",{element, subelement1, subelement2], ...}] to import subelements, specifically useful for partial data import. Example Example data data = Table[ FromDigits[{i , j}] , {i, 0, 9} , {j, 1, 10} ]; TableForm[ data , TableHeadings -> Automatic ] Save to file Export[ "Test.CSV" , data ]; Import Import["Test.CSV", {"CSV", "Data", All, 4}] (*{4, 14, 24, 34, 44, 54, 64, 74, 84, 94} *)
[ "physics.stackexchange", "0000095234.txt" ]
Q: Toppling of a cylinder on a block A uniform cylinder rests on a cart.The height and diameter is given.coefficient of static friction is given.How can i find the minimum acceleration of block such that the block topples? Morever what is the reason of toppling? Again, if i consider static friction to be the cause,then what is the point of rotation? If i consider the top to be te point of rotation,then why does the block topple with the lower end as point?I have conducted this experiment many times and if the block falls,it fell along the lower end. A: This is how to think about the problem, not how to do the calculations. An external force on the cylinder always accelerates the cylinder. It may also cause the cylinder to rotate. The rotation depends on where the force is applied. The cylinder is made of many atoms rigidly connected together. If you pull on one atom, it exerts a force on its neighbors, which pull on their neighbors, and so on. The result is the whole cylinder moves or rotates, but distances and angles among the atoms don't change. These are internal forces. They change the motion of individual atoms. But since the sum is 0, they don't change the acceleration of the cylinder as a whole. We will mostly gloss over them. In general, the goal is to think about the cylinder as a whole. You want to do calculations with mass, moment of inertia, external forces, and such. You don't want to think about atoms and the internal interatomic forces. But to get the idea, we will look at the pieces of a simpler system. Three identical rigidly connected blocks are floating in space. You exert a force on the bottom block. Forces and accelerations are vectors. You can add them together to see the total effect of multiple forces. This property of vectors is really useful. Sometimes replacing many little forces with one big force makes a calculation simpler. Likewise, you can pretend that one force is really multiple forces, so long as the sum is the same, and you are careful to apply the forces at a points that produces the same torque. Sometimes this allows you to consider a problem piece by piece, where each piece is easier to understand. You get the same accelerations (and therefore the same motion) with these three forces, because two forces on the middle block cancel. Divide the problem into these two pieces. A force through the center of mass accelerates the system without rotating it. Two equal and opposite forces, not on the same line, are a torque. They rotate the system without displacing the center of mass. The torque will move the bottom block forward, the top block backward, and leave the center block still. If you apply the three forces for a short time, they will cause small displacements to each block. Small displacements are vectors. The total displacement of each block is the sum of displacements from each piece of the problem. The bottom block has two (unequal) forward displacements. The middle block has one displacement. The top has a forward displacement and a backward displacement. If you drew a line through the blocks, you would find some point on the line doesn't move. For that point, the forward displacement from one part of the problem cancels the backward displacement from the other. It turns out this point is between the top and middle blocks. For the cylinder, it may appear that the rotation is around the bottom of the cylinder because the bottom is at rest with respect to the cart. But the cart is moving. To see why a minimum acceleration is needed to topple the cylinder, we will look at 4 blocks sitting on a cart. When the cart is still, there are two external forces: gravity and an upward force from the surface of the cart. I have drawn the external forces off to the side. Gravity exerts a force $mg$ on each block. You should be able to see that this does not cause any rotation. The cart exerts an upward force that is just strong enough to keep the blocks from penetrating the surface of the cart. This is $2mg$ on each bottom block. This does not cause any rotation. We would get the same result if gravity was a single force, $2mg$, applied to each bottom block. When the cart accelerates slowly, friction adds small torques and an irrotational force at the center of mass. This shows only the new forces. Note that we would get the same result if torques like this had been applied. The surface of the cart exerts an upward force just strong enough to keep the blocks from penetrating the surface. Notice the upward forces must be unequal to prevent rotation, which would cause the back block to penetrate the surface. Now your job is to repeat this analysis with a cylinder instead of blocks. You might want to keep in mind that the force of gravity on each atom can be rearranged in different ways to produce the same result. You can have one force at the center of mass. You can have one force at the bottom of the cylinder if you choose the right place. You can split it into two or more forces at different places on the bottom. Likewise the force of friction on each atom at the bottom of the cylinder can be rearranged. Choose carefully to make the problem simple.
[ "stackoverflow", "0026796542.txt" ]
Q: How to remove a specific index from a multidimensional array in php I am trying to remove pieces of a multidimensional array if a certain condition is met. The array can be as shown below, call it $friends: array (size=3) 0 => array (size=1) 0 => object(stdClass)[500] public 'id' => int 2 public 'first_name' => string 'Mary' (length=4) public 'last_name' => string 'Sweet' (length=5) 1 => array (size=1) 0 => object(stdClass)[501] public 'id' => int 9 public 'first_name' => string 'Joe' (length=3) public 'last_name' => string 'Bob' (length=3) 2 => array (size=1) 0 => object(stdClass)[502] public 'id' => int 1 public 'first_name' => string 'Shag' (length=4) public 'last_name' => string 'Well' (length=4) I have a function called is_followed, that let's me see if the id of one of the people in the array is being followed by the "user". The code I am trying is: //remove followed friends from the $friends array $i=0; foreach($friends as $friend) { foreach($friend as $f) { if(Fanfollow::is_followed($id,$f->id)) { unset($friend[$i]); } } $i++; } The $id is the id of the current user. However, this is not working. I know that using unset on $friend and not $friends is probably the issue. But using unset on $friends also won't work, because it is the higher level array. Any ideas? Thank you. A: If you're trying to take down the first parent keys, use the first foreach keys instead: foreach($friends as $i => $friend) { // ^ assign a key foreach($friend as $f) { if(Fanfollow::is_followed($id,$f->id)) { unset($friends[$i]); // unset this } } } Or if only for that single friend: foreach($friends as $friend) { foreach($friend as $i => $f) { // ^ this key if(Fanfollow::is_followed($id,$f->id)) { unset($friend[$i]); // unset this } } }
[ "stackoverflow", "0048748427.txt" ]
Q: Slickgrid header row filtering empty cells not working in example I was looking into this example and saw that filtering does not happen when searching for empty cells. This means I typed any string in the filterbox and then removing the string. However, when debugging it locally and making some cells empty, I saw that dataview.refresh() is called upon an empty input, the grid just doesn't display the empty cells. In my application I have a use case where one might want to search for all cells that have no content, so my question is, is this something that can be changed, or is it baked deeply under the Slickgrid hood? I can understand the use case in the linked example, as it already loads the filters on page load, but in my application the filter is only applied after a confirmation button click. Thanks for your help. A: This is all completely configurable. In the example you link, dataView.setFilter(filter); sets up the filtering, and passes the filter function function filter(item) { for (var columnId in columnFilters) { if (columnId !== undefined && columnFilters[columnId] !== "") { var c = grid.getColumns()[grid.getColumnIndex(columnId)]; if (item[c.field] != columnFilters[columnId]) { return false; } } } return true; } To make the changes you suggest, simply edit the columnFilters[columnId] !== "" bit. You'll need to work out some other way of telling whether to apply the filter or not, rather than an empty string.
[ "stackoverflow", "0056827805.txt" ]
Q: only adapted untyped ActorRefs permissible I am trying to test my actors with Actor discovery as follows: class DetectorSpec extends BddSpec { private val sap = new SapMock() .withExposedPorts(8080) .waitingFor(Wait.forHttp("/")) private val kafka = new KafkaContainer("5.2.1") sap.start() kafka.start() override def afterAll(): Unit = { sap.stop() kafka.stop() } private def withKafkaAndSapOnline(testCode: TestInbox[ServerEvent] => Future[Assertion]) : Future[Assertion] = { val config = ConfigFactory.parseString( s""" kafka { servers = "${kafka.getBootstrapServers}" } sap { server = "ws://${sap.getContainerIpAddress}:${sap.getMappedPort(8080)}" }""") val system = ActorSystem(DetectorSupervisor.create(), "testSystem1", config) val inbox = TestInbox[ServerEvent]() system.receptionist ! Receptionist.Register(ServerStateKey, inbox.ref) complete { testCode(inbox) } lastly { system.terminate() } } feature("Detect Kafka and SAP availability") { info("As a technical user, I want to be notified in real time, if Kafka and SAP is up and running or not.") scenario("SAP and Kafka are available") { withKafkaAndSapOnline { inbox => Given("I am waiting for the current state message") When("I am receive the state message") Then("it should contain `SAP and Kafka are online`") Future { inbox.receiveMessage() should be(ServerOnlineApproved) } } } } } When I start test, I've got the following error message: [ERROR] [06/30/2019 22:15:07.643] [testSystem3-akka.actor.default-dispatcher-3] [akka://testSystem3/system/receptionist] only adapted untyped ActorRefs permissible (Actor[akka.actor.typed.inbox://anonymous/inbox#-233829306] of class akka.actor.testkit.typed.internal.FunctionRef) akka.actor.ActorInitializationException: akka://testSystem3/system/receptionist/$a: exception during creation at akka.actor.ActorInitializationException$.apply(Actor.scala:202) at akka.actor.ActorCell.create(ActorCell.scala:696) at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:547) at akka.actor.ActorCell.systemInvoke(ActorCell.scala:569) at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:293) at akka.dispatch.Mailbox.run(Mailbox.scala:228) at akka.dispatch.Mailbox.exec(Mailbox.scala:241) at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) Caused by: java.lang.UnsupportedOperationException: only adapted untyped ActorRefs permissible (Actor[akka.actor.typed.inbox://anonymous/inbox#-233829306] of class akka.actor.testkit.typed.internal.FunctionRef) at akka.actor.typed.internal.adapter.ActorRefAdapter$.toUntyped(ActorRefAdapter.scala:55) at akka.actor.typed.internal.adapter.ActorContextAdapter.watch(ActorContextAdapter.scala:99) at akka.actor.typed.internal.receptionist.LocalReceptionist$.$anonfun$behavior$2(LocalReceptionist.scala:64) at akka.actor.typed.Behavior$DeferredBehavior$$anon$1.apply(Behavior.scala:264) at akka.actor.typed.Behavior$.start(Behavior.scala:331) at akka.actor.typed.internal.adapter.ActorAdapter.preStart(ActorAdapter.scala:238) at akka.actor.Actor.aroundPreStart(Actor.scala:550) at akka.actor.Actor.aroundPreStart$(Actor.scala:550) at akka.actor.typed.internal.adapter.ActorAdapter.aroundPreStart(ActorAdapter.scala:51) at akka.actor.ActorCell.create(ActorCell.scala:676) ... 9 more The problem is for sure: system.receptionist ! Receptionist.Register(ServerStateKey, inbox.ref) But what am I doing wrong? A: The Inbox is not a real actor (it's implemented using a FunctionRef) and cannot be registered to the receptionist. Use a TestProbe[T] instead in tests. That works since those are backed with a real actor.
[ "stackoverflow", "0003221687.txt" ]
Q: Risk evaluation for framework selection I'm planning on starting a new project, and am evaluating various web frameworks. There is one that I'm seriously considering, but I worry about its lasting power. When choosing a web framework, what should I look for when deciding what to go with? Here's what I have noticed with the framework I'm looking at: Small community. There are only a few messages on the users list each day No news on the "news" page since the previous release, over 6 months ago No svn commits in the last 30 days Good documentation, but wiki not updated since previous release Most recent release still not in a maven repository It is not the officially sanctioned Java EE framework, but I've seen several people mention it as a good solution in answers to various questions on Stack Overflow. I'm not going to say which framework I'm looking at, because I don't want this to get into a framework war. I want to know what other aspects of the project I should look at in my evaluation of risk. This should apply to other areas besides just Java EE web, like ORM, etc. A: I'll say that so-called "dead" projects are not that great a danger as long as the project itself is solid and you like it. The thing is that if the library or framework already does everything you can think you want, then it's not such a big deal. If you get a stable project up and running then you should be done thinking about the framework (done!) and focus only on your webapp. You shouldn't be required to update the framework itself with the latest release every month. Personally, I think the most important point is that you find one that is intuitive to your project. What makes the most sense? MVC? Should each element in the URL be a separate object? How would interactivity (AJAX) work? It makes no sense to pick something just because it's an "industry standard" or because it's used by a lot of big-name sites. Maybe they chose it for needs entirely different from yours. Read the tutorials for each framework and be critical. If it doesn't gel with your way of thinking, or you have seen it done more elegantly, then move on. What you are considering here is the design and good design is tantamount for staying flexible and scalable. There's hundreds of web frameworks out there, old and new, in every language. You're bound to find half a dozen that works just the way you want to think in your project. Points I consider mandatory: Extensible through plug-ins: check if there's already plug-ins for various middleware tasks such as memcache, gzip, OpenID, AJAX goodness, etc. Simplicity and modularity: the more complex, the steeper the learning curve and the less you can trust its stability; the more "locked" to specific technologies, the higher the chances that you'll end up with a chain around your ankle. Database agnostic: can you use sqlite3 for development and then switch to your production DB by changing a single line of code or configuration? Platform agnostic: can you run it on Apache, lighttpd, etc.? Could you port it to run in a cloud? Template agnostic: can you switch out the template system? Let's say you hire dedicated designers and they really want to go with something else. Documentation: I am not that strict if it's open-source, but there would need to be enough official documentation to enable me to fully understand how to write my own plug-ins, for example. Also look to see if there's source code of working sites using the same framework. License and source code: do you have access to the source code and are you allowed to modify it? Consider if you can use it commercially! (Even if you have no current plans to do that currently.) All in all: flexibility. If I am satisfied with all four points, I'm pretty much done. Notice how I didn't have anything about "deadness" in there? If the core design is good and there's easily installable plug-ins for doing every web-dev 3.0-beta buzzword thing you want to do, then I don't care if the last SVN commit was in 2006.
[ "stackoverflow", "0050283743.txt" ]
Q: React.js, pulling data from api and then looping through to display Im new to react. I am trying to pull data from an API, and then loop through it and display it. Error : Cannot read property 'map' of undefined. The API data is coming through, but it seems as if React is calling the looplistings before the data is stored into State. constructor () { super() this.state = { data:'', } } componentWillMount(){ // Im using axios here to get the info, confirmed data coming in. //Updating 'data' state to equal the response data from the api call. } loopListings = () => { return this.state.data.hits.map((item, i) => { return(<div className="item-container" key={i}> <div className="item-image"></div> <div className="item-details">tssss</div> </div>) }) } loopListings = () => { return this.state.data.hits.map((item, i) => { return( <div className="item-container" key={i}> <div className="item-image"></div> <div className="item-details">tssss</div> </div>) }) } render () { return ( <div> {this.loopListings()} </div> ) } A: The reason you are receiving this error is that your call to the API is happening asynchronously to the react lifecycle methods. By the time the API response returned and persisted into the state the render method has been called for the first time and failed due to the fact you were trying to access an attribute on a yet undefined object. In order to solve this, you need to make sure that until the API response has been persisted into the state the render method will not try to access that part of the state in your render method or to make sure that if it does there is a valid default state in the constructor: Solve this by changing your render to do something like this: render () { return ( <div> {this.state.data && Array.isArray(this.state.data.hits) && this.loopListings()} </div> ) } or initialize your constructor like so : constructor () { super() this.state = { data: {hits: []}, } } Remeber react is just javascript and its behavior is just the same.
[ "stackoverflow", "0011917911.txt" ]
Q: How to detect if a string has UTF-8 characters in it? Possible Duplicate: How do I detect non-ASCII characters in a string? I have an array representing a US-ASCII transliteration table, liket this one: http://www.geopostcodes.com/encoding#az If the string has one of those characters, then I replace it with the ASCII correspondent (with strtr). Because the array is huge, I wish to load it into a variable and transliterate the string only if the string contains these type of UTF-8 characters. Is there a decently fast way to find this out? A: There is no real way to do this. However, if you don't need any codepoints above ASCII 127 (so no "extended ASCII" like éáÿ), you can check if any bytes have the first bit set: for (var i = 0; i < text.length; i++) if (ord(text[i]) > 127) // Unicode/UTF-8 character!
[ "stackoverflow", "0060143362.txt" ]
Q: Writing NPM package, how do I specify that a PNG file path is in reference to the node_module script as opposed to from where it's imported I'm writing a npm package that requires importing PNG files from within the package: Directory Structure __test__ __test__/test.js src src/resources src/resources/PNG Image File src/index.js I'm using require(../src/index.js) from within test.js. Whenever I try to reach ./resources/image.png from index.js, the path is attempted from within __test__ (because it's technically being imported an run by test.js. I can't use the path ../src/resources because the goal is to create this as an NPM package that can be imported from anywhere. What's the best way to specify within index.js that no matter where it's run, it should be looking within it's own directory for these image files. A: You can use __dirname to represent the directory where your module was loaded from which is independent of how it was loaded. So, from within index.js, you can refer to your PNG file llocation ike this: let pngFileDirectory = path.join(__dirname, "..", resources); And, if you know the filename you're looking for: let pngFile = path.join(__dirname, "..", resources, "myFile.png"); Done this way, you dynamically construct the path relative to your own module file. Since the image file is part of the same NPM installation, the PNG file is in a fixed relative location to your own module file and this is independent of how your module was loaded or what the current working directory is in the project. Using __dirname is the key.
[ "stackoverflow", "0047820623.txt" ]
Q: HTML multiple image tags with same image only showing one image instead of same image many times I have some HTML code with a animating GIF as placeholder to show while the browser is waiting for data like this: <div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count"> <span class="count_top"><i class="fa fa-calculator"></i> Total Units</span> <div id="total_units_content" class="count" > <img border="0" id="avatar-green" alt="avatar-green" src="~/images/avatar-green.gif" width=50" height="50"> </div> <span class="count_bottom"><i class="green">0% </i> From last Week </span> </div> <div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count"> <span class="count_top"> <i class="fa fa-cloud"></i> Total units online </span> <div id="total_units_online_content" class="count" > <img border="0" id="avatar-green" alt="avatar-green" src="~/images/avatar-green.gif" width=50" height="50"> </div> <span class="count_bottom"> <i class="green"><i class="fa fa-sort-asc"></i>0% </i> From last Week </span> </div> <div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count"> <span class="count_top"> <i class="fa fa-close"></i> Total units offline </span> <div id="total_units_offline_content" class="count green"> <img border="0" alt="avatar-green" src="~/images/avatar-green.gif" width=50" height="50"> </div> <span class="count_bottom"><i class="green"> <i class="fa fa-sort-asc"></i>0% </i> From last Week </span> </div> The problem is that only the first image is showing, and I only get the alt text for the other images. Does anyone have an idea why this happens? A: All of your image tags are missing a " on width=50". Correct to width="50".
[ "mathoverflow", "0000172388.txt" ]
Q: A special case of the integer Hodge conjecture Let $X$ be a projective complex manifold of dimension $n$. Are torsion cohomology classes in $H^{2n-2}(X,\mathbb{Z})$ algebraic? (We may assume, without loss of generality, that $n=3$, because of the Lefschetz hyperplane theorem.) I know that torsion classes (of even codimension) aren't always algebraic; the first counterexamples were found by Atiyah and Hirzebruch in 1960s. But I do not know any counterexample in this codimension. Note that by Poincare duality $H^{2n-2}(X,\mathbb{Z})\cong H_2(X)$, so the equivalent question is whether torsion classes in $H_2(X)$ are generated by algebraic curves in $X$. This looks like a "dual" to the well known fact that torsion classes in $H^{2}(X,\mathbb{Z})$ are generated by divisors (it is a torsion part of the Neron-Severi group). A: This 2013 paper of Totaro says that it is an open question. But the integral Hodge conjecture is known to fail for dimension 1, just not via torsion.
[ "stackoverflow", "0031156623.txt" ]
Q: Take param in bash I need take params in bash, I can take the param h,c,p,s,a but i cant take the param b. Why can't I take it? This is my script: if [ ! -z $1 ]; then HOSTNAME="" CLIENT="" SUBSCRIPTIONS_GROUPS="" PROVIDER="" SERVER="" while getopts ":h:c:p:s:a:b" opt; do case $opt in h) HOSTNAME=${OPTARG} ;; c) CLIENT=${OPTARG} ;; p) PROVIDER=${OPTARG} ;; s) SUBSCRIPTIONS_GROUPS=${OPTARG} ;; a) ALWAYS_ON="on" ;; b) SERVER=${OPTARG} ;; ?) ;; esac done fi A: I see two flaws in your implementation: First character is colon After b there is no colon Your getops string should look like this: while getopts "h:c:p:s:ab:" opt; do ... When you want getopts to expect an argument for an option, just place a : (colon) after the proper option flag and If the very first character of the option-string is a : (colon), which would normally be nonsense because there's no option letter preceding it, getopts switches to "silent error reporting mode". In productive scripts, this is usually what you want because it allows you to handle errors yourself without being disturbed by annoying messages. Extracts from http://wiki.bash-hackers.org/howto/getopts_tutorial
[ "stackoverflow", "0009261205.txt" ]
Q: The SQL Server equivalent for the MySQL Limit Possible Duplicate: Equivalent of LIMIT and OFFSET for SQL Server? this is a mysql query SELECT email FROM emailTable LIMIT 9,20 WHERE id=3 how do you write it in SQL Server (2008)? do I have to write SELECT TOP 9,20 email FROM emailTable WHERE id=3 ? Thank you for your help A: Try this: SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY email) as rowNum FROM tableName ) sub WHERE rowNum > 9 AND rowNum <= 9 + 20 AND id = 3 DEMO
[ "stackoverflow", "0049830103.txt" ]
Q: Tree shaking doesn't work with babel loader in webpack 4 I'm tinkering with the tree shaking example from the webpack document. But it seems that tree shaking doesn't work once I add babel-loader to the mix. Here is an overview of my project: index.js: import { cube } from "./math"; function component() { const element = document.createElement('pre'); element.innerHTML = [ 'Hello webpack!', '5 cubed is equal to ' + cube(5) ].join('\n\n'); return element; } document.body.appendChild(component()); math.js: export function square(x) { console.log('square'); return x * x; } export function cube(x) { console.log('cube'); return x * x * x; } .babelrc: { "presets": [ ["env", { "modules": false }], "react" ], "plugins": ["react-hot-loader/babel"] } package.json: { "dependencies": { "react": "^16.3.1", "react-dom": "^16.3.1", "react-hot-loader": "^4.0.1" }, "name": "react-webpack-starter", "version": "1.0.0", "main": "index.js", "license": "MIT", "scripts": { "start": "webpack-dev-server --mode development --open --hot", "build": "webpack -p --optimize-minimize" }, "sideEffects": false, "devDependencies": { "babel-core": "^6.26.0", "babel-loader": "^7.1.4", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "html-webpack-plugin": "^3.2.0", "webpack": "^4.5.0", "webpack-cli": "^2.0.14", "webpack-dev-server": "^3.1.3" } } webpack.config.js: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.join(__dirname, '/dist'), filename: 'index_bundle.js' }, mode: 'production', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] }; As index.js is not consuming the square function, the square function should be pruned out of the bundle. However, when I open up the bundle.js and search for 'square', I can still find the square function and the console log statement. After I comment out the babel-loader specification in webpack config and npm run build again, the "square" word is nowhere to be seen in the generated bundle file. I did specify modules: false in .babelrc. Can anyone tell me what could be causing this problem? Here's the repo for reproduction: https://github.com/blogrocks/treeshaking-issue.git A: My problem finally got resolved. I should have specified "cross-env NODE_ENV=production" when running webpack. And it's not even sufficient to use DefinePlugin to set NODE_ENV to "production" in plugins. It seems babel-loader keys off the "NODE_ENV=production" from the command. Oh, I finally find that it is react-hot-loader that is keying off NODE_ENV=production from the command!!
[ "ru.stackoverflow", "0000577049.txt" ]
Q: Конфликт фрагмента и активити Пытаюсь во фрагменте написать следующее: recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); Ошибка предсказуема, так как подобное я прописываю во фрагменте, а не в активити - cannot be applied, но решение данной проблемы не нахожу. A: Не совсем понятно из описания в чем именно проблема... Но ты можешь попробовать так: recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
[ "math.stackexchange", "0003446056.txt" ]
Q: Finding a Non-Primitive Root Mod N Given a large random (prime or composite) N, how do I find $a$ (non-trivial: $a\neq1$ and $a\neq{N-1}$) and $b<N/2$ such that $a^b=1 \bmod N$ as quickly as possible? I'm guessing I need to factor N to get the totient, but hoping there is some faster trick. For example, what $a$ and $b$ work for the following $N$? 535681323635377947803477563729034842741283197685482147845846116229490072327829772255980786581056231891824965196685872407087235634574765922267452145891219949840333521605137458047897130486331989436075480864422748548516493270268959879090425463 A: While you are struggling with giving an example, let me mention that it is in general not easy to find the order of an element $a$ modulo $N$. Think about the case when $N = pq$ is a product of two different prime numbers. If you pick a random number $a$ modulo $N$, then there is a significant probability that $a$ is in fact a primitive root modulo both $p$ and $q$. Thus knowing the order of $a$ modulo $N$ will likely let you know $\phi(N)$, and that again implies that you know the factorization of $N$. Therefore a factorization of $N$ seems unavoidable to me. Of course, once $N$ is factorized, you know everything and the task becomes trivial.
[ "stackoverflow", "0032165947.txt" ]
Q: How to make ctrlp search only ~/Documents directory? ctrlp searches my home directory. Is there a line I can put in my vimrc so that ctrlp only searches my ~/Documents directory by default? A: This in my vimrc did the trick: " set cwd so Ctrl-P starts searches from Documents when Vim opens cd /home/user_name/Documents/
[ "stackoverflow", "0008356551.txt" ]
Q: Unix command to find the number of debug statements in a source code How do i find the count of the number of debug statements that is without an if checking? This is an example of a debug statement that has an if checking: if(log.isDebug()){ log.debug("This is a debug statement"); } This is an example of a standalone debug statement that does not have if checking: log.debug("This is a debug statement"); For example, to find the number of debug statements, i would use this command: grep -ir "debug" * | wc -l A: grep -ir "debug" * | grep -v "if" | wc -l
[ "stackoverflow", "0002043672.txt" ]
Q: Access 2000 - Erase Multiple Forms? Anyway to Erase multiple forms, queries, etc in Access 2000? (In the designer that is). A: This worked better for me. Trying to remove the elements in the loop itself kept having trouble. I just slapped the object names into an array, then deleted them afterward. Public Sub DeleteAllFormsAndReports() Dim accobj As AccessObject Dim X As Integer Dim iObjCount As Integer Dim sObjectNames() As String If MsgBox("Are you sure you want to delete all of the forms and reports?", vbCritical + vbYesNo) = vbYes Then ReDim sObjectNames(0) For Each accobj In CurrentProject.AllForms ReDim Preserve sObjectNames(UBound(sObjectNames) + 1) sObjectNames(UBound(sObjectNames)) = accobj.Name Next accobj For X = 1 To UBound(sObjectNames) DoCmd.DeleteObject acForm, sObjectNames(X) Next X ReDim sObjectNames(0) For Each accobj In CurrentProject.AllReports ReDim Preserve sObjectNames(UBound(sObjectNames) + 1) sObjectNames(UBound(sObjectNames)) = accobj.Name Next accobj For X = 1 To UBound(sObjectNames) DoCmd.DeleteObject acReport, sObjectNames(X) Next X End If End Sub
[ "ru.stackoverflow", "0001077133.txt" ]
Q: Сохранение информации в приложении после закрытия pyqt5 У меня есть маленькое приложение, как набросок с помощью которого хочу сделать уже нормальное. Столкнулся с проблемой, в приложении можно получать бонусные пункты на баланс каждые 5 секунд. Но после закрытия и повторного открытия приложения все сбрасывается, баланс и время до получения бонуса. Как можно сделать так чтоб все это сохранялось? Я узнал что что-то надо сравнивать но как именно и как это делать так и не понял. main1.py: import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.Qt import * import random class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(515, 588) font = QtGui.QFont() font.setFamily("Arial") MainWindow.setFont(font) MainWindow.setStyleSheet("background-color: rgb(75, 75, 75);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 440, 521, 21)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(13) self.label.setFont(font) self.label.setStyleSheet("color: rgb(255, 255, 255);") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(0, 490, 521, 61)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(60) self.label_2.setFont(font) self.label_2.setStyleSheet("color: rgb(255, 255, 255);") self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(10, 0, 221, 31)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.label_3.setFont(font) self.label_3.setStyleSheet("color: rgb(255, 255, 255);") self.label_3.setObjectName("label_3") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(10, 30, 171, 41)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(15) self.pushButton.setFont(font) self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;\n" "border-color: rgb(161, 161, 161);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(10, 150, 151, 41)) self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(180, 150, 151, 41)) self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(350, 150, 151, 41)) self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_4.setObjectName("pushButton_4") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "...")) self.label.setText(_translate("MainWindow", "Ваши пункты:")) self.label_2.setText(_translate("MainWindow", "0")) self.label_3.setText(_translate("MainWindow", "Не хватает пунктов?")) self.pushButton.setText(_translate("MainWindow", "КЛИКАЙ")) self.pushButton_2.setText(_translate("MainWindow", "ВОПРОС №1 100 ПУНКТОВ")) self.pushButton_3.setText(_translate("MainWindow", "ВОПРОС №2 100 ПУНКТОВ")) self.pushButton_4.setText(_translate("MainWindow", "ВОПРОС №3 100 ПУНКТОВ")) class Ui_MainWindow_PointApp(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(520, 588) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(140, 400, 251, 61)) self.pushButton.setObjectName("pushButton") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 30, 521, 81)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(29) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "Получить пункты")) self.label.setText(_translate("MainWindow", "Бесплатные пункты")) class PointApp(QtWidgets.QMainWindow, Ui_MainWindow_PointApp): def __init__(self, parent): super().__init__() self.setupUi(self) self.parent = parent self.pushButton.clicked.connect(self.onClicked) self.start = QPoint(0, 0) self.pressing = False self.bonus_point = 0 self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.updtTime) self.testTimeDisplay = QtWidgets.QLCDNumber(self) self.testTimeDisplay.setFixedSize(0.1, 0.1) self.testTimeDisplay.setSegmentStyle(QtWidgets.QLCDNumber.Filled) self.testTimeDisplay.setDigitCount(8) self.dt = QtCore.QDateTime.currentDateTime().addDays(1) self.fl = True self.sec = ... self.updtTime() self.timer.start(1000) def onClicked(self): if self.fl: self.bonus_point = random.uniform(1, 10.5) self.BonusGet() self.dt = QtCore.QDateTime.currentDateTime().addSecs(1*6 ) self.fl = False self.sec = 0 else: self.flashSplash() def updtTime(self): currentTime = QtCore.QDateTime.currentDateTime().toString('hh:mm:ss') self.testTimeDisplay.display(currentTime) self.sec = QtCore.QDateTime.currentDateTime().secsTo(self.dt) if self.sec <= 0: self.fl = True def flashSplash(self): self.splash = QtWidgets.QSplashScreen(QtGui.QPixmap('rry.png').scaled(382, 72, QtCore.Qt.KeepAspectRatio)) self.splash.move(755, 680) self.splash.show() self.splash.showMessage( '<h2 style="color:white; font: Arial">Кнопка будет доступна через {} секунд</h2>'.format(self.sec), QtCore.Qt.AlignCenter, QtCore.Qt.white) QtCore.QTimer.singleShot(2200, self.splash.close) def BonusGet(self): self.splash = QtWidgets.QSplashScreen(QtGui.QPixmap('ggt.png').scaled(382, 72, QtCore.Qt.KeepAspectRatio)) self.splash.move(755, 680) # width() self.splash.show() self.splash.showMessage( '<h2 style="color:white; font: Arial">Вы получили {:.2f} пунктов</h2>'.format(self.bonus_point), QtCore.Qt.AlignCenter, QtCore.Qt.white) QtCore.QTimer.singleShot(2200, self.splash.close) self.parent.label_2.setText( str(round(float(self.parent.label_2.text()) + self.bonus_point, 2))) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(515, 588) font = QtGui.QFont() font.setFamily("Arial") MainWindow.setFont(font) MainWindow.setStyleSheet("background-color: rgb(75, 75, 75);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 440, 521, 21)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(13) self.label.setFont(font) self.label.setStyleSheet("color: rgb(255, 255, 255);") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(0, 490, 521, 61)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(60) self.label_2.setFont(font) self.label_2.setStyleSheet("color: rgb(255, 255, 255);") self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(10, 0, 221, 31)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.label_3.setFont(font) self.label_3.setStyleSheet("color: rgb(255, 255, 255);") self.label_3.setObjectName("label_3") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(10, 30, 171, 41)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(15) self.pushButton.setFont(font) self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;\n" "border-color: rgb(161, 161, 161);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(10, 150, 151, 41)) self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(180, 150, 151, 41)) self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(350, 150, 151, 41)) self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_4.setObjectName("pushButton_4") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "...")) self.label.setText(_translate("MainWindow", "Ваши пункты:")) self.label_2.setText(_translate("MainWindow", "0")) self.label_3.setText(_translate("MainWindow", "Не хватает пунктов?")) self.pushButton.setText(_translate("MainWindow", "КЛИКАЙ")) self.pushButton_2.setText(_translate("MainWindow", "ВОПРОС №1 100 ПУНКТОВ")) self.pushButton_3.setText(_translate("MainWindow", "ВОПРОС №2 200 ПУНКТОВ")) self.pushButton_4.setText(_translate("MainWindow", "ВОПРОС №3 300 ПУНКТОВ")) class MainApp(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.pushButton.clicked.connect(self.onClicked1) self.exampleApp_2 = PointApp(self) def onClicked1(self): self.exampleApp_2.show() def actionClicked(self): action = self.sender() print(action.text()) print(action.data()) if __name__=="__main__": app = QtWidgets.QApplication(sys.argv) window = MainApp() window.show() sys.exit(app.exec_()) A: Вам просто нужен файлик, например bonus.ini, где вы будете сохранять бонусы. import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.Qt import * import random import os.path # +++ class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(515, 588) font = QtGui.QFont() font.setFamily("Arial") MainWindow.setFont(font) MainWindow.setStyleSheet("background-color: rgb(75, 75, 75);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 440, 521, 21)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(13) self.label.setFont(font) self.label.setStyleSheet("color: rgb(255, 255, 255);") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(0, 490, 521, 61)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(60) self.label_2.setFont(font) self.label_2.setStyleSheet("color: rgb(255, 255, 255);") self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(10, 0, 221, 31)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.label_3.setFont(font) self.label_3.setStyleSheet("color: rgb(255, 255, 255);") self.label_3.setObjectName("label_3") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(10, 30, 171, 41)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(15) self.pushButton.setFont(font) self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;\n" "border-color: rgb(161, 161, 161);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(10, 150, 151, 41)) self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(180, 150, 151, 41)) self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(350, 150, 151, 41)) self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_4.setObjectName("pushButton_4") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "...")) self.label.setText(_translate("MainWindow", "Ваши пункты:")) self.label_2.setText(_translate("MainWindow", "0")) self.label_3.setText(_translate("MainWindow", "Не хватает пунктов?")) self.pushButton.setText(_translate("MainWindow", "КЛИКАЙ")) self.pushButton_2.setText(_translate("MainWindow", "ВОПРОС №1 100 ПУНКТОВ")) self.pushButton_3.setText(_translate("MainWindow", "ВОПРОС №2 100 ПУНКТОВ")) self.pushButton_4.setText(_translate("MainWindow", "ВОПРОС №3 100 ПУНКТОВ")) class Ui_MainWindow_PointApp(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(520, 588) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(140, 400, 251, 61)) self.pushButton.setObjectName("pushButton") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 30, 521, 81)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(29) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "Получить пункты")) self.label.setText(_translate("MainWindow", "Бесплатные пункты")) class PointApp(QtWidgets.QMainWindow, Ui_MainWindow_PointApp): def __init__(self, parent): super().__init__() self.setupUi(self) self.parent = parent self.pushButton.clicked.connect(self.onClicked) self.start = QPoint(0, 0) self.pressing = False self.bonus_point = 0 self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.updtTime) self.testTimeDisplay = QtWidgets.QLCDNumber(self) self.testTimeDisplay.setFixedSize(0.1, 0.1) self.testTimeDisplay.setSegmentStyle(QtWidgets.QLCDNumber.Filled) self.testTimeDisplay.setDigitCount(8) self.dt = QtCore.QDateTime.currentDateTime().addDays(1) self.fl = True self.sec = ... self.updtTime() self.timer.start(1000) def onClicked(self): if self.fl: self.bonus_point = random.uniform(1, 10.5) self.BonusGet() self.dt = QtCore.QDateTime.currentDateTime().addSecs(1*6 ) self.fl = False self.sec = 0 else: self.flashSplash() def updtTime(self): currentTime = QtCore.QDateTime.currentDateTime().toString('hh:mm:ss') self.testTimeDisplay.display(currentTime) self.sec = QtCore.QDateTime.currentDateTime().secsTo(self.dt) if self.sec <= 0: self.fl = True def flashSplash(self): self.splash = QtWidgets.QSplashScreen(QtGui.QPixmap('rry.png').scaled(382, 72, QtCore.Qt.KeepAspectRatio)) self.splash.move(755, 680) self.splash.show() self.splash.showMessage( '<h2 style="color:white; font: Arial">Кнопка будет доступна через {} секунд</h2>'.format(self.sec), QtCore.Qt.AlignCenter, QtCore.Qt.white) QtCore.QTimer.singleShot(2200, self.splash.close) def BonusGet(self): self.splash = QtWidgets.QSplashScreen(QtGui.QPixmap('ggt.png').scaled(382, 72, QtCore.Qt.KeepAspectRatio)) self.splash.move(755, 680) # width() self.splash.show() self.splash.showMessage( '<h2 style="color:white; font: Arial">Вы получили {:.2f} пунктов</h2>'.format(self.bonus_point), QtCore.Qt.AlignCenter, QtCore.Qt.white) QtCore.QTimer.singleShot(2200, self.splash.close) self.parent.label_2.setText( str(round(float(self.parent.label_2.text()) + self.bonus_point, 2))) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(515, 588) font = QtGui.QFont() font.setFamily("Arial") MainWindow.setFont(font) MainWindow.setStyleSheet("background-color: rgb(75, 75, 75);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 440, 521, 21)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(13) self.label.setFont(font) self.label.setStyleSheet("color: rgb(255, 255, 255);") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(0, 490, 521, 61)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(60) self.label_2.setFont(font) self.label_2.setStyleSheet("color: rgb(255, 255, 255);") self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(10, 0, 221, 31)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.label_3.setFont(font) self.label_3.setStyleSheet("color: rgb(255, 255, 255);") self.label_3.setObjectName("label_3") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(10, 30, 171, 41)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(15) self.pushButton.setFont(font) self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;\n" "border-color: rgb(161, 161, 161);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(10, 150, 151, 41)) self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(180, 150, 151, 41)) self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(350, 150, 151, 41)) self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-radius: 10px;") self.pushButton_4.setObjectName("pushButton_4") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "...")) self.label.setText(_translate("MainWindow", "Ваши пункты:")) self.label_2.setText(_translate("MainWindow", "0")) self.label_3.setText(_translate("MainWindow", "Не хватает пунктов?")) self.pushButton.setText(_translate("MainWindow", "КЛИКАЙ")) self.pushButton_2.setText(_translate("MainWindow", "ВОПРОС №1 100 ПУНКТОВ")) self.pushButton_3.setText(_translate("MainWindow", "ВОПРОС №2 200 ПУНКТОВ")) self.pushButton_4.setText(_translate("MainWindow", "ВОПРОС №3 300 ПУНКТОВ")) class MainApp(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) # +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv if os.path.exists('bonus.ini'): with open('bonus.ini', 'r') as f: self.bonus = f.read() else: with open('bonus.ini', 'w') as f: self.bonus = '0' # +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ self.pushButton.clicked.connect(self.onClicked1) self.exampleApp_2 = PointApp(self) self.label_2.setText(self.bonus) # +++ self.label_2.setGeometry(QtCore.QRect(0, 490, 521, 61)) # +++ def onClicked1(self): self.exampleApp_2.show() def actionClicked(self): action = self.sender() print(action.text()) print(action.data()) def closeEvent(self, event): # +++ with open('bonus.ini', 'w') as f: self.bonus = f.write(self.label_2.text()) if __name__=="__main__": app = QtWidgets.QApplication(sys.argv) window = MainApp() window.show() sys.exit(app.exec_())
[ "stackoverflow", "0003936558.txt" ]
Q: What's the difference between these two java variable declarations? public class SomeClass { private HashSet<SomeObject> contents = new HashSet<SomeObject>(); private Set<SomeObject> contents2 = new HashSet<SomeObject>(); } What's the difference? In the end they are both a HashSet isn't it? The second one looks just wrong to me, but I have seen it frequently used, accepted and working. A: Set is an interface, and HashSet is a class that implements the Set interface. Declaring the variable as type HashSet means that no other implementation of Set may be used. You may want this if you need specific functionality of HashSet. If you do not need any specific functionality from HashSet, it is better to declare the variable as type Set. This leaves the exact implementation open to change later. You may find that for the data you are using, a different implementation works better. By using the interface, you can make this change later if needed. You can see more details here: When should I use an interface in java? A: Set is a collection interface that HashSet implements. The second option is usually the ideal choice as it's more generic. A: Since the HashSet class implements the Set interface, its legal to assign a HashSet to a Set variable. You could not go the other way however (assign a Set to a more specific HashSet variable).
[ "math.stackexchange", "0000185169.txt" ]
Q: Proving: $x\left ( 1-y \right )+y\left ( 1-z \right )+z\left ( 1-x \right )< 1$ What is the proof that: $x\left ( 1-y \right )+y\left ( 1-z \right )+z\left ( 1-x \right )< 1$ if: $0< x;y;z< 1$ A: Look at the cubic polynomial $P(t)$, where $$P(t)=t^3-(x+y+z)t^2+(xy+yz+zx)t-xyz.$$ This has as its roots $x$, $y$, and $z$. These are all less than $1$, so $P$ is positive at $1$ (and beyond). Now you can get the required result from $$P(1)=1-(x+y+z)+(xy+yz+zx)-xyz \gt 0.$$
[ "stackoverflow", "0034738765.txt" ]
Q: Redis: set maximum number of elements of a set In redis, is it possible to set a maximum number of elements to a set so when one use the sadd, the redis server prevents the set from having more elements that a maximum amount? e.g. something like : 127.0.0.1:6379> SETSIZE KEY 100 Thanks in advance. A: No, it`s not possible with usual commands but possible with LUA scripting: local size = redis.call('SCARD', KEYS[1]); if size < tonumber(ARGV[1], 10) then return redis.call('SADD', KEYS[1], ARGV[2]); end return -1;
[ "stackoverflow", "0058013947.txt" ]
Q: Array to String Conversion Error while inserting data in db I am using Vue multiselect. I want to save id of selected options in db but unfortunately i'm getting error of Array to string conversion. I put both site_id and administrator in fillables.I am getting Array of selected options at controller side but i think issue is in insert method which is throwing error. Hope you understand my question. Html: <form @submit.prevent="addAllocateSites"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label class="typo__label">Select Site</label> <multiselect v-model="form.selected_sites" :options="options" :multiple="true" :close-on-select="false" :clear-on-select="false" :preserve-search="true" placeholder="Pick Site" name = "selected_sites" label="asset_name" track-by="asset_name" :class="{ 'is-invalid': form.errors.has('selected_sites') }"> <template slot="selection" slot-scope="{ values, search, isOpen }"><span class="multiselect__single" v-if="values.length &amp;&amp; !isOpen">{{ values.length }} Sites selected</span> </template> </multiselect> <pre class="language-json"><code>{{form.selected_sites}}</code></pre> </div> <has-error :form="form" field="selected_sites"></has-error> <button type="submit" class="btn btn-primary">Save</button> </div> </div> <br> </form> Script: <script> import Multiselect from 'vue-multiselect'; import Form from 'vform'; export default { components: { Multiselect }, data() { return { form: new Form({ selected_sites: [], }), options: [] } }, methods: { getSites() { axios.get('api/sites').then(data => { this.options = data.data; console.log(data.data) }, function (data) { console.log(data) }); }, addAllocateSites(){ this.form.post('api/allocate_sites').then(() => { toast.fire({ type: 'success', title: 'Sites Allocated Successfully' }); }); } }, mounted() { this.getSites(); console.log('Component mounted.') } } </script> Controller: public function store(Request $request) { $siteIds = $request->input('selected_sites'); // dd($siteIds); $validation = Validator::make($request->all(), [ 'selected_sites' => 'required|array', ]); if ($validation->fails()) { return ['Fields required']; } else { for ($i = 1; $i < count($siteIds); $i++) { $sites[] = [ "site_id" => $siteIds[$i], "administrator_id" => Auth::user()->id, ]; } $insertData = AllocateSites::insert($sites); if ($insertData) { return ['Sites Allocated']; } else { return ['Failed to add data']; } } } A: I got the solution for ($i = 0; $i < count($siteIds); $i++) { $sites[] = [ "site_id" => $siteIds[$i]['id'], "administrator_id" => Auth::user()->id, ]; }
[ "travel.stackexchange", "0000112273.txt" ]
Q: Do I need to trigger my ESTA? I'm a UK citizen. I hope I can explain correctly. If I go to Mexico for six months, then go into US, I understand if I go across the border by land it won't trigger the US ESTA. I'd then travel across to North Carolina. That's a long way by land for a female on her own and it isn't my best choice. If I took a domestic flight, would it trigger the ESTA? I wouldn't be going through customs. The reason I don't want to trigger the ESTA is then I only have 90 days. I don't want to stay illegally as I go see my family a lot in America so don't want a "no entry" for ten years. Once the ESTA is triggered even if I go back to my English brother in Mexico it's still included in the US ESTA as if entry is made in the US--Mexico and Canada are classed as North America. But if my first port of entry is actually in Mexico then the US ESTA isn't triggered if that makes sense. So after that long ramble I'm asking does anyone know if as a foreigner would taking a domestic flight trigger the visa. A: You are confused about VWP and ESTA are and how they work. As a VWP-country national, you can visit the US on the Visa Waiver Program (VWP), and you will be admitted for 90 days at entry. That's 90 days starting with, and including, the day you entered. It doesn't matter how you enter the US, by land, sea, or air; the conditions of VWP are the same. Leaving the US and re-entering on VWP will generally not get you a new 90-day admission period if you only go to Canada, Mexico, or the Caribbean islands. ESTA is a travel authorization, valid for 2 years, to allow you to board a plane or boat if you wish to enter the US on VWP by air or sea, but not needed if you travel by land. Whether you have an ESTA or not (if you enter by land) doesn't affect the conditions of VWP, including the 90-day admission period. A: Much of the confusion here seems to be related to your status in Mexico rather than your status in the US. For example, you wrote in a comment Once the American 90 days have started I can't go back to mexico for another 180 days. Actually, you can. Mexico does not care about your US status under the VWP, and Mexico allows you in for however long it allows you in regardless of whether you've recently been in the US or are coming from the US. What you can't do is get back into the United States after doing that. And actually, as we'll see in a bit, you might even be able to do that. going to mexico from US comes under the same visa as me coming to just the US. Only as far as the US is concerned. That is, your time in Mexico counts against your authorized period of stay in the US. But Mexico doesn't care about that in the least. They will authorize you to stay in Mexico independently of your VWP stay in the US. The rule we're struggling with here is designed to prevent people from doing visa runs from the US into Canada, Mexico, or an "adjacent island." The US does not want you to spend 90 days in the US, pop over the border for a couple of days, and then return to the US for another 90 days. But you seem to want to do the opposite. The rule has an exception for people who actually reside in one of those places, but the rule is also worded in such a way that border officers have discretion to invoke the rule or not: An alien admitted to the United States under this part may be readmitted to the United States after a departure to foreign contiguous territory or adjacent island for the balance of his or her original Visa Waiver Pilot Program admission period if he or she is otherwise admissible and meets all the conditions of this part with the exception of arrival on a signatory carrier. Source: 8 CFR 217.3(b). So if you try to reenter the US more than 90 days after your first entry, the rule does not apply to you. Suppose you spent a week in the US, go to Mexico, and then come back the day before your original 90-day period ends asking to stay for another week. The officer "may" readmit you for one day, but may also decide to give you a new 90-day period. Now, because this rule is designed to prevent border runs, and it concerns only Mexico, Canada, and "adjacent islands," you might wonder what would happen if you spent 90 days in the US, then went to Costa Rica for a couple of days, and then came back to the US. In fact, you would be likely to be refused entry anyway, because the immigration officer has discretion to do that. Even though you went to Costa Rica, you would nonetheless appear to be abusing the VWP. Now, to your specific comments: Now I have a large chunk of money. I want to go to mexico for a year or how ever long the money lasts. Plenty of people do it. Instead of strategizing visa runs, you might want to consider a temporary resident visa, with which you can get a resident card: This is a single entry Visa and will allow the applicants to enter to the country to exchange it for a Temporary Resident Card within 30 days upon their arrival at the nearest migration office (INM). The temporary resident card will be valid for one year and multiple entries. You also wrote: Once the American 90 days have started I can't go back to mexico for another 180 days. As noted above, this isn't true. What you can't do is go back to the US during the initial 90-day period and stay past the end of the initial 90-day period. But if you just want to stay in Mexico without going back to the US, or indeed visit any country other than the US and return to Mexico, that's perfectly fine. Now I've read a few posts that if you go out by land it's a different visa and the 90 days arnt triggered. Because I'm not going through customs? Those posts are almost certainly mistaken. When you enter the US by land, you do not need ESTA, but you would still be entering under the Visa Waiver Program. If you follow the US news at all, you will be well aware that there are very stringent immigration controls for people crossing into the US from Mexico by land; there's no way you can do that legally without being inspected by an immigration officer. In closing, let me assume that your goal is to spend roughly a year in Mexico with a visa run that includes visiting your family in North Carolina. In that case, you have two options: 1) Get a Mexican temporary resident visa. If you do that, your return to Mexico will reset the 90-day clock on the US visa waiver. For more information about that, you should ask at Expatriates. 2) Do the visa run to the US and then stay out of the US for the next 90 days. This assumes that Mexico won't take exception to your second 180-day entry coming so closely after your first; I do not know whether that assumption is at all reasonable because I have no experience with nor much knowledge of Mexican immigration practices. A: The ESTA isn't a visa. It's just an electronic document that pre-clears you, in a sense, to be admitted to the US - a heads-up, if you will. It's only required on flights and ship voyages (except ferries between Canada and the US in B.C./Washington). You still are subject to the terms of the Visa Waiver Program, and an I-94 visitor record is still required, so entering the US by land, sea or air doesn't change how long you can stay.
[ "stackoverflow", "0033602257.txt" ]
Q: How to listen an MailItem event in Mail Add-in? I want to detect an event in Mail Add-in. In Outlook, thick/desktop version, we can detect the mail event, such as MailItem.Send and MailItem.AttachmentAdd. Is it possible to listen to these events in Outlook online? A: Unfortunately there are almost no events of any kind in the Mailbox API, other than asynchronous callbacks that are only fired when you initiate them. There is nothing that I'm aware of that can be used to detect item send or attachment modification events. The closest option is to use the Outlook Notifications REST API (https://msdn.microsoft.com/office/office365/APi/notify-rest-operations), but these are more suitable to monitoring item/folder level changes. Perhaps you can hook into a notification for the Sent Items folder to approximate a MailItem.Send operation, or watch changes to a draft item to detect a newly added attachment.
[ "gaming.stackexchange", "0000148269.txt" ]
Q: how safe is HBC on Wii-U? I had a question about installing home-brew on the Wii U. I heard it's safe(within reason), but some games say that they will deactivate if unauthorized software is installed. if I install HBC will that make Mario Bros, etc permanently stop working? also after installing is there a way to remove all traces of it or will it always leave a stub in the memory? A: It's as safe as any other unauthorized software; user beware. There are no guarantees for perfect safety, nor unlimited usage. It can even brick your system if you do it wrong. Official updates may remove your homebrew or other software, or even brick your system, and you won't have any recourse, since installing unofficial software invalidates your warranty. Anything you do is solely your responsibility. That said, I have yet to find any sort of bricked Wii whatsoever; the process is pretty painless, and effort has been invested to ensure only stubs are replaced with the custom software. Usually, that same software can bypass the official Wii launcher, so you don't even need to update the system to play them. But take that with a grain of salt, because it's always a cat and mouse game between the console manufacturers and the homebrew scene. Just because it works now does not guarantee it's future functionality or that it will work the same as it does now. In the homebrew scene, there are no safety nets or guarantees. Use at your own risk.
[ "stackoverflow", "0005293211.txt" ]
Q: Determining if a day of the week lies in between two others in an NSMutableArray? If I have an array that holds various days of the week (i.e. @"Fri, Mar 11, 2011", @"Wed, Mar 9, 2011", @"Tue, Mar 8, 2011", @"Mon, Mar 7, 2011") and this array is constantly changing because users are adding/removing days from the array, and let's say that I create some variable NSString *myDay = @"Thu, Mar 10, 2011"; how can I programatically determine that specifically between the first and second elements in the array (i.e. in this case @"Fri, Mar 11, 2011" and @"Wed, Mar 9, 2011") that myDay(i.e. @"Thu, Mar 10, 2011") does not lies in between them (or does in other cases)? Note: In this array there can be multiple entries for a specific day of the week (i.e Thursday), it will just be part of a different week. A: If I understand your question right, you're only looking to deal with the contents of the array, not with the true concept of what days are between other days. In that case, you can use a couple calls to indexOfObject:, then compare, to see whether your object is between them. For example: - (BOOL)array:(NSArray *)arr hasObject:(id)obj between:(id)a and:(id)b { NSUInteger startIdx = [arr indexOfObject:a]; NSUInteger endIdx = [arr indexOfObject:b]; NSUInteger targetIdx = [arr indexOfObject:obj]; if(startIdx != NSNotFound && endIdx != NSNotFound && targetIdx != NSNotFound && startIdx <= targetIdx && targetIdx <= endIdx) { return YES; } else { return NO; } } NSArray * days = [NSArray arrayWithObjects:@"Mon", @"Wed", @"Fri", @"Sat", nil]; [self array:days hasObject:@"Wed" between:@"Mon" and:@"Fri"]; // YES [self array:days hasObject:@"Wed" between:@"Wed" and:@"Wed"]; // YES [self array:days hasObject:@"Sat" between:@"Mon" and:@"Fri"]; // NO [self array:days hasObject:@"Thu" between:@"Mon" and:@"Fri"]; // NO [self array:days hasObject:@"Wed" between:@"Fri" and:@"Mon"]; // NO In this example, we don't care about what the objects actually represent (days of the week), so even though Thursday is between Monday and Friday, the method returns NO because Thursday doesn't exist in the array. The second example call is also an interesting case - you can easily modify the method to use strict inequality when comparing, so that an object is not "between" two others if it matches one (or both) of the others.
[ "stackoverflow", "0052316715.txt" ]
Q: mysql ordering question using date and status field Need ideas on the most efficient way to order some items/events based on date and by status. Currently I have the following query. select tevent.ID, tevent.ename, e_dates.edate, tevent.status, tevent.eactive from tevent LEFT JOIN e_dates on tevent.ID=e_dates.EID) Where tevent.status <> 'delete' and tevent.eactive ='Y' group by tevent.id order by (case when tevent.status = 'closed' and e_dates.edate >= curdate() then 0 else 1 end), edates.edate desc I used a case but it ordered the status, then by date, which confuses people. Below is the output +----+--------------+-----+-----------+ | ID |Edate | Ename | Status | +----+--------------+-----+-----------+ | 2 | 2018-09-21 | Event2 | Closed | | 5 | 2018-09-15 | Event5 | Closed | | 3 | 2018-12-12 | Event3 | Open | | 6 | 2018-10-25 | Event6 | Approved| | 4 | 2018-10-25 | Event4 | Open | | 7 | 2018-10-15 | Event7 | Pending | | 10 | 2018-10-01 | Event10 | Open | | 1 | 2018-09-30 | Event1 | Open | | 4 | 2018-09-30 | Event4 | Open | | 8 | 2018-09-01 | Event8 | Closed | | 11 | 2018-08-25 | Event11 | Closed | +----+--------------+-----+-----------+ EDITED: What I'm trying to accomplish is to list the closed events in which the event date is before the date of the event stay on top. IE (ID 2 and ID 5) But want the event status that are OPEN, APPROVED, PENDING be listed in chronological order by ASC. and closed event in which the event date (edate) is after the current date (now()) listed at the bottom For example: +----+--------------+-----+-----------+ | ID |Edate | Ename | Status | +----+--------------+-----+-----------+ | 2 | 2018-09-21 | Event2 | Closed | | 5 | 2018-09-15 | Event5 | Closed | | 1 | 2018-09-30 | Event1 | Open |* | 4 | 2018-09-30 | Event4 | Open |* | 10 | 2018-10-01 | Event10 | Open |* | 7 | 2018-10-15 | Event7 | Pending |* | 4 | 2018-10-25 | Event4 | Open |* | 6 | 2018-10-25 | Event6 | Approved|* | 3 | 2018-12-12 | Event3 | Open |* | 11 | 2018-08-25 | Event11 | Closed | | 8 | 2018-09-01 | Event8 | Closed | +----+--------------+-----+-----------+ A: I think you were almost right. You need three options in your case statement - 0 for all the closed ones at the top, 2 for all the closed ones at the bottom, and 1 for everything else in the middle. Then remove the desc on the date to get the date to be ascending inside each section, so your order by clause should look like order by ( case when tevent.status = 'closed' and e_dates.edate >= curdate() then 0 when tevent.status = 'closed' and e_dates.edate < curdate() then 2 else 1 end ), edates.edate Or you could write this same thing as order by ( case when tevent.status = 'closed' then case when e_dates.edate >= curdate() then 0 else 2 end else 1 end ), edates.edate
[ "stackoverflow", "0013729856.txt" ]
Q: Is there a way to "auto-name" expression in J I have a few questions/suggestions concerning data.table. R) X = data.table(x=c("q","q","q","w","w","e"),y=1:6,z=10:15) R) X[,list(sum(y)),by=list(x)] x V1 1: q 6 2: w 9 3: e 6 I think it is too bad that one has to write R) X[,list(y=sum(y)),by=list(x)] x y 1: q 6 2: w 9 3: e 6 It should default to keeping the same column name (ie: y) where the function calls only one column, this would be a massive gain in most of the cases, typically in finance as we usually look as weighted sums or last time or... => Is there any variable I can set to default to this behaviour ? When doing a selectI might want to do a calculus on few columns and apply another operation for all other columns. I mean too bad that when I want this: R) X = data.table(x=c("q","q","q","w","w","e"),y=1:6,z=10:15,t=20:25,u=30:35) R) X x y z t u 1: q 1 10 20 30 2: q 2 11 21 31 3: q 3 12 22 32 4: w 4 13 23 33 5: w 5 14 24 34 6: e 6 15 25 35 R) X[,list(y=sum(y),z=last(z),t=last(t),u=last(u)),by=list(x)] #LOOOOOOOOOOONGGGG #EXPR x y z t u 1: q 6 12 22 32 2: w 9 14 24 34 3: e 6 15 25 35 I cannot write it like... R) X[,list(sum(y)),by=list(x),defaultFn=last] #defaultFn would be applied to all remaniing columns => Can I do this somehow (may be setting an option)? Thanks A: On part 1, that's not a bad idea. We already do that for expressions in by, and something close is already on the list for j : FR#2286 Inferred naming could apply to j=colname[...] Find max per group and return another column But if we did do that it would probably need to be turned on via an option, to maintain backwards compatibility. I've added a link in that FR back to this question. On the 2nd part how about : X[,c(y=sum(y),lapply(.SD,last)[-1]),by=x] x y z t u 1: q 6 12 22 32 2: w 9 14 24 34 3: e 6 15 25 35 Please ask multiple questions separately, though. Each question on S.O. is supposed to be a single question.
[ "askubuntu", "0000388715.txt" ]
Q: Header files in Anjuta What is used instead of header in anjuta for a simple C program to give an output? I am new to programming and only used turbo c previously. Thanks in advance. A: you should use stdio.h, not conio.h. conio.h is specific to consoles, while stdio is standard input/ouput. If all you are doing is character fetching, you will find getc() etc in stdio.h.
[ "stackoverflow", "0005634793.txt" ]
Q: to validate checkbox input for table using multiple rows i using js to add multiple row in a particular table, but when submit the form all check box having the same value, so how can i validate this checkbox using js before submit so change value to if unchecked, i trying on that but got no solution, does any one this before, thanks in advance A: finally i found solution for my problem, thanks 'vindia' for the clue, i add checkbox with array, sol as below in html `<input id="abc[]" name="abc[]" type="checkbox" value="1">` in js for(var i=0;i<chkDefaultLength;i++){ if(!document.neworupdateevent["chkDefault[]"][i].checked){ document.neworupdateevent["chkDefault[]"][i].value=0; } }