text
stringlengths
64
89.7k
meta
dict
Q: "Human Knot" solvability probability Somewhat surprisingly, I don't see a question about this. There is a team-building (or just fun mathematical) game where a group of people hold hands with each other, usually trying not to hold hands with someone right next to you. The goal is then to "untangle the human knot" thus formed. Folk wisdom says this can always be "solved", in the sense of twisting and moving to demonstrate the knot formed is just one unknot, but this isn't so, since you can form all sorts of knots. Probably forming a simple non-trivial link of circles would be easiest to demonstrate this. But I am intrigued by a lack of easy-to-find references on the probability of such a configuration being the unknot. There is this MathOverflow question, which however has devolved into whether any link can be formed, which is NOT what I am asking. See also this Reddit thread and this Quora thread. In any event, not only do I feel like probably there is a known answer, it is also not possible to search on this site for questions on MO, so hopefully it is appropriate to ask on MSE this question: Given any reasonable set of definitions of this game and reasonable probability distribution given your definitions, what is the probability that such a link is the unknot, as a function of $n$ players? Presumably this will vary by some assumptions on arm length or the exact rules (can you grasp your neighbor's hand, how are people arranged), so there could be multiple answers. I suppose it's likely the parity of $n$ will be involved as well. As a hint, there is a comment to the MO question suggesting some possible references in somewhat difficult-to-access resources - but I don't care about references per se, I would like answers that are publicly available on a user-friendly and well-indexed site ... such as this one! Update: A review of one of the articles linked to on MO has some useful information about how many loops one can find in the link, though apparently not whether said loops are knotted or (k)not. A: In a somewhat related MathOverflow question, where a closed loop is chosen at random as a polygonal path whose vertices lie on a sphere, there are some thoughts that the average crossing number of such a knot is something like $n^{3/2}$, where $n$ is the number of vertices. This would mean nontrivial knots are reasonably likely as the number of people grows, especially since the maximum crossing number of any such knot is bounded above by $n^2$. Even-Zohar has a paper on models for random knots. The random jump model is sort of like the human knot, but people are allowed to be placed anywhere in a unit sphere. Numerical experiments suggest the probability of encountering an unknot vanishes faster than $\exp(−O(n))$. In that paper, there is a description of a model that is much closer to the human knot game: random grid diagrams. If I understand it correctly, the difference is that the order in which people hold hands matters. Figure 15 has a graph showing the sampled distributions for the Casson invariant $c_2$ (the order-$2$ Vassiliev invariant, the second coefficient of the Alexander-Conway polynomial) of random knots from different models (including the grid model). The value of $c_2$ for the unknot is $0$. If I'm reading the graph correctly, with about eighty people the probability of getting an unknot happens no more than $55\%$ of the time. The actual probability is less since other knots also have $c_2=0$. The paper cites what appears to be a 2007 PhD thesis by Gilad Cohen in which the human knot game is numerically analyzed. However, I cannot find a copy or a reference to it anywhere. In one experimental analysis of the grid diagram model, they find the knotting probability approaches $1$ as $n$ increases. As an example, it looks like the human knot game (conditioned on people always forming a single closed loop) for ten people has nearly a $20\%$ chance of being unable to be detangled, though I can't say for certain since I don't know how well this random model actually maps to the human knot game. Anyway, the short of it is that it appears the answer is unknown right now, but there is numerical evidence to support the conjecture that, as the number of people playing the game increases, winning becomes arbitrarily improbable.
{ "pile_set_name": "StackExchange" }
Q: Nonexistence of an injective $C^1$ map between $\mathbb R^2$ and $\mathbb R$ I am getting bored waiting for the train so I'm thinking whether there can exist a $C^1$ injective map between $\mathbb{R}^2$ and $\mathbb{R}$. It seems to me that the answer is no but I can't find a proof or a counterexample... Can you help me? A: There is no such map. If $f\colon\mathbb R^2\to\mathbb R$ is continuous then its image is connected, that is an interval in $\mathbb R$. Note that this is a non-degenerate interval since the function is injective. However if you remove any point from $\mathbb R^2$ it remains connected, however if we remove a point whose image is in the interior of the interval then the image cannot be still connected if the function is injective.
{ "pile_set_name": "StackExchange" }
Q: What's different in the 3 versions of Kingdom Hearts 2? More of less the same thing i asked here but this time referring to Kingdom Hearts 2 as i have played the PAL Release on PS2 and would like to know the differences between that and Final Mix and what may have been added to that in 2.5 HD Remix A: There are quite a lot of differences between Kingdom Hearts 2 and the Final Remix so I'll just list the major ones: Differences between Kingdom Hearts 2 and Final Remix New difficulty mode (critical mode) English voice acting and Japanese text/subtitles Higher definition textures New mini-game which unlocks special items (puzzle) New heartless colours New cutscenes New weapons New accessories Additional battles Filling the Drive Gauge is easier "Theater Mode" for re-watching cutscenes Secret ending video Bunch of balance changes Kingdom Hearts HD 2.5 ReMIX Includes Kingdom Hearts II Final Mix and Kingdom Hearts Birth by Sleep Final Mix Further improved graphics 3+ hours of high definition cutscenes with Kingdom Hearts Re:coded
{ "pile_set_name": "StackExchange" }
Q: How to add multiple series in highcharts synchronously I tried to add multiple series in highcharts synchronously, but the response time is very slow. It took almost 3-5 seconds to display the charts. Here is part of the code. while(chart.series.length>0){ chart.series[0].remove(true); } chart.addSeries(series1); chart.addSeries(series2); chart.addSeries(series3); chart.addSeries(series4); chart.addSeries(series5); When I remain only one addSeries command, it response immediately, so I realized it may be the problem of add multiple series in highcharts synchronously. Not so good at highcharts, so is there anyone could help me about this? Or maybe there is another way to do this, I am much appreciated. A: addSeries accept redraw as second parameter. So you can call it with it set to false and then the last one as true, which is the default. var series = [ series1, series2, series3, series4 ], i = 0; for( ; i < 4; i++ ) { chart.addSeries( series[i], false ); } chart.addSeries(series5); You can do the same to remove: while( chart.series.length > 1 ){ chart.series[0].remove( false ); } chart.series[0].remove();
{ "pile_set_name": "StackExchange" }
Q: Debugging a Windows CE application which uses a Microsoft Azure service This question has probably less to do with actual programming and more to do with environment setup. I'm developing an application for a Windows CE device, which will use a service hosted in Microsoft Azure. Obviously, this is all under development, and the service itself has not yet been uploaded to Azure. So I'm using the emulators provided by MS to deploy the service locally. Also, I don't think uploading the service to Azure just to debug it is a good idea, as that could net us a bill for Azure we don't yet want to pay. Also, please note, I'm using VS2008 for the Windows CE project and VS2010 for the Azure project (thank you MS for dropping support for mobile devices -_-). The problem is, the service seems to be accessible only via 127.0.0.1 or localhost, and if I physically connect a Windows CE device or use an emulated one, it becomes a new entity on the network, and cannot access that service any more. How can I debug my Window CE application and have it see the service, whilst still being able to debug the service itself? A: OK, I don't know if this was intentional, or if I found one of the mentioned hacks, but I saw that IIS hosts the Azure site I created on port 5100, and the binding for this site is *, so it accepts all connections. Using this I could access the service from my emulator, and I could still debug all Azure related stuff.
{ "pile_set_name": "StackExchange" }
Q: Django settings -- could not import unipath I could not figure out what I'm doing wrong. Could you please help me? I have the following directory structure: project-repository \-- my-project \--manage.py \--my-project \--__init__.py \--urls.py \--wsgi.py \--settings \--__init__.py \--local.py \--base.py In the local.py I import base.py. In base.py I have from unipath import Path. When I try to run django-admin shell --settings=my-project.settings.local it shows me an error: Error: Could not import settings 'my-project.settings.local' (Is it on sys.path?): No module named unipath When I do pip freeze it shows me: Unipath==0.2.1 and I can easily import it in python console. Also I have project-repository and my-project on PYTHONPATH. Here is unipath.__file__ output: /home/User/.virtualenvs/django.1.4/local/lib/python2.7/site-packages/unipath/__init__.pyc And here is one of the lines from sys.path output: /home/User/.virtualenvs/django.1.4/local/lib/python2.7/site-packages Could you please point me to what I'm doind wrong? A: It seems like I figured out the problem. The think was that I did a lot of mess. I had django and other apps installed globaly (long before I started developing the project). Then I installed virtualenvwrapper and created virtualenv. Working in the virtualenv I installed the required dependencies and the django. But when I was trying to run that I ran the globally installed version of django. As a result there were some incompatibilities. After I uninstalled global packages, everithing is ok. How I figured out it? Thanks a lot to Jeff Knup and his post Starting a Django 1.4 Project the Right Way. I walked through the described steps and when I ran (my-virtualenv)$ which django-admin.py it showed me the following path: /usr/local/bin/django-admin while it should have: $HOME/.virtualenvs/ that was a sign that something is wrong. Thanks a lot for everybody for trying to help me.
{ "pile_set_name": "StackExchange" }
Q: Creating screen for android applications with Photoshop I'm working on an android application and I was wondering if there is a way to create the different screen of my application in Photoshop and then using them in the in eclipse as the screens? A: In contrary to iOS, Android runs on a huge variety of devices with screen sizes and resolutions from tiny wrist-watches to full blown HD screens. Thus, it's not possible to create a complete screen with Photoshop and use it in your app. Better have a look on the various Layouts and how to build them via XML layout files. Also you should have an idea of how nine-patch images work.
{ "pile_set_name": "StackExchange" }
Q: how can a program keep a secret from its creator? The idea is that I want a program that can edit a file yet I, the programmer, cannot edit or forge the file. Encrypting the file is an obvious choice, but even then, I'll still have to keep the encryption key secret from myself somehow. Obscuring the secret doesn't seem to work, because I could just use the de-obscuring part of the code that I would need for the program. I'm asking this because I'm trying to make a program that will keep me productive by monitoring my activities, and tell my friends/boss/family just how terrible a procrastinator i am if i don't live up to the goals i set the previous day (in other words: Present me can force future me to not procrastinate) A: It seems the content of the program doesn't matter that much but you want to assure that the timestamp and content of the log can't be forged. I suggest writing the log to some external site where you can put data to but not delete from. Writing false values to the log can only be prevented by having a log which progresses by time. For example, if you hide expenses from your bank account you'll run into problems because future balances will be lower than expected. For short pieces of information like your account balance, just write it to some public site like Twitter. AFAIK it's not possible to send twitter messages like there were sent some time before. For more complex data like the progress of a software development project push your changes with a version control system like git to a remote repo where you can't delete or overwrite history. Update: As you explained in the comments you want to log dinstinct data on your computer that could be forged to anything. IMHO it's virtually impossible for you to write a program on your own which runs on your own computer with root but cannot be controlled. The only kind of software that is somehow similar to your request is DRM software that is calling home to prevent software "piracy". You need a binary program written by somebody else or with the source code deleted. It would need some kind of encrypted and obfuscated network communication which you can't understand. I think there is not much hope for you using this approach. Better learn to control yourself and not answer random questions by strangers on Stackoverflow, ehem.
{ "pile_set_name": "StackExchange" }
Q: Not able to use std::sort with Android NDK ndk-build always complains that the std::sort() has wrong arguments and in same message that it can't be found. Does the ndk use a other function? candidate expects 2 arguments, 3 provided sort(centroids.begin() + i * 10, centroids.begin() + (i + 1) * 10, pointXGreater); error: no matching function for call to 'sort(__gnu_cxx::__normal_iterator*, std::vector > >, __gnu_cxx::__normal_iterator*, std::vector > >, removeConvexity(cv::Mat, cv::Mat, cv::Mat)::&)' for (int i = 0; i < 10; i++) { sort(centroids.begin() + i * 10, centroids.begin() + (i + 1) * 10, pointXGreater); } thats the function call. vector<cv::Point> centroids; centroids.reserve(100); for (int i = 0; i < contours.size(); i++) { vector<cv::Point> contour = contours.at(i); Moments mom = moments(contour); cv::Point center = cv::Point(int(mom.m10 / mom.m00), int(mom.m01 / mom.m00)); centroids.push_back(center); } std::reverse(centroids.begin(), centroids.end()); struct { bool operator()(const cv::Point p1, const cv::Point p2) { return p1.x < p2.x; } } pointXGreater; Somehow I was only able to compile it once. Now the problem came back. A: static bool pointXGreater(const cv::Point p1, const cv::Point p2) { return p1.x < p2.x; } for (int i = 0; i < 10; i++) { sort(centroids.begin() + i * 10, centroids.begin() + (i + 1) * 10, pointXGreater); } that solved the problem.
{ "pile_set_name": "StackExchange" }
Q: Concrete5 database index specified in db.xml but doesn't "take". How do I make it work? Environment: Windows7, IIS7, MySQL 5.1.57, Concrete5 5.4.1.1 I'm getting this rather odd error message when I place my custom block: Fatal error: Uncaught exception 'ADODB_Exception' with message 'mysql error: [-1: No primary key found for table btCtL] in BlockRecord::UpdateActiveTable(0, 0) ' in C:\inetpub\wwwroot\Concrete5\concrete\libraries\3rdparty\adodb\adodb-exceptions.inc.php:78 Stack trace: #0 C:\inetpub\wwwroot\Concrete5\concrete\libraries\3rdparty\adodb\adodb-active-record.inc.php(494): adodb_throw('mysql', 'BlockRecord::Up...', -1, 'No primary key ...', 0, 0, Object(ADODB_mysql)) #1 C:\inetpub\wwwroot\Concrete5\concrete\libraries\3rdparty\adodb\adodb-active-record.inc.php(402): ADODB_Active_Record->Error('No primary key ...', 'UpdateActiveTab...') #2 C:\inetpub\wwwroot\Concrete5\concrete\libraries\3rdparty\adodb\adodb-active-record.inc.php(136): ADODB_Active_Record->UpdateActiveTable(false) #3 C:\inetpub\wwwroot\Concrete5\concrete\libraries\block_view.php(30): ADODB_Active_Record->__construct('btCtL') #4 C:\inetpub\wwwroot\Concrete5\concrete\libraries\block_controller.php(222): BlockRecord->__construct('btCtL') #5 C:\inetpub\wwwroot\Concrete in C:\inetpub\wwwroot\Concrete5\concrete\libraries\3rdparty\adodb\adodb-exceptions.inc.php on line 78 The db.xml in this case reads <?xml version="1.0"?> <schema version="0.3"> <table name="btCtL"> <field name="bID" type="I"> <unsigned /> <key /> </field> <field name="Number_1" type="C" size="12"></field> <field name="Number_2" type="C" size="12"></field> <field name="Number_3" type="C" size="12"></field> <field name="Number_4" type="C" size="12"></field> <field name="Number_5" type="C" size="12"></field> <field name="Number_6" type="C" size="12"></field> <field name="Number_7" type="C" size="12"></field> <field name="Number_8" type="C" size="12"></field> <field name="Number_9" type="C" size="12"></field> <field name="Number_10" type="C" size="12"></field> </table> </schema> The error has to do with there being "No primary key found for table btCtL" which is demonstrably false. If I go into phpAdmin and force the issue, it works, but I can't be doing that for every client site, nor can I expect clients to do it themselves. Is this a bug? Is there a workaround? Or am I just thick? A: The problem seems to be Concrete5's. I have just used MySQLInstanceConfig.exe to change from "Best Support for multilingualism" (what I had wanted in the first instance) to "Standard Character Set". This takes the character set from utf8 to Latin1. After this change a Refresh creates a PRIMARY key on bID. Alternatively, it's MySQL 5.1's problem and may have been fixed in 5.5. Am yet to try it out.
{ "pile_set_name": "StackExchange" }
Q: Unable to solve this Error I am getting "you must specify a way to create the tab indicator" error(as per logcat). Can't find the reason. Main class: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pes.user.pesce/com.pes.user.pesce.MessagesActivity}: java.lang.IllegalArgumentException: you must specify a way to create the tab indicator. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.IllegalArgumentException: you must specify a way to create the tab indicator. MesaageActivty.java public class MessagesActivity extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.messages_layout); TabHost tabHost = getTabHost(); // Tab for Photos TabHost.TabSpec photospec = tabHost.newTabSpec("Overview"); // setting Title and Icon for the Tab // photospec.setIndicator("Photos", getResources().getDrawable(R.drawable.icon_photos_tab)); Intent photosIntent = new Intent(this, AdmissionActivity.class); photospec.setContent(photosIntent); // Tab for Songs TabHost.TabSpec songspec = tabHost.newTabSpec("How to Apply"); // songspec.setIndicator("Songs", getResources().getDrawable(R.drawable.icon_songs_tab)); Intent songsIntent = new Intent(this, OverviewActivity.class); songspec.setContent(songsIntent); // Adding all TabSpec to TabHost tabHost.addTab(photospec); // Adding photos tab tabHost.addTab(songspec); // Adding songs tab } } message_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#f8f9fe" android:orientation="vertical" > <include layout="@layout/actionbar_layout" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="15dip" android:text="Admissions" android:textColor="#ff29549f" android:textSize="25dip" android:textStyle="bold" /> </LinearLayout> <TabHost android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/tabhost"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content"></TabWidget> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tab1" android:id="@+id/textView2" /> </LinearLayout> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/tab2" android:orientation="vertical"></LinearLayout>--> </FrameLayout> </LinearLayout> </TabHost> </LinearLayout> manifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.pes.user.pesce" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".AndroidDashboardDesignActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AdmissionActivity"></activity> <activity android:name=".OverviewActivity"></activity> </application> </manifest> I can't guess the exact problem. Would be grateful for any guidance. A: Uncomment that lines: photospec.setIndicator("Photos", ...... songspec.setIndicator("Songs", ....... And use onlky text, without icons. photospec.setIndicator("Photos") songspec.setIndicator("Songs")
{ "pile_set_name": "StackExchange" }
Q: How can I delete a datafile that has no tablespace without accessing the filesystem? I dropped a tablespace and accidentally did not drop the data file with it. Now I cannot find the data file in dba_data_files. How do I remove it? A: Create a new tablespace Add the datafile to the tablespace Drop the tablespace and its datafiles For example: CREATE TABLESPACE MYAPP DATAFILE '/mnt/data/app/oracle/oradata/MYAPP_02.dat' SIZE 100M AUTOEXTEND ON; alter tablespace MYAPP add datafile '/mnt/data/app/oracle/oradata/MYAPP_01.dat'; drop tablespace MYAPP including contents and datafiles;
{ "pile_set_name": "StackExchange" }
Q: Encoding YUV to mP4 With qp to get max quality I am trying to encode my YUV420 Raw format file into mp4. Here is the ffmpeg command ffmpeg -f s16le -ar 44100 -ac 1 -i "0.a" -f rawvideo -pix_fmt yuv420p -s 480x480 -r 30 -i "0.v" -vcodec libx264 -profile:v baseline -preset ultrafast -qp 0 -b:v 1024k -g 30 -acodec libfdk_aac -ar 44100 -ac 1 -b:a 64k -f mp4 -movflags faststart "1438947231095.mp4" If i remove qp = 0; it works however the quality is very low not sure why. If i put qp = 0 it doesn't work, What is wrong? Getting this error Error while opening encoder for output stream #0:0 - maybe incorrect parameters A: The baseline profile doesn't support lossless H.264. You must use the High 4:4:4 Predictive profile instead: -profile:v high444
{ "pile_set_name": "StackExchange" }
Q: StackPanel in Swing Is there any way I can display the stack panel in using swing. I have tried and googled various option but could not find anything relevant. Please give me an idea. A: Errr... A lot of confusion here. Let me see if I can add to it. Swing has a CardLayout, into which you can put plain JPanels. So, make a JPanel, give a Cardlayout as the manager. Cardlayout handles displaying JPanels (or other controls) on top of others. I hope I understood, and that my answer helps.
{ "pile_set_name": "StackExchange" }
Q: Jasmine Create Spy on Native JS Function on Global Window Object I am writing a test to see if Array.prototype.map was called. I thought this would work since Array.prototype.map is located on the global window object: it("does not use Array.prototype.map", function(){ spyOn(window, "Array.prototype.map") fn([2,2,3]); expect(Array.prototype.map.calls.count()).toEqual(0); }); I receive the error Array.prototype.map does not exist. When I create my own custom global functions, this method works fine. Based on this other post It appears any global functions can be spied on using the syntax I am using above. If I create my own functions, this syntax works. Any ideas on why Array.prototype.map is returning undefined? A: hopefully you already got your answer, but for people searching, it's because you should spyOn(Array.prototype, 'map');
{ "pile_set_name": "StackExchange" }
Q: Find all SSRS reports using the same shared dataset I have been trying to find out what (if anything) is using a particular database table, so I can update it. I have found a stored procedure accessing this table that is used by a SSRS instance for a shared dataset. I have a copy of the SSRS solution and when I open it in VS2008 I can see the dataset. There are also 18 reports in this solution. When I right-click and select find usages on any of the shared datasets it just says "Usages of blah.rsd was not found". I can individually open each Report and check the datasets on each report to see if they match the shared dataset, but that seems ridiculous. Surely there is an easier way to find usages of the shared dateset? A: The query below displays all reports that are in the same project and using the shared dataset. For explanation of the type column in the Catalog, see this link from the msdn forums where they also unhelpfully mention querying the database directly is not supported... select c.Name as ReportName, c.Path from Catalog c join DataSets ds on c.ItemID = ds.ItemID --all reports datasets (including those created from shared datasets) join Catalog c2 on ds.LinkID = c2.ItemID and c2.Type = 8 --all shared datasets join Catalog c3 on c.ParentID = c3.ItemID --the project dataset object join Catalog c4 on c3.ParentID = c4.ItemID --the project object where c2.Name = 'MySharedDatasetName' and c4.Name = 'MyProjectName' Thanks to s_f for leading me in the right direction!
{ "pile_set_name": "StackExchange" }
Q: Setting cookie expiration for OpenIdConnectAuthentication I'm trying to set an expiration date for OIDC cookie. I tried to set AuthenticationTicket.ExpiresUtc in Notifications.SecurityTokenValidated but the .AspNet.Cookies cookie expiration time is still "Session" in browser. Is there a way to do this? app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, CookieHttpOnly = true }); var oidcOptions = new OpenIdConnectAuthenticationOptions { UseTokenLifetime = false, .. SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType, Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenReceived = n => { n.AuthenticationTicket.Properties.ExpiresUtc = System.DateTimeOffset.UtcNow.AddMinutes(30); return Task.FromResult(0); } }; I'm using ASP.NET MVC .NET 4.5.2, Owin 4.0.1 A: Apparently you also need to add n.AuthenticationTicket.Properties.IsPersistent = true;
{ "pile_set_name": "StackExchange" }
Q: How to get the value of custom HTML attribute using JQuery? I have a repeater with check boxes in each row. I'm trying to check the check box in row based on another check box in same row. For this I'm executing a function on OnClick event of check box and this function finds the custom attribute of the parent and checks if parent is checked or not. If returned true it checks the check box with same attribute name for child class . Th problem is I can't get the value of custom attribute of parent class. It is always undefined. childid in jquery function is always undefined. I tried using data property too but it's of no use . $(objid).data('chldname'); function check_view(objid) { var childid = $(objid).attr('chldname'); if ($(objid).is(':checked')) { $("[name=" + childid + "]").attr('checked', true); } } HTML: <td style="text-align: center"> <asp:checkbox id="cb_uploadaccess" runat="server" chldname='chld<%#Eval("ROLE_SEQ")%>' onclick='JavaScript:return check_view(this);' /> <asp:hiddenfield id="hiddenuploadaccess" runat="server" value='<%#Eval("UPLOAD_ACCESS")%>' /> </td> <td style="text-align: center"> <asp:checkbox id="cb_viewaccess" name='chld<%#Eval("ROLE_SEQ")%>' runat="server" /> <asp:hiddenfield id="hiddenviewaccess" runat="server" value='<%#Eval("VIEW_ACCESS")%>' /> </td> A: I did this in another way, just changed my JQuery function like this which worked. function check_view(objid) { var childid = $(objid).attr('ID'); var childId1 = childid.substr(childid.length - 2); if ($(objid).is(':checked')) { $(childId1).attr('checked', true); $("[id$=chpMain_rptDocAccessroles_cb_viewaccess" + childId1 + "]").attr('checked', true); } }
{ "pile_set_name": "StackExchange" }
Q: What happened to *kweþana? In a time when distinct Germanic dialects already existet in geographically diffenrent areas, the usual verbs to signal a following direct speech seem to be descendant of PrG „*kweþana“ in any dialect (e.g. Go: Wulfila, OS: Heliand, OHG: Monsee Fragments). However in todays‘ use of Germanic languages (both oral and written) forms like G „sagen“, EN „to say“ Du „zeggen“, IS „segja“, Sw „säga“, Nw „seie“, Da „sige“ dominate. Why and how did this often used verb nearly completely diappear form all Germanic languages? Why and how could it consequently be replaced be the „same“ word in distinct dialects over geographically diffenrent areas? A: First, just to note, *kweþaną didn't completely die out: English "quoth" is archaic but still recognizable, and Icelandic kveða is still in active use. But you're absolutely right about the general trend that killed off most descendants of *kweþaną. It's now quite rare across the Germanic languages, when it used to be widespread. It's hard to say why something like this happens in linguistics, at least in a falsifiable way, but it's certainly possible to speculate and make some educated guesses. As Colin Fine points out in the comments, there's a very nice parallel here with Latin inquam. Inquam ("I say") was a common Classical word with very restricted usage: it was always connected to a specific quotation or phrase of some sort, and almost always occurs in the present tense singular—it doesn't even have a single attestation of its infinitive, anywhere, in any stage of the language. So despite its Classical popularity, inquam left no impression at all on modern Romance languages. It was simply too heavily restricted; more general words like dicō "to speak" took its place, giving French dire, Spanish decir, and so on. It's entirely possible that the same thing happened with *kweþaną in Germanic: the use of this verb became restricted to certain contexts, and eventually more general synonyms caught on and took its place. In the languages where the root survives, like Icelandic, it has no such restrictions (either having lost them or never developed them), and so it sticks around as a general-purpose verb for speech.
{ "pile_set_name": "StackExchange" }
Q: How to set EXTJS Combobox label width I am trying to get the label for the combobox to show correctly in the example below. I am trying to get it to work in Sencha Fiddle. The text if too long, is getting truncated. Ext.application({ name : 'Fiddle', launch : function() { // The data store containing the list of states var states = Ext.create('Ext.data.Store', { fields: ['abbr', 'name'], data : [ {"abbr":"AL", "name":"Alabama"}, {"abbr":"AK", "name":"Alaska"}, {"abbr":"AZ", "name":"Arizona"} //... ] }); // Create the combo box, attached to the states data store Ext.create('Ext.form.ComboBox', { fieldLabel: 'Reaaaaaaaaaaaaaaallllllllly long', fieldlabelStyle: 'width:600px',//doesn't do anything store: states, queryMode: 'local', displayField: 'name', valueField: 'abbr', renderTo: Ext.getBody() }); } }); A: Try with labelStyle Ext.application({ name : 'Fiddle', launch : function() { // The data store containing the list of states var states = Ext.create('Ext.data.Store', { fields: ['abbr', 'name'], data : [ {"abbr":"AL", "name":"Alabama"}, {"abbr":"AK", "name":"Alaska"}, {"abbr":"AZ", "name":"Arizona"} //... ] }); // Create the combo box, attached to the states data store Ext.create('Ext.form.ComboBox', { fieldLabel: 'Reaaaaaaaaaaaaaaallllllllly long', labelStyle: 'width:600px', //fieldlabelStyle: 'width:600px',//doesn't do anything store: states, queryMode: 'local', displayField: 'name', valueField: 'abbr', renderTo: Ext.getBody() }); } });
{ "pile_set_name": "StackExchange" }
Q: What would happen if EVM didn't exist in Ethereum? It's not clear to me the importance of the Ethereum Virtual Machine and why it is used. So it is natural to ask what would happen if EVM didn't exist? or Ethereum didn't use it. A: Ethereum provides two main services : Money transfer and Smart contracts processing. The first doesn't need a VM but the second does while a smart contract is a piece of code which needs a VM or a compiler to run it. So no VM no ability to write smart contract or advanced programs handling assets or money. read this post to get more details about why do they creat a new VM instead using an existing one : What was the reason to invent the EVM? A: First to get an idea on EVM you may refer this question on what is EVM. And then, What would happen if the EVM didn't exist? As I understand, Since ethereum should provide a platform independent (Otherwise you need to deploy different contracts at different addresses for different platforms?) running environment to execute smart contracts (providing a Turing Complete language to write smart contracts is a main specialty in Ethereum ) , A VM is highly needed. But why not an existing VM is not used? Ethereum has it's on requirements other than just executing a code. This answer requirements needed for the EVM will give a good idea on that. And this comparison with JVM will give a more insight to that. Highlighting the security aspect Ethereum Virtual machine(EVM) provides the secured run-time environment for the smart contracts in the network. Smart Contracts are open to everyone in the network and anyone in the network is allowed to deploy smart contracts. When a node need execute a smart contract function, the code is run with in the particular node. These reasons open up a security vulnerability, unless the run-time environment is not controlled. In a worst case scenario, it may lead nodes to be unavailable and ultimately the network to be unavailable. These vulnerabilities are prevented by controlling the run-time environment by the EVM.
{ "pile_set_name": "StackExchange" }
Q: Why is there a short ŭ in rŭtus? In Cerberus's list of u-stem verbs, rŭō, rŭere, rŭī, rŭtus is the only one with a short ŭ in the participle stem. Why is this? Does it go back to different types of verbs in PIE, as with stătus versus amātus? A: Szemerényi (1980) says that the following "descriptive rule" summarizes the conjugation pattern for verbs ending in -uo: verbs in -uo in general form their perfect in -uī, their PPP in -ūtus (even tuor/tūtus would conform to this rule!); a list would have to specify four exceptions: ruo has rūtus, but in the compounds -rŭtus; two verbs which have a velar in the perfect (fluxī, struxī) show it in the PPP, too, as does frūctus from fruor. (pp. 11-12) (emphasis added) I was a bit confused by the rule saying that the length of the vowel in -rutus depends on whether the word is a compound. Some 17th-century books on Latin grammar seem to indicate that the form ruitum is used as the supine of ruo 'to rush', but that -ruitum is not used in derived compound words (The Royal Grammar, Commonly Called Lilie's Grammar, explained by William Walker (1695); A Compleat System of Grammar, English and Latin, by William Clare (1699)); however, I don't know whether ruitum is a post-Classical form—it doesn't seem to be mentioned in Lewis and Short. A further complication is that apparently, there are two different verbs that have ruo as the first principal part. Szemerényi refers to them as ¹ruo and ²ruo. The form rūtus seems to occur primarily as the PPP of ²ruo, which is thought to come from a PIE root ending in *w~u followed by a laryngeal. In Indo-European languages, u (=syllabic *w) followed by a laryngeal developed into the long vowel ū. Many of the other -uo verbs with PPPs ending in -ūtus (acuo, arguo, futuo, metuo, minuo, statuo, tribuo) seem to be "denominative", which somehow explains the length of the vowel. Szemerényi says The PPP has, as we have seen (2.1), -ūtus in the denominatives. This is what we should expect in any case, seeing that before the suffix -to the stem-final vowel is lengthened even in purely adjectival forms; c.f. aurītus, crīnītus, turrītus, on the one hand, argūtus, cinctūtus, cornūtus, versūtus, verūtus, on the other, and, outside Italy, e.g., Greek δακρῡτός 'wept over, tearful'. (p. 28) Principal parts of ¹ruo and ²ruo Szemerényi gives different vowel lengths in the PPP for ¹ruo and ²ruo: ¹ruo -uī -ŭtum 'rush, overthrow' (Palatus) ²ruo -uī -ūtus 'root, rake, scrape' (Lucretius) (p. 10) There are two corresponding entries for ruo in Wiktionary and in De Vaan (2008), but they give conflicting information about the perfect and supine forms: For ¹ruo, Wiktionary says "perfect active ruī, supine rutum" (Wiktionary doesn't use breves in its Latin entries, so the lack of a macron is supposed to imply that the vowel is short). De Vaan also gives the perfect as ruī, but gives the PPP as rū̆tum. As I mentioned above, I've also seen the form ruitum in a few sources. The Latin Wiktionary ("Victionarium") says " rutum vel rūtum vel ruitum". For ²ruo, Wiktionary says "no perfect or supine forms". De Vaan gives no perfect form, but gives the PPP as rūtum. Etymology of ¹ruo and ²ruo Szemerényi says ¹ruo is from IE *ereu- (I don't understand the reason for the initial *e in this reconstruction, but it seems irrelevant to the development of the vowel after the *r) which is also supposed to be the source of Sanskrit r̥ṇōmi and Greek ὀρούω (p. 23). Wiktionary says that the verb that Szemerényi calls ¹ruo is from PIE *h₃rew-. For Italic specifically, Szemerényi gives the reconstruction *rewō, and says "The form of the Latin verb would then be due to the compounds" (p. 24). I'm not sure what this means. De Vaan gives the Proto-Italic form as *rowe/o-, and the PIE form as *h₃reu-e/o-. For ²ruo, after listing some cognates, Szemerényi suggests that it comes from IE "*rūyō" (comparing the form to Old Church Slavonic ryjo). Wiktionary says that what Szemerényi calls ²ruo is from "*(H)rewH-", which seems consistent with Szemerényi's suggestion (PIE *uH developed to IE *ū). De Vaan gives the Proto-Italic form as *rowe/o- (the same as for ¹ruo, apparently), and the PIE form as *(H)reuH-e/o-. Although the sources don't agree on all the details, I think it seems fairly clear that the reason for the (at least potential) length difference between the vowels in the PPPs of ¹ruo and ²ruo is the laryngeal that comes after the w~u in the reconstructed ancestor of ²ruo in PIE. Vowel length in words related to ²ruo Some weird things seem to happen with vowel length in related words or derivatives of these words. De Vaan's entry for ²ruo lists rutus, -ūs, rutābulum, rutellum, rutrum, rūta caesa (as well as some verbs) as derivatives, and says "It seems that the derivatives of ruō 'to rush' and ruō 'to dig' have become mixed up: we find short-vowel forms meaning 'dig', in spite of the PIE root etymology *(H)ruH-" (p. 531). Likewise, Szemerényi says in a footnote on p. 23 that "rutrum, rutābulum, 'Schaufel', rūta caesa [...] belong with ²ruo". A (long) side note: Lewis and Short use a macron on the first syllable of rutrum, but I'm inclined to think that this is an example of the use of the macron to mark metrical weight. Because rutrum has a medial consonant cluster, it could scan in poetry as rut.rum with a heavy first syllable. That doesn't make the vowel in the first syllable long (despite the confusing old description of such vowels as "long by position"), but Lewis and Short seem to have considered syllable weight sufficient reason to mark a vowel with a macron, at least in certain contexts where the weight of the syllable would otherwise be somewhat non-obvious—e.g., as far as I know, L&S don't use macrons like this on vowel letters before double consonant letters, but they do seem to use them on vowel letters before single consonant letters that scan long, like the j in mājor (which is thought to have been pronounced [majjor] in Latin) and the z in trăpēzīta (which comes from Greek τραπεζίτης, with epsilon; L&S mention an alternative spelling with tarpess- which provides further support for the idea that it was the consonant rather than the vowel that was long in this word). Works cited Szemerényi, Oswald. 1980. "Latin Verbs in uo, uere". Italic and Romance Linguistic Studies in Honor of Ernst Pulgram, edited by Herbert J. Izzo. De Vaan, Michiel. 2008. Etymological Dictionary of Latin and the Other Italic Languages.
{ "pile_set_name": "StackExchange" }
Q: OpenGL gluLookAt I tried to draw a teapot and view it in 3D but when I ran the program, nothing showed up. There is nothing in the window. I know it has something to do with my gluLookAt() function but I am not sure how to fix it. // helloteapot.cc //#include <GLUT/gl.h> #include <GLUT/glut.h> #include "GL/glui.h" void display () { /* clear window */ glClear(GL_COLOR_BUFFER_BIT); /* draw scene */ glColor3f(1.0, 0.0, 0.0); glTranslatef(0.0, 0.5, 0.0); glutSolidTeapot(0.15); /* flush drawing routines to the window */ glFlush(); } int main ( int argc, char * argv[] ) { glutInit(&argc,argv); /* setup the size, position, and display mode for new windows */ glutInitWindowSize(800,600); glutInitWindowPosition(0,0); glutInitDisplayMode(GLUT_RGB); /* create and set up a window */ glutCreateWindow("hello, teapot!"); glutDisplayFunc(display); /*GLfloat width = 800; GLfloat height = 600; GLfloat aspect = (GLfloat)width / (GLfloat)height; // Set the viewport to cover the new window glViewport(0, 0, width, height);*/ // Set the aspect ratio of the clipping volume to match the viewport glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix glLoadIdentity(); // Reset // Enable perspective projection with fovy, aspect, zNear and zFar //luPerspective(45.0f, aspect, -100.0f, 100.0f); gluLookAt(0, 0, 0, 0, 0.5, 0, 0, -1, 0); /* tell GLUT to wait for events */ glutMainLoop(); } A: You have asked GL to position the camera at the origin, aim the camera upwards towards the point (0, 0.5, 0), and have also specified (incorrectly) the up vector to be 0, -1, 0. The problem is that the camera's forward direction is (0, 1, 0) [as specified by your eye and aim positions], and this direction conflicts with the up vector or (0, -1, 0). Try using a vector at right angles to the forward direction instead! (e.g. [1, 0, 0], [0, 0, 1]) gluLookAt( 0, 0, 0, //< camera location 0, 0.5, 0, //< looking towards point 1, 0, 0); //< which direction is up?
{ "pile_set_name": "StackExchange" }
Q: Ruby undefined helper method I am writing a simple ruby script. I want a help message to be displayed when the script is run. def myClass def help puts "Help message" end (...other methods...) help # main loop (...rest of script...) end When I run it, I get "undefined local variable or method 'help' for myClass:Class (NameError)". Why doesn't ruby see my help method? Did ruby lose it? It's already defined! I can't define it any further! A: you need to define a class method, what you have there is an instance method. class MyClass def self.help puts "help" end help end To clarify a bit class MyClass def self.my_class_method puts 'class method' end def my_instance_method puts 'instance method' end end # class methods are called on teh class itself MyClass.my_class_method # instances methods are available on instances of the class obj = MyClass.new obj.my_instance_method
{ "pile_set_name": "StackExchange" }
Q: matplotlib - what kind of set_major_locator should I use I have a question regarding a plot feature when the X-Axis is a date. Setting I have a two time-series dt and x, where dt is a list of datetime.datetime values and x is a numpy array object. dt = [datetime.datetime(1996, 12, 3, 0, 0), datetime.datetime(1996, 12, 4, 0, 0), ..., datetime.datetime(2015, 6, 5, 0, 0), datetime.datetime(2015, 6, 8, 0, 0)] x = array([29.06262, 29.26933, ..., 208.41999, 208.44532]) and both have the same length. When I plot them as : ax.plot(dt, x, color='black', lw=2) I get a chart which has X-Tick Labels as their years (e.g. 1994, 1998, 2002, 2006, 2010, 2014). After some zooming, the X-Tick Labels nicely start showing months (e.g. Aug 2009, Oct 2009, Dec 2009, Feb 2010, Apr 2010, Jun 2010). After further zooming, the X-Tick Labels again nicely start showing days (e.g. Jan 14 2010, Jan 21 2010, Jan 28 2010, Feb 04 2010, Feb 11 2010, Feb 18 2010). Question Now, I am trying to draw a custom chart (e.g. say using LineCollection) instead of using the default plot. I suspect I would need to use ax.xaxis.set_major_locator(???) and ax.xaxis.set_major_formatter(???) to get the same feature of the X-Axis as in the default plot function. What do I need to provide (i.e. ???) to ax.xaxis.set_major_locator(???) and ax.xaxis.set_major_formatter(???) ? A: Yes, you assumption was right: You have to set the locator and formatter manually. The "regular" ones are available in matplotlib.ticker and the ones related to dates in matplotlib.dates. There is quite a variety of fixed ones (e.g. WeekdayLocator, MicrosecondLocator, etc.), but also the automatic ones that you get when using plot. So this should do it: import matplotlib.pyplot as plt import matplotlib.dates as mdates # all your fancy plotting code ax.xaxis.set_major_locator(mdates.AutoDateLocator()) ax.xaxis.set_major_formatter(mdates.AutoDateFormatter()) plt.show() Further reading: http://matplotlib.org/api/dates_api.html Extra: Be careful with you list of datetimes: matplotlib has an internal date/time representation (number of days as floats) and thus datetime objects need to be converted before plotting. In plot this conversion happens automatically, for custom graphs you might have to do that yourself with matplotlib.dates.date2num.
{ "pile_set_name": "StackExchange" }
Q: Client-side not creating file So, I have a working socket. I'm basically making a socket to allow me to transfer files from one program to another program. Everything is working except on the client side, it won't create the file? Server: int main() { WSADATA Winsock; SOCKET Socket, Sub; Addr addr; IncomingAddress incomingAddress; int AddressLen = sizeof(IncomingAddress); // Start up Winsock WSAStartup(MAKEWORD(2, 2), &Winsock); if (LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2) { WSACleanup(); return 0; } Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // Memset alternative ZeroMemory(&addr, sizeof(Addr)); addr.sin_family = AF_INET; addr.sin_port = htons(portNumber); bind(Socket, (sockaddr*) &addr, sizeof(Addr)); if (listen(Socket, 1) == SOCKET_ERROR) { printf("Listening error!\n"); } else { printf("Listening...\n"); } if (Sub = accept(Socket, (sockaddr*) &incomingAddress, &AddressLen)) { char *ClientIP = inet_ntoa(incomingAddress.sin_addr); int ClientPort = ntohs(incomingAddress.sin_port); printf("Client connected!\n"); printf("IP: %s:%d\n", ClientIP, ClientPort); printf("Sending file... \n"); FILE *File; char *Buffer; unsigned long Size; File = fopen("test.txt", "rb+"); if (!File) { printf("Error while reading the file!\n"); getchar(); return 0; } fseek(File, 0, SEEK_END); Size = ftell(File); fseek(File, 0, SEEK_SET); Buffer = malloc(Size); fread(Buffer, Size, 1, File); char cSize[MAX_PATH]; sprintf(cSize, "%i", Size); fclose(File); send(Sub, cSize, MAX_PATH, 0); // File size } return 0; } Client: int main() { WSADATA Winsock; SOCKET Socket; Addr addr; IncomingAddress incomingAddress; int AddressLen = sizeof(IncomingAddress); WSAStartup(MAKEWORD(2, 2), &Winsock); if (LOBYTE(Winsock.wVersion) != 2 || HIBYTE(Winsock.wVersion) != 2) { WSACleanup(); return 0; } Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); ZeroMemory(&addr, sizeof(Addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(6000); if (connect(Socket, (sockaddr*) &addr, sizeof(Addr)) < 0) { printf("Connection Failed!\n"); getchar(); return 0; } printf("Connection successful! \n"); printf("Receiving file... \n"); int Size; char *Filesize = malloc(1024); if (recv(Socket, Filesize, 1024, 0)) { // File Size Size = atoi((const char*) Filesize); printf("File size: %d\n", Size); } char *Buffer = malloc(Size); int Offset = 0; while (Size > Offset) { int Amount = recv(Socket, Buffer + Offset, Size - Offset, 0); if (Amount <= 0) { printf("Error: " + WSAGetLastError()); break; } else { Offset += Amount; printf("2\n"); } } FILE *File; File = fopen("test.txt", "wb+"); fwrite(Buffer, 1, Size, File); fclose(File); getchar(); closesocket(Socket); WSACleanup(); return 0; } A: You're sending merely the lenght of the file, but not the file itself to the client: send(Sub, cSize, MAX_PATH, 0); // File size This never recieves anything: int Amount = recv(Socket, Buffer + Offset, Size - Offset, 0); So yeah, just send the actual file as well.
{ "pile_set_name": "StackExchange" }
Q: Android convert array of months I get an Array of months since my SQLite database, now I want to see months in the chart aChartEngine with the long name. How do I? String sql = "SELECT strftime('%m',"+Table.DATE+") AS month"; Cursor c = db.rawQuery(sql, null); int count = c.getCount(); String[] months= new String[count]; for(int i=0; i<count; i++) { c.moveToNext(); months[i] = c.getString(0); } for(int i=0;i<months.length;i++){ multiRenderer.addXTextLabel(i+1, months[i]); } A: TimeZone timezone = TimeZone.getDefault(); Calendar calendar = new GregorianCalendar(timezone); for(int i=0;i<months.length;i++){ int monthNumber=Integer.valueOf(months[i])-1; calendar.set(2014, monthNumber, 1, 1, 1, 1); String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()); multiRenderer.addXTextLabel(i+1, monthName); }
{ "pile_set_name": "StackExchange" }
Q: BuildTemplate Edits: TFS Community Build Extensions: TFSVersion Build Activity - SourceDirectory problems I'm trying to follow TFSVersion Build Activity1 to edit my TFS build template. My default template (and some added activities following the instructions above) for TFS 2013 looks like this: I can't get workflow working. Here are the the issues: I read that SourcesDirectory is in the WellKnownEnvironmentVariables in namespace Microsoft.TeamFoundation.Build.Activities.Extensions. But when i try to use the SourcesDirectory in the "Find the AssemblyInfo File" activity. it tells me it is not declared. i thought you are not supposed to declare it because it's already known? i have the Microsoft.TeamFoundation.Build.Activities referenced. what else do i need? The instructions say to locate GetWorkspace in your default template. My default template doesn't have that. Do i need to add it under associate changesets? or can i use something from the Initialize Environment activity. But when i look there.. all i see is "src". not ever sure what that is. Do i need to do a GetWorkspace at all if the template uses the Init Env Act? A: Follow: SourcesDirectory1 Yes, apparently you need to use GetEnvironmentVariable activity to get the SourcesDirectory (for TFS 2013). (Save the result in a local variable to be used by the FindMatchingFiles Activity) In my case i also needed to use the FULL Path of the SourcesDirectory variable. Since even though i have it listed under the imports, it didn't resolve "WellKnownEnvironmentVariables.SourcesDirectory". Microsoft.TeamFoundation.Build.Activities.Extensions.WellKnownEnvironmentVariables.SourcesDirectory Also i did NOT need to use GetWorkspace.
{ "pile_set_name": "StackExchange" }
Q: How do I in CSS combine a plus selector with parent and class? In a div wrapper, I have some radio buttons. When one is selected, I wish to make the label for it have a certain background color. How specific can I be in the CSS rule for this? HTML: <div class="switch-wrapper"> <form> <input id="id-1" class="my-switch-on" type="radio" /> <label for="id-1">Yes</label> <input id="id-2" class="my-switch-off" type="radio" /> <label for="id-2">No</label> </form> </div> My closest guess: div.switch-wrapper input[type="radio"].my-switch-on+label { background-color: #000; } But I can't get it to work. What I did instead was this: input[type="radio"]:checked + label { background: #000; } Which certainly work, but I'd like to know how to combine the plus selector with other types of selectors and classes. Is it possible? Can you group selectors with parenthesis? E.g.: div.foo form.bar + div > span { background-color: #000; } Which selector has precedence? Can't do more than one? I mostly do backend engineering so front-end isn't my strong suit. Grateful for any tips or guidelines, links to specs I didn't find an/or short answers. :) A: This SO post should answer your specific question about selector associativity. If you have control over the HTML and you find yourself needing highly elaborate selectors, it's probably better to slightly reorganize the HTML instead (yes, this goes against the ideal of separating semantics and presentation, but HTML and CSS have always fallen far short in that respect)
{ "pile_set_name": "StackExchange" }
Q: How do I set the minimum and maximum length of dataframes in hypothesis? I have the following strategy for creating dataframes with genomics data: from hypothesis.extra.pandas import columns, data_frames, column import hypothesis.strategies as st def mysort(tp): key = [-1, tp[1], tp[2], int(1e10)] return [x for _, x in sorted(zip(key, tp))] positions = st.integers(min_value=0, max_value=int(1e7)) strands = st.sampled_from("+ -".split()) chromosomes = st.sampled_from(elements=["chr{}".format(str(e)) for e in list(range(1, 23)) + "X Y M".split()]) genomics_data = data_frames(columns=columns(["Chromosome", "Start", "End", "Strand"], dtype=int), rows=st.tuples(chromosomes, positions, positions, strands).map(mysort)) I am not really interested in empty dataframes as they are invalid, and I would also like to produce some really long dfs. How do I change the sizes of the dataframes created for test cases? I.e. min size 1, avg size large? A: You can give the data_frames constructor an index argument which has min_size and max_size options: from hypothesis.extra.pandas import data_frames, columns, range_indexes import hypothesis.strategies as st def mysort(tp): key = [-1, tp[1], tp[2], int(1e10)] return [x for _, x in sorted(zip(key, tp))] chromosomes = st.sampled_from(["chr{}".format(str(e)) for e in list(range(1, 23)) + "X Y M".split()]) positions = st.integers(min_value=0, max_value=int(1e7)) strands = st.sampled_from("+ -".split()) dfs = data_frames(index=range_indexes(min_size=5), columns=columns("Chromosome Start End Strand".split(), dtype=int), rows=st.tuples(chromosomes, positions, positions, strands).map(mysort)) Produces dfs like: Chromosome Start End Strand 0 chr11 1411202 8025685 + 1 chr18 902289 5026205 - 2 chr12 5343877 9282475 + 3 chr16 2279196 8294893 - 4 chr14 1365623 6192931 - 5 chr12 4602782 9424442 + 6 chr10 136262 1739408 + 7 chr15 521644 4861939 +
{ "pile_set_name": "StackExchange" }
Q: I want to uninstall the monetdb before I install it again what should I do? only remove the bin directory? or I need some extra operation? A: I would reinstall except if you used a unique --prefix during ./configure. If the latter is the case, the prefix can simply be removed. In an empty prefix, I have the following files: bin: arraytest Mfilter.py mserver5 sample0 smack00 testgetinfo malsample.pl MkillUsers msqldump sample1 smack01 tomograph Mapprove.py Mlog Mtest.py sample2 sqlsample.php mclient monetdb Mtimeout sample3 sqlsample.pl Mdiff monetdbd odbcsample1 sample4 stethoscope etc: tmpfiles.d include: monetdb lib: libbat.la libmapi.so.7 libMonetODBC.la libstream.so.6 libbat.so libmapi.so.7.0.0 libMonetODBCs.la libstream.so.6.0.0 libbat.so.11 libmonetdb5.la libMonetODBC.so monetdb5 libbat.so.11.0.1 libmonetdb5.so libMonetODBCs.so pkgconfig libmapi.la libmonetdb5.so.17 libstream.la python2.7 libmapi.so libmonetdb5.so.17.0.1 libstream.so python3.3 lib64: perl5 local: share share: doc man monetdb php var: monetdb5 So you could also try removing those. Be careful however, there are some subdirectories such as var, lib64, local etc. that will also contain other things on the / prefix in a typical linux system.
{ "pile_set_name": "StackExchange" }
Q: Copy header into new file astropy I have this script that makes a file with multiple extensions, but I would like to add headers from the old files to the extensions. new_hdul = fits.HDUList() new_hdul.append(fits.PrimaryHDU(header=headermain)) new_hdul.append(fits.ImageHDU(nod1, header=header1, name='Chop1')) new_hdul.append(fits.ImageHDU(nod2, header=header2, name='Chop2')) new_hdul.append(fits.ImageHDU(diff1, name='Dif')) Now I have tried: headermain = fits.getheader(file,0) and headermain = fits.open(file).header.copy() But both give me errors saying that ValueError: header must be a Header object How can I fix this? headermain = fits.getheader(file,0) print(headermain) see http://pastebin.com/JXki7EPV A: Generally getting the header as Header object from a file isn't complicated. You astropy.io.fits.open() the file and extract the Header from the PrimaryHDU with: from astropy.io import fits filename = 'test.fits' with fits.open(filename) as hdus: headermain = hdus[0].header or with getheader: headermain = fits.getheader(filename) # Defaults to primary header! and the result will be a fits.Header-object that you can use during writing. But if your file is not a valid FITS file there might be problems. If this doesn't work could you edit your question and show the output of any of these two functions? print(headermain)
{ "pile_set_name": "StackExchange" }
Q: Which is the preferred way of installing up to date versions of Python using Powershell? Packaged binaries or online install? I am attempting to create a tool that will run on PC's with unknown installs of Python. I've created a Powershell script to make sure an up-to-date version is being run so that the rest of the package can run smoothly as it is written in Python 3.7. My current working solution is this: First it checks for any installed version of python, if it is determined that the version (if any is present) is below 3.7, this snippet runs: `[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.7.0/python-3.7.0.exe" -OutFile "c:/temp/python-3.7.0.exe" c:/temp/python-3.7.0.exe /quiet InstallAllUsers=0 PrependPath=1 Include_test=0` My question would be, is this the best way of doing this? Or would it be better to include Python binaries inside the package to circumvent any potential network issues. Thanks for any help or insight! A: I prefer this solution as it decreases the size of the program overall by not preincluding python. although its up to your user. if its a library aimed at extending python for other developers, than no need to include the binaries. instead if this is meant to be standalone, it may be worth it to include the binaries. although I still prefer what you have so it installs the most up to date version.
{ "pile_set_name": "StackExchange" }
Q: postgres fast check if attribute combination also exists in another table I want to check if the same two attribute values exist in two different tables. If the combination from table_a is not existing in table_b it should be inserted into the select statement table. Right now I have the following query, which is working: CREATE TABLE table_a ( attr_a integer, attr_b text, uuid character varying(200), CONSTRAINT table_a_pkey PRIMARY KEY (uuid) ); CREATE TABLE table_b ( attr_a integer, attr_b text, uuid character varying(200), CONSTRAINT table_b_pkey PRIMARY KEY (uuid) ); SELECT * FROM table_a WHERE (table_a.attr_a::text || table_a.attr_b::text) != ALL(SELECT (table_b.attr_a::text || table_b.attr_a::text) FROM table_b) However, the execution time is pretty long. So I would like to ask if there is a faster solution to check for that. A: Your where clause uses a manipulation of attr_a (casting it to text and concatinating with attr_b), so the index can't be used. Instead of this concatination, why not try a straight-forward exists operator? SELECT * FROM table_a a WHERE NOT EXISTS (SELECT * FROM table_b b WHERE a.attr_a = b.attr_a AND b.attr_b = b.attr_b)
{ "pile_set_name": "StackExchange" }
Q: Setting java path in .bat file On Windows 8, I've got a bat file with the following contents: @echo off echo Setting JAVA_HOME set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_39 echo setting PATH set PATH=C:\Program Files\Java\jdk1.6.0_39\bin;%PATH% echo Display java version java -version which I'm trying to use to switch java versions. When I run the .bat file, it outputs the version as 1.6.0_39, but doesn't actually switch versions. Instead, I've had to manually change the path variable every time I want to use a different version. Is there something wrong with the way that I'm setting the path? When I look at the path env variable after I've run this, it doesn't look like it's changed, and you'd think that it would be fairly visible... Current version: @echo off echo Setting JAVA_HOME setx JAVA_HOME "C:\Program Files\Java\jdk1.7.0_09" echo Display java version java -version with %JAVA_HOME%\bin; at the front of my path variable. Doesn't seem to be looking at %JAVA_HOME% A: The SET statement sets an environment variable for the current process only. Set the the global (default) value of an environment variable, use setx. Note that even setx will not affect existing processes, so you will only notice the change in a new command prompt window.
{ "pile_set_name": "StackExchange" }
Q: Integral of $((x^2+1)((x-1)^2+1))^{-1}$ Find $$\int_{-\infty}^{\infty}\frac{1}{(x^2+1)(2-2x+x^2)}dx$$ So I am going to integrate this using a semicircular contour. Is it safe to say that on the curved part, the integral vanishes? because we have two terms that are of the order $x^2$. Wouldn't this mean that the Integral that I wish to calculate is equivalent to $2\pi i\sum Res$. Now the zeros of the denominator are $\pm i$ and $1\pm i$. However, only $i$ and $1+i$ belong in the semicircle. Is this part correct so far? Also, how would I calculate the residues at those two points. A: Yes, you are correct so far. To calculate the residue at $i$, multiply by $x-i$, then evaluate at $i$. So calculate $$\frac1{(x+i)(x^2-2x+2)}$$ at $x=i$, and multiply by $2\pi i$. Then do the same for $1+i$.
{ "pile_set_name": "StackExchange" }
Q: yz Vector3 to Vector2 Simple question, no answer found around the web. Is there an easy way to cast the Y,Z of a Vector3 into a Vector2 without creating a "new Vector2()" Something like Vector3 v = Vector3.one; Vector2 plan = v.yz; (All that with C# in Unity3d) Thx A: C# has a pretty cool feature called extension methods. Set up a class VectorExtensions for example and put this code inside: public static Vector2 YZ (this Vector3 v) { return new Vector2 (v.y, v.z); } Now you can call from everywhere in your project: Vector2 v2 = v3.YZ ();
{ "pile_set_name": "StackExchange" }
Q: Importing multi-valued field into Solr from mySQL using Solr Data Import Handler We have the following two tables in our mySQL: mysql> describe comment; +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | blogpost_id | int(11) | YES | | NULL | | | comment_text | varchar(256) | YES | | NULL | | +--------------+--------------+------+-----+---------+-------+ mysql> describe comment_tags; +------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+-------------+------+-----+---------+-------+ | comment_id | int(11) | YES | | NULL | | | tag | varchar(80) | YES | | NULL | | +------------+-------------+------+-----+---------+-------+ Where each comment can have multiple tags. We can import the entire comment into Solr using the Data Import Handler. However I am not sure how to import the tags for each comment into a multivalued field defined the schema.xml for each comment document. Please advise. Thanks A: You can also use GROUP_CONCAT with a Seperator(e.g " , ") and then try something like this : <dataConfig> <!-- dataSource is just an example. Included just for completeness. --> <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/db" user="root" password="root"/> <document> <entity name="comment" pk="id" query="SELECT *, group_concat(tags) as comment_tags FROM comment" transformer="RegexTransformer"> <field column="blogpost_id" name="blogpost_id"/> <field column="comment_text" name="comment_text" /> <field column="tag" name="comment_tags" splitBy = "," /> </entity> </document> </dataConfig> It'll increase the Performance and also will remove the Dependency of another query. A: Try something like this: <dataConfig> <!-- dataSource is just an example. Included just for completeness. --> <dataSource batchSize="500" type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/my-database" user="root" password="somethinglong1283"/> <document> <entity name="comment" pk="id" query="SELECT * FROM comment"> <field column="blogpost_id" name="blogpost_id"/> <field column="comment_text" name="comment_text" /> <entity name="comment_tags" pk="comment_id" query="SELECT * FROM comment_tags WHERE comment_id='${comment.id}'"> <field column="tag" name="tag" /> </entity> </entity> </document>
{ "pile_set_name": "StackExchange" }
Q: Is it possible to serialize non case classes in Scala? Is it possible to serialize object of below class using Json4s or lift or any other library? class User(uId: Int) extends Serializable { var id: Int = uId var active: Boolean = false var numTweets: Int = 0 var followers: ArrayBuffer[Int] = null var following: ArrayBuffer[Int] = null var userTimeline: Queue[String] = null var homeTimeline: Queue[String] = null var userTimelineSize: Int = 0 var homeTimelineSize: Int = 0 //var notifications: Queue[String] = null var mentions: Queue[String] = null var directMessages: Queue[String] = null } A: You can use Json4s for this purpose (with help of FieldSerializer), below is the code to get started with serialization of the User object: def main(args: Array[String]) { import org.json4s._ import org.json4s.native.Serialization import org.json4s.native.Serialization.{read, write, writePretty} implicit val formats = DefaultFormats + FieldSerializer[User]() val user = new User(12) val json = write(user) println(writePretty(user)) } Also, in your non case class anything which is missing from the JSON needs to be an Option. Another method would be to go for Genson: def main(args: Array[String]) { import com.owlike.genson._ import com.owlike.genson.ext.json4s._ import org.json4s._ import org.json4s.JsonDSL._ import org.json4s.JsonAST._ object CustomGenson { val genson = new ScalaGenson( new GensonBuilder() .withBundle(ScalaBundle(), Json4SBundle()) .create() ) } // then just import it in the places you want to use this instance instead of the default one import CustomGenson.genson._ val user = new User(12) val jsonArray = toJson(user) println(jsonArray) }
{ "pile_set_name": "StackExchange" }
Q: haskell basic telnet network socket example 2 module Main where import Network import Network.Socket import System.IO main :: IO () main = withSocketsDo $ do addrInfos <- getAddrInfo Nothing (Just "localhost") (Just "23") s <- socket (addrFamily (head addrInfos)) Stream defaultProtocol connect s (addrAddress (head addrInfos)) h <- socketToHandle s ReadWriteMode hSetBuffering h (BlockBuffering Nothing) l <- hGetLine h putStrLn l I am trying to make a haskell example of howto login and send receive some hardcoded telnet line commands. So far I have something like this. I expected to see "login:" on the screen but it shows nothing? A: Don't use BlockBuffering Nothing. Use NoBuffering. The haddocks are very clear that BlockBuffering Nothing gives implementation-dependent buffering, not no buffering. So that buffering may well be getting in the way of the hGetLine function.
{ "pile_set_name": "StackExchange" }
Q: Create a race track on a landcape with banked corners I would like to create a racetrack on a landscape with banked corners. I am able to start with a landscape, add a Bezier curve, and use the curve and array modifier to create a track which follows the terrain and is level. However, I would like to bank the corners. Is there a way to do this? For example, is there way to follow a curve and independently specify the angle of rotation in along the curve? The blend file for this example is located here - A: Duplicate the curve, then use the Follow Path constraint with Follow Curve Checked. With the constraint, the banking is influence by the curves tilt. CtrlT in curve edit mode.
{ "pile_set_name": "StackExchange" }
Q: Como adicionar uma classe a multiplos elementos em cache de uma só vez? Em jQuery, podemos adicionar classes de CSS a múltiplos elementos, mas com o elemento já em cache numa variável, como podemos realizar a mesma operação? Exemplo: // adicionar classe a ambos os elementos $('#myEle, #anotherEle').addClass('johnDoe'); Elementos em cache: var $ele1 = $('#myEle'), $ele2 = $('#anotherEle'); // adicionar classe a ambos os elementos $ele1.addClass('johnDoe'); $ele2.addClass('johnDoe'); Como passar para uma linha a adição de uma classe de CSS ao $ele1 e $ele2 ? A: jQuery contém um método, o .add(), que permite agrupar vários objectos de jQuery que representam um grupo de elementos do DOM num único objecto: Documentação da API jQuery: .add() Exemplo: var $ele1 = $('#myEle'), $ele2 = $('#anotherEle'); // adicionar classe a ambos os elementos $ele1.add($ele2).addClass('johnDoe'); Trabalhando com elementos já em cache, será util saber que podes colocar em cache o $ele1 e o $ele2 para o caso de serem chamados várias vezes: var $elements = $ele1.add($ele2); $elements.addClass('johnDoe');
{ "pile_set_name": "StackExchange" }
Q: Convert HTML to markdown I have an app and the admin can create article , and i use the markitup markdown editor for add title etc. Now in my view i want convert this markdown text in html. So in my view if for exemple when admin write the article he write exemple , in the view the text are in bold. I hope you understand and you can help me. I install redcarpet and i put in my application helper this : module ApplicationHelper def markdown(text) if text markdown = Redcarpet::Markdown.new( Redcarpet::Render::HTML.new ) markdown.render(text).html_safe end end and in my show view this : <%= markdown(@article.content) %> I restarted my server but i have one error : uninitialized constant ApplicationHelper::Redcarpet EDIT 2 : THANK's All works !!! !!!!! A: The kramdown gem provides an HTML to Markdown solution in pure Ruby. irb> html = 'How to convert <b>HTML</b> to <i>Markdown</i> on <a href="http://stackoverflow.com">Stack Overflow</a>.' => "How to convert <b>HTML</b> to <i>Markdown</i> on <a href=\"http://stackoverflow.com\">Stack Overflow</a>." irb> document = Kramdown::Document.new(html, :html_to_native => true) => <KD:Document: ... > irb> document.to_kramdown => "How to convert **HTML** to *Markdown* on [Stack Overflow][1].\n\n\n\n[1]: http://stackoverflow.com\n" A: It seems you need this gem reverse_markdown Transform existing html into markdown in a simple way, for example if you want to import existings tags into your markdown based application. html2markdown Simple html to Markdown ruby gem We love markdown, cause it is friendly to edit. So we want everything to be markdown uninitialized constant ApplicationHelper::Redcarpet Add require 'redcarpet' before module ApplicationHelper require 'redcarpet' module ApplicationHelper def markdown(text) Redcarpet.new(text).html_safe end end
{ "pile_set_name": "StackExchange" }
Q: Optimal number of connections in connection pool Currently we are using 4 cpu windows box with 8gb RAM with MySQL 5.x installed on same box. We are using Weblogic application server for our application. We are targeting for 200 concurrent users for our application (Obviously not for same module/screen). So what is optimal number of connections should we configured in connection pool (min and max number) (We are using weblogic AS' connection pooling mechanism) ? A: Did you really mean 200 concurrent users or just 200 logged in users? In most cases, a browser user is not going to be able to do more than 1 page request per second. So, 200 users translates into 200 transactions per second. That is a pretty high number for most applications. Regardless, as an example, let's go with 200 transactions per second. Say each front end (browser) tx takes 0.5 seconds to complete and of the 0.5 seconds, 0.25 are spent in the database. So, you would need 0.5 * 200, or 100 connections in the WebLogic thead pool and 0.25 * 200 = 50 connections in the DB connection pool. To be safe, I would set the max thread pool sizes to at least 25% larger than you expect to allow for spikes in load. The minimums can be a small fraction of the max, but the tradeoff is that it could take longer for some users because a new connection would have to be created. In this case, 50 - 100 connections is not that many for a DB so that's probably a good starting number. Note, that to figure out what your average transaction response times are, along with your average DB query time, you are going to have to do a performance test because your times at load are probably not going to be the times you see with a single user. A: There is a very simple answer to this question: The number of connections in the connection pool should be equal the number of the exec threads configured in WebLogic. The rationale is very simple: If the number of the connections is less than the number of threads, some of the thread maybe waiting for a connection thus making the connection pool a bottleneck. So, it should be equal at least the number the exec threads (thread pool size). A: Sizing connection pool is not a trivial thing to do. You basically need: metrics to investigate the connection usage failover mechanisms for when there is no connection available FlexyPool aims to aid you figuring our the right connection pool size. You might check the following articles: FlexyPool, reactive connection pooling Professional Connection Pool Sizing The simple scalability equation
{ "pile_set_name": "StackExchange" }
Q: Using Mono in Spring to populate a Cloud Firestore entity I am using spring-cloud-gcp-starter-data-firestore for accessing Google Cloud Firestore in my Java Spring application. Currently, my entity looks like this: public class Subscription { public String userId; public String companyId; // other properties } However, I obtain the userId and companyId via a reactor.core.publisher.Mono in org.springframework.security.core.context.ReactiveSecurityContextHolder. How can I persist both properties which are nested inside Monos without resorting to Mono#block? A: I am now using Mono#zipWith to combine both Monos. Then I am creating the entity inside Mono#flatMap. service.getCompanyId() .zipWith(service.getUserId()) .flatMap(objects -> createEntity(objects.getT1(), objects.getT2()))
{ "pile_set_name": "StackExchange" }
Q: Spring Boot 2.0, H2, Unable to start app on existing H2 DB file I am in the process of migrating my application from Spring Boot 1.4.x to 2.0.0. In our development environment we run an H2 on file db, as shown in the debug log below. I can run the app with ddl-auto: create with an in MEM db, but when trying to work against my existing H2 file, I get the following error: 14:59:21.440 [] [] [main] DEBUG org.hibernate.loader.collection.plan.CollectionLoader - Static select for collection com.lmig.cortex.domain.entities.EmrProvisioning.associatedBuckets: select associated0_.emr_provisioning_id as emr_prov1_26_0_, associated0_.bucket_name as bucket_n2_26_0_, associated0_.is_ro as is_ro3_26_0_ from emr_associated_buckets associated0_ where associated0_.emr_provisioning_id=? 14:59:21.502 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - HikariPool-1 - configuration: 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - allowPoolSuspension.............false 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - autoCommit......................true 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - catalog.........................none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - connectionInitSql...............none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - connectionTestQuery.............none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - connectionTimeout...............30000 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSource......................none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSourceClassName.............none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSourceJNDI..................none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - dataSourceProperties............{password=<masked>} 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - driverClassName................."org.h2.Driver" 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - healthCheckProperties...........{} 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - healthCheckRegistry.............none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - idleTimeout.....................600000 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - initializationFailFast..........true 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - initializationFailTimeout.......1 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - isolateInternalQueries..........false 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - jdbc4ConnectionTest.............false 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - jdbcUrl.........................jdbc:h2:file:~/API;FILE_LOCK=FS;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - leakDetectionThreshold..........0 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - maxLifetime.....................1800000 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - maximumPoolSize.................10 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - metricRegistry..................none 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - metricsTrackerFactory...........com.zaxxer.hikari.metrics.micrometer.MicrometerMetricsTrackerFactory@1da5c19d 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - minimumIdle.....................10 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - password........................<masked> 14:59:21.503 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - poolName........................"HikariPool-1" 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - readOnly........................false 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - registerMbeans..................false 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutor...............none 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - scheduledExecutorService........internal 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - schema..........................none 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - threadFactory...................internal 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - transactionIsolation............default 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - username........................"sa" 14:59:21.504 [] [] [main] DEBUG com.zaxxer.hikari.HikariConfig - validationTimeout...............5000 14:59:21.504 [] [] [main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting... 14:59:21.530 [] [] [main] DEBUG com.zaxxer.hikari.pool.PoolBase - HikariPool-1 - Failed to create/setup connection: Constraint "FK5FKLEKY5P9R43SW8TI8CRLYXG" already exists; SQL statement: Here is how my config looks that fails: datasource: url: jdbc:h2:file:~/API;FILE_LOCK=FS;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL driver-class-name: org.h2.Driver username: sa password: continue-on-error: true jpa: database-platform: H2 hibernate: ddl-auto: update h2: console: enabled: true Additional Info: I can delete my h2 DB files, run the app, which generates new DB files. Everything is good and I can re-run the app without problem. I delete these new files, move the old files back. Same problem. Is there a place in these files where metadata about actions/updates that have been performed? Maybe I could tweak it? A: From Spring Boot 1.4.7 to 2.0.0, H2 upgrades from 1.4.196 to 1.4.197. It's difficult to determine which one, without having your h2 files, but one of the item in the long changelog list from 1.4.196 to 1.4.197 is the cause of your problem. If you want to keep your data, one solution would be to export them as SQL statements (see How in H2DB get sql dump like in MySql?) and reimport them with H2 1.4.197.
{ "pile_set_name": "StackExchange" }
Q: Down-voting Stolen Answers etiquette There have been a few times where I have come across a question with a wrong or incomplete answer, provided a correct answer and then had the original answerer edit/correct/expand their answer to match mine. If this is done quickly enough the stolen answer often gets the up-votes (it was answered earlier) and sometimes is marked as the correct answer (which at that point, it is). I am not against people correcting wrong answers (especially little mistakes) or making some revisions. Nor am I against the idea of up-voting multiple correct answers - although I rarely do it when there are duplicate answers, I just up-vote the one that got there first. All that to say, what is the general etiquette when you have had your answer stolen? I could leave a comment but that would tend to make me look like a petty jerk. I could down-vote the answer, but the answer is now correct so I'm really down-voting the user which may feel good to me, but be misleading to other users. Or I could just suck it up, be irritated, delete my "duplicate" answer and move on - this seems like the most mature, if least satisfying, response. Perhaps there is a middle ground or precedent that I am unaware of for these types of situations? A: I find this happens rarely, rarely enough for me to grit my teeth and move on. A: Oh it depends on where you live (tag) in SE. In some lower population tags, the competition can be rather intensive. However, the only professional approach would be to move on. Due to the grace period, it is a lost cause for you to pursue any action. (Even after deleting your competing answer, any 10k user can see it). I reckon if you are concerned more about rep than correct answers, it is time to move out of the site for a while and breathe some fresh air. Your answer has been borg-ed and it is now part of the SE collective, even if you are not attached to it.
{ "pile_set_name": "StackExchange" }
Q: How to print server-side with asp.net mvc I am new to asp.net and to programming altogether. I have an asp.net mvc web app, that is hosted on Azure. Basically it is for a store where different salesmen make sales and enter the information on the site. I want that after each sale is saved that one computer that is attached to a printer to print invoice. the question is how can I achieve that with server-side printing. how can i get the server to talk to one computer, when it is hosted in the cloud? A: You need to create api method in your web app that return new orders, after that you need to create a sub programm that request your api method for orders from web app and send them to print. Run sub programm on customer machine with printer.
{ "pile_set_name": "StackExchange" }
Q: jquery help on displaying values in a textbox In my application the user opens up a grid and selects an option. After the user selects the option if they click on the "Add question" button then it will add a new row in the table showing the option value in the textbox. Now lets say the user changes their mind and wants in the table row they have added they wanted to change their option value, the user can open the grid by clicking on the "Open Grid" link within the table row and select another option. The only problem is that the option they have chosen should be displayed in the textbox with in the table row but it isn't, instead it appears on the top textbox where the user originally selects an option. So how can I get it so that if the user changes an option within a table row, that the value is displayed in the textbox within the row and not the textbox in top? Steps to follow in my fiddle to help you: Open the grid and select option "3" click on "Add Question", you can see a new row has been added showing the option you have chosen in the textbox Now in the new row you have added click on the "Open Grid" link and select option "5". Now as you can see the text box in the table row still states "3" but if you look at the textbox on top, it shows "5". The textbox on top should not change to "5", it should be the textbox with in the table row. Use the jsfiddle so you can see what I mean and you can use it to test your ideas, click here A: First of all, you don't have to hide a set of matched elements after fading them out. Referring to: $('body').on('click', function() { $('#optionTypeTbl').fadeOut('slow'); $('#optionTypeTbl').hide(); }); Then I personally think the code could be better. You basically have the options table as a fixed element. But you actually could also remove it as it ends fading, of course still having it in a variable within your script, and append it as the user clicks on [Open Grid] to somewhere appropriate. (I still haven't gone through your entire code so I can't provide a sample right away. Give me some time on that.) Then, instead of using $('#optionTypeTbl input').click(function() { $(".gridBtns").removeClass("gridBtnsOn"); $(this).addClass("gridBtnsOn"); // THIS FOLLOWING LINE $('.box INPUT').val($(this).val()); $('#optionTypeTbl').hide(); }); since you have now made your options table a child of the parent of the clicked [Open Grid] link, you can refer to its parents by using closest like this: $( this ).closest( 'tr' ).find( '.box input' ).val( $( this ).val( ) ); To be honest, I couldn't solve your problem without changing great parts of your behavior. I'd need a little time to fix you my version of the code. EDITH: Okay, so I've worked on your fiddle and came up with a working snippet. Here you go!
{ "pile_set_name": "StackExchange" }
Q: Insert Performance Benchmarks It would be extremely useful to have some idea of expected performance benchmarks for inserts in a postgresql database. Typically the type of answers one would get on this are vague, and in many ways rightly so. For example, answers could range from every database is different, to it depends on the number of indexes/columns, to hardware makes a big difference, to db tuning makes a big difference etc. MY goal is to know the general guidelines of insert performance, roughly at an equivalent level as when an experienced SQL Developer's intuition says "this seems slow, I should try to optimize this". Let me illustrate, someone could ask how much does it cost to buy a house? We answer, expensive! And there are many factors that go into the price such as size of the house and location in the country. BUT, to the person asking the question, they might think $20,000 is a lot of money so houses must cost about that much. Saying it's expensive and there are a lot of variables obviously doesn't help the person asking the question much. It would be MUCH more helpful for someone to say, in general the "normal" cost of houses ranges from $100K-$1M, the average middle-class family can afford a house between $200K and $500K, and a normal cost per square foot is $100/square foot. All that to say I'm looking for ballpark performance benchmarks on inserts for the following factors Inserting 1000, 10000, 100000 rows into average table size of 15 columns. Rough effect of every additional 5 columns added to the table Rough effect of each index on the table Effect of special types of indexes Any other ideas that people have I'm fine with gut feel answers on these if you are an experienced postgresql performance tuner. A: You cannot get a meaningful figure here for the list of conditions you specified, because you do not even list the types of conditions that would have a profound effect on the speed of the INSERT command: Hardware capabilities: CPU speed + number of cores storage speed memory speed and size Cluster architecture, in case the batch is huge and can cross over Execution scenario: text batch, with pre-generated inserts one-by-one direct stream-based insert insert via a specific driver, like an ORM In addition, the insert speed can be: maintained (consistent or average) speed single-operation speed, i.e. for a single batch execution You can always find a combination of such criteria so bad you would be struggling to do 100 inserts a second, and on the other side it is possible to go over 1m of inserts in a properly set up environment and execution plan. So you will find the speed of your implementation somewhere in between, but given the known conditions, the speed will be 42 :)
{ "pile_set_name": "StackExchange" }
Q: router deprecated is not found in angular 2 package Recently i ran npm install command in my angular2 project directory, but it didn't install router-deprecated under my angular package. Has it been omitted from recent release? If yes, where can i find RouterOutlet class? A: You need to add it in your config '@angular/router-deprecated': { main: 'router-deprecated.umd.js', defaultExtension: 'js' }, or like shown in Angular2 router-deprecated dependencies not being loaded
{ "pile_set_name": "StackExchange" }
Q: Enum binding with converter I have Languages enum. And My Model.Translations is representing different languages translations: public ObservableCollection<LanguageValue> Translations { get; set; } public class LanguageValue { public Language Key { get; set; } public string Value { get; set; } } I want my view to have label - textbox list for each item in Translations. But in Label I want to have something like "Caption ({0})", where parameter is Language name (enum to string representation). This text itself is coming from Resources. Something like: <ItemsControl ItemsSource="{Binding Path=Translations}"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid Margin="5,2,5,2"> <Grid.ColumnDefinitions> <ColumnDefinition Width="30*"/> <ColumnDefinition Width="70*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" x:Name="ItemLabel" VerticalAlignment="Center" Text="{Binding Path=Key, Converter=languageConverter, ConverterParameter={x:Static res:Resources.lblCaption}}" /> <TextBox Grid.Column="1" x:Name="ItemText" VerticalAlignment="Center" Text="{Binding Path=Value, Mode=TwoWay}" /> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> My LanguageConverter: [ValueConversion(typeof(Language), typeof(string))] public class LanguageToDisplayConverter : IValueConverter { public object Convert(object value, Type t, object parameter, CultureInfo culture) { return string.Format(parameter.ToString(), ((Language)value).ToString()); } public object ConvertBack(object value, Type t, object parameter, CultureInfo culture) { //I guess I don't need this anyway? return null; } } But I've got error: The TypeConverter for "IValueConverter" does not support converting from a string. What is wrong? A: you should declare your converter as a resource (in a Window, or app-wide in App.xaml): <Window.Resources> <views:LanguageToDisplayConverter x:Key="languageConverter"/> </Window.Resources> and use accordingly: Text="{Binding Path=Key, Converter={StaticResource languageConverter}, ... the error "The TypeConverter for "IValueConverter" does not support converting from a string" indicates that wpf didn't recognize string "languageConverter" as a converter the same effect can be also achieved by using StringFormat property of Binding, without converter: Text="{Binding Path=Key, StringFormat={x:Static res:Resources.lblCaption}}"
{ "pile_set_name": "StackExchange" }
Q: How to correctly use a class implemented in C++/CLI as a data source for data binding in .net? I defined an abstract class in VC++ like this: public ref class AbstractFoo abstract { public: virtual property String^ Bar { virtual String^ get() = 0; } // More stuff }; And I have multiple concrete classes like this: public ref class ConcreteFoo : AbstractFoo { public: property String^ Bar { virtual String^ get() override; } // more } I now want to select one of several AbstractFoo implementations in a ComboBox in a C# application. So, I clicked the small arrow on the combo box and checked "Use Data Bound items". I then try to create a new data source with the AbstractFoo type. When I then click Finish, I get: Error using the dropdown: Object reference not set to an instance of an object. When I close the dialog box, VS exits. This also happens when I use the ConcreteFoo. For now, the only working solution I could come up with was to define a class in C# like this: internal sealed class FooWrapper { private readonly AbstractFoo _foo; internal FooWrapper(AbstractFoo foo) { _foo = foo; } public String DisplayName { get { return _foo.Bar; } } public static implicit operator AbstractFoo(FooWrapper w) { return w._foo; } } And then add these FooWrappers and use the implicit conversion to get the AbstractFoos back. Is this really the only way or did I declare something wrong where VS chokes at? EDIT: At the time the GUI is created, the ConcreteFoo implementations already exist. A: I investigated on this some more, and I found the cause for this problem. To my current knowledge, there is no solution but the workaround stated above. It has to do with the managed / unmanaged interop. I am still bound to VS2010 in this project, so I do not know if this is just a bug in there or if it is a misconfiguration of things by me. Here is how I reproduced the behaviour: First, I created a C++/CLI class library with a very simple abstract and concrete class (let's call them AbstractThing and ConcreteThing for now). I then created a simple C# Windows Forms application, containing only a combobox which is bound to a binding source with the AbstractThing type. This worked. I then added the dependencies to the unmanaged library as I always do: Specifying the include directory of the unmanaged library as an additional include directory, the directories which contain unmanaged.lib and unmanaged.dll for both debug and release modes, and add unmanaged.lib as an additional library. I then added a post-build command in the C# application that copies the appropriate unmanaged.dll into the build directory after a successful build. Recreating the binding then still worked. Now, on to the game-breaker: As soon as I added an include to the unmanaged library like #include <unmanaged.h> I got the above error and VS exited. To bring matters to a head, I then created such a wrapper as stated above, which worked at first, but led to the next strange error: When I re-entered the GUI designer, I got an error page that my managed/unmanaged interop DLL (the one containing AbstractThing and ConcreteThing) could not be found. The case is: .net's Data Binding analyzes the classes for public properties, and if any of them happens to be of a type that is interoperating with unmanaged stuff, things go crazy. I believe that the GUI designer and VS looks for the dependent unmanaged DLLs in the wrong directory. So, the only feasible thing is to write a wrapper and hide the interop stuff from the data binding by doing the extraction explicitly with an internal property or a method. So, this wrapper for the example AbstractThing class now works: internal sealed class ThingWrapper { private readonly AbstractThing _thing; internal ThingWrapper(AbstractThing thing) { _thing = thing; } public String DisplayName { get { return _thing.SomeStringProperty; } } internal AbstractThing Thing { get { return _thing; } } } Making internal AbstractThing Thing property public causes the designer to fail to correctly load, so one cannot use the ValueMember property of the binding source. The extraction must be done manually as of AbstractThing theThing = ((ThingWrapper) theComboBox.SelectedItem).Thing;
{ "pile_set_name": "StackExchange" }
Q: Checking nested property that can be null I've the following data in my collection: { colour: { r: 0, g: 0, b: 0 }}, { colour: null }, How can I find all the documents that have colour == null or color.r between some values? I've tried .find({ where: { $or: [{colour: null}, {"colour.r": {$gt: 0, $lt: 100}}]}}) but of course this gives me cannot read property 'r' of null for null rows. A: Use $where only if there is no other way to express your query db.test.find({$or: [{"colour": null}, {"colour.r": {$gt: 0, $lt: 100}}]})
{ "pile_set_name": "StackExchange" }
Q: How to set a specific dimension of a Button object in Java Swing? I have this simple Java Swing test application that show an upper label and under this label a button: package com.techub.exeute; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingConstants; import org.jdesktop.application.SingleFrameApplication; public class Main extends SingleFrameApplication{ public static void main(String[] args) { Main a = new Main(); a.startup(); } @Override protected void startup() { JFrame frame = new JFrame("FrameDemo"); frame.setMinimumSize(new Dimension(800, 400)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER); myLabel.setFont(new Font("Serif", Font.BOLD, 22)); myLabel.setBackground(Color.RED); myLabel.setOpaque(true); myLabel.setPreferredSize(new Dimension(100, 80)); frame.getContentPane().add(myLabel, BorderLayout.NORTH); Button myButton = new Button("Click Me !!!"); myButton.setMaximumSize(new Dimension(50, 25)); frame.getContentPane().add(myButton, BorderLayout.CENTER); //Display the window. frame.pack(); frame.setVisible(true); } } The button is in the BorderLayout.CENTER position. The problem is that this button occupies all available space in the CENTER position also if I have set the Maximum Size property with a Dimension object. What am I wrong? What can I do to create a button having specific dimension? A: You're currently telling Java to place the button in the center of your BorderLayout. Java then thinks that you want the entire area filled with this button. If you want to place a normal sized button in the center of your BorderLayout, add the button to a new JPanel and place the JPanel inside BorderLayout.CENTER. Doing this, you're telling Java to fill out BorderLayout.CENTER with your JPanel. The elements that you place inside this JPanel will appear normal, because these elements are not getting "stretched" because of your BorderLayout - the JPanel is.
{ "pile_set_name": "StackExchange" }
Q: How to reload a clojure file in REPL What is the preferred way of reloading functions defined in a Clojure file without having to restart the REPL. Right now, in order to use the updated file I have to: edit src/foo/bar.clj close the REPL open the REPL (load-file "src/foo/bar.clj") (use 'foo.bar) In addition, (use 'foo.bar :reload-all) does not result in required effect, which is evaluating the modified bodies of functions and returning new values, instead of behaving as the source haven't changed at all. Documentation: load-file use A: Or (use 'your.namespace :reload) A: There is also an alternative like using tools.namespace, it's pretty efficient: user=> (use '[clojure.tools.namespace.repl :only (refresh)]) user=> (refresh) :reloading (namespace.app) :ok A: Reloading Clojure code using (require … :reload) and :reload-all is very problematic: If you modify two namespaces which depend on each other, you must remember to reload them in the correct order to avoid compilation errors. If you remove definitions from a source file and then reload it, those definitions are still available in memory. If other code depends on those definitions, it will continue to work but will break the next time you restart the JVM. If the reloaded namespace contains defmulti, you must also reload all of the associated defmethod expressions. If the reloaded namespace contains defprotocol, you must also reload any records or types implementing that protocol and replace any existing instances of those records/types with new instances. If the reloaded namespace contains macros, you must also reload any namespaces which use those macros. If the running program contains functions which close over values in the reloaded namespace, those closed-over values are not updated. (This is common in web applications which construct the "handler stack" as a composition of functions.) The clojure.tools.namespace library improves the situation significantly. It provides an easy refresh function that does smart reloading based on a dependency graph of the namespaces. myapp.web=> (require '[clojure.tools.namespace.repl :refer [refresh]]) nil myapp.web=> (refresh) :reloading (myapp.web) :ok Unfortunately reloading a second time will fail if the namespace in which you referenced the refresh function changed. This is due to the fact that tools.namespace destroys the current version of the namespace before loading the new code. myapp.web=> (refresh) CompilerException java.lang.RuntimeException: Unable to resolve symbol: refresh in this context, compiling:(/private/var/folders/ks/d6qbfg2s6l1bcg6ws_6bq4600000gn/T/form-init819543191440017519.clj:1:1) You could use the fully qualified var name as a workaround for this problem but personally I prefer not having to type that out on each refresh. Another problem with the above is that after reloading the main namespace the standard REPL helper functions (like doc and source) are no longer referenced there. To solve these issues I prefer to create an actual source file for the user namespace so that it can be reliably reloaded. I put the source file in ~/.lein/src/user.clj but you can place in anywhere. The file should require the refresh function in the top ns declaration like this: (ns user (:require [clojure.tools.namespace.repl :refer [refresh]])) You can setup a leiningen user profile in ~/.lein/profiles.clj so that location you put the file in is added to the class path. The profile should look something like this: {:user {:dependencies [[org.clojure/tools.namespace "0.2.7"]] :repl-options { :init-ns user } :source-paths ["/Users/me/.lein/src"]}} Note that I set the user namespace as the entry point when launching the REPL. This ensures that the REPL helper functions get referenced in the user namespace instead of the main namespace of your application. That way they won’t get lost unless you alter the source file we just created. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Why are there no branes in heterotic string theory? Why does the heterotic string (or heterotic supergravity) have no brane solutions? According to David Tong's notes: the heterotic string doesn’t have (finite energy) D-branes. This is due to an inconsistency in any attempt to reflect left-moving modes into right- moving modes. I know that the heterotic string does not have the same structure in the left- moving and right- moving sectors (whether one uses the Green Schwarz or the RNS formulation). But why does that imply no branes? BPS-brane solutions are obtained by starting from the supersymmetry transformations of the fields and solving them in a zero-fermion background. This leads to stable solutions if they exist. Why would such an approach not work with the heterotic supergravity action? EDIT: It seems that there is a simple qualitative explanation (source). Specifically, a heterotic string must necessarily be closed, and unlike other string theories which have closed strings and open strings (which end on D-branes) there are no heterotic open strings of type $E_8 \times E_8$ (cf. this paper, which I haven't yet read) and so no D-branes. A: The systematic way to deduce the brane content of string/M-theory is to classify the WZW-terms ($\kappa$-symmetry terms) for the would-be Green-Schwarz action functionals for the possible super $p$-branes (the "brane scan" or "brane bouquet"). Doing this for the would-be D-branes for the heterotic string, one proves that the required non-trivial cocycles don't exist. This is shown in C. Chrysso‌malakos, José de Azcárraga, J. M. Izquierdo and C. Pérez Bueno, "The geometry of branes and extended superspaces", Nuclear Physics B Volume 567, Issues 1–2, 14 February 2000, Pages 293–330 (arXiv:hep-th/9904137) see footnote 14 there, a side remark in the corresponding computation which finds the D-branes in type IIA this way. The analogous computation classifying the type IIB branes is in section 2 of Makoto Sakaguchi, "IIB-Branes and New Spacetime Superalgebras", JHEP 0004 (2000) 019 (arXiv:hep-th/9909143). One may organize these computations in a classifying "bouquet" of super Lie $n$-algebra extensions, which shows the brane spectrum in string/M-theory systematically from super Lie $n$-algebra cohomology: Here each item denotes a super Lie $n$-algebra and each edge denotes a Lie $n$-algebra extension classified by the relevant super Lie $n$-algebra cocycle needed for the Green-Schwarz sigma-model. Moreover, for every edge the brane species that it points to may end on the brane species that it starts at. The un-boxed items are those branes appearing already in the "old brane scan", while the boxed items are those branes appearing only as one generalized from super Lie algebras to super Lie $n$-algebras. Since there are no relevant extensions over the super Lie 2-algebra coresponding to the heterotic string, there are no branes that it may end on, in contrast to the type II strings. For more see Domenico Fiorenza, Hisham Sati, Urs Schreiber, "Super Lie $n$-algebra extensions, higher WZW models and super $p$-branes with tensor multiplet fields", International Journal of Geometric Methods in Modern Physics, Volume 12, Issue 02 (2015) 1550018 (arXiv:1308.5264)
{ "pile_set_name": "StackExchange" }
Q: Should I be concerned about my 1-year-old and her mother moving in with a man I've never met? About 8 months ago, I and the mother of my 1-year-old child separated. Everything was mutual and amicable and we have a reasonably good relationship now - if a bit awkward. This weekend, when I returned my daughter to her mother, she told me that she's moving in with her boyfriend (of 3 months or so). I have a couple of concerns about this however. Her new boyfriend is (I'm told) a policeman, and so theoretically is safe to be around children. I don't know this man (even his name) and I feel like I ought to if my daughter is living with him and at least be able to verify his identity. Whilst I can't dictate how quickly their relationship moves along, I'm concerned that my child's mother has moved in with her new boyfriend so quickly so that she can leave her mother's house. I'm concerned about my child being exposed to someone that she gets used to only for them to break up. Are my concerns valid? Should and how should I address them? A: I suggest you invite the guy out for a beer to get to know him. Make it clear that you are not jealous, that you wish them well, and that the only thing you care about his how he treats your daughter and her mother. Your concern for her mother is exactly that, concern for your daughter's mother. Not concern for your ex. There's a lot of crappy stuff in this world and your daughter having another person who cares for her and looks out for her is a good thing. A: I don't think there's anything you can do about this. Imagine it was the other way around - would you let her tell you who you can live with? To 1: Just because he's a policeman doesn't mean he's safe for kids to be around. But really shouldn't you look at it from the other end? Shouldn't you assume that he's okay until he gives you reason for suspicion? The vast majority of people aren't child abusers. Your ex chose you, which was hopefully a good choice. Doesn't that say something about the type of person she likes? Do you think she'd put her BF before the well-being of your daughter? To 2: I wouldn't worry about this, especially at your daughters age. When she gets older, she might get attached to some of her mothers BFs, but unless one becomes a surrogate father figure, I doubt she'll be permanently hurt by a separation. I'm a divorce kid and never minded the string of BFs and GFs much, though I was older at the time of separation (school age). I'm also happily married - and have been for longer than my parents were - so I didn't somehow internalize that relationships must always break. My suggestion would be to give your ex some time and then suggest an activity with all of you - maybe take your daughter to the zoo for her next birthday and invite your ex and her BF to come along. Then do some small talk with the BF to get to know him a bit. Maybe repeat if it isn't too awkward. A: I agree with those who have advocated communication. That's the only option open to you at this point. Are you being unreasonable? About your daughter living with a stranger, no, I don't think so. The way to deal with that is to get to know this person. Invite the three of them out to dinner and get to know him. If it goes well, do that from time to time; as your daughter grows up, you'll be seeing much more of him if you attend your daughter's functions. If the relationship dissolves and a new relationship forms quickly, you may have a point. But you don't have a choice right now and this is only one data point in addition to your own separation. Are you being unreasonable about your concern for your wife? I don't know, but I can say you're on very shaky ground here. It depends on why the two of you separated, what kind of person she is, whether you have reason to distrust her motives, etc. If she was reasonably trustworthy while you were married, and you trust her as the mother of your child, then trust her here as well. What decisions she makes about her personal life is no longer your business unless you believe it will harm the child. It sounds right now like you have no reason at all to raise any objection. This is hard. if you only have verbal agreements about custody, you might want to consider firming them up (i.e. hiring a lawyer and getting the court to approve your custody arrangement) before it possibly becomes an issue.
{ "pile_set_name": "StackExchange" }
Q: rsync list of specific local files in 1 step I'm working on a web application where a user uploads a list of files, which should then be immediately rsynced to a remote server. I have a list of all the local files that need to be rsynced, but they will be mixed in with other files that I do not want rsynced every time. I know rsync will only send the changed files, but this directory structure and contents will grow very large over time and the delay would not be acceptable. I know that doing a remote rsync, I can specify a list of remote files, i.e... rsync "host:/path/to/file1 /path/to/file2 /path/to/file3" ... but that does not work once I remove "host:" and try to specify the files locally. I also know I can use --files-from, but that would require me to create a file ahead of time with a list of files that I want to rsync (and then delete it afterwards). I think it'd be cleaner to just effectively say "rsync these 4 specific files to this remote server", but I can't seem to get that to work. Is there any way to do what I'm trying to accomplish, or do I have to resort to creating a tmp file with a list in it? Thanks! A: You should be able to list the files similar to the example you gave. I did this on my machine to copy 2 specific files from a directory with many other files present. rsync test.sql test2.cpp myUser@myHost:path/to/files/synced/
{ "pile_set_name": "StackExchange" }
Q: Set of $n$ numbers which has no two elements whose sum is an another I want a set $S = \{ S_1, ..., S_n \} $ of $n$ numbers, which satisfies the condition $S_i + S_j ∉ S$, where $i, j = 1 ... n$. How could I compute a solution set for it? In other words, the set must satisfy that the sum any two elements is not an element of the set. A: Take any set of odd numbers. $\hspace{0pt}$ A: Take any sequence $S_1, S_2, \ldots$ such that $S_1 > 0$ and $S_n > 2 S_{n-1}$ for $n \ge 2$. A: Let $m$ be any integer at least 2. Then for any nonzero $\ell \in \mathbb{Z}/m\mathbb{Z}$ let $S = \{mk + \ell; k = 1,2,\ldots, n\}$. Taking powers of $m$ would work too.
{ "pile_set_name": "StackExchange" }
Q: MPDF - Start page numbering from number 10 on the first sheet I have an application and need to print a document using the MPDF class, however necessary that the number of page start at number 43, 44, 45 and so on. And not from the 1, 2, 3 ... I managed to start from the 43 but only jumping a leaf. I can not insert a pagebreak. Thanks. Below is my code. $mpdf = new mPDF(); $mpdf->setFooter("{PAGENO}"); $numero_paginas = "{nb}"; $mpdf->SetHTMLHeader(' <table> <tr> <td> <img src="img/cabecalho.png" /> </td> </tr> </table> <hr> '); $mpdf->SetHTMLFooter(''); $mpdf->WriteHTML(' <style type="text/css"> body{ font-family:Arial, Times New Roman, sans-serif; font-size:10px; } </style> ' . $corpo_documento . ''); $mpdf->Output(); exit; A: From mPDF manual on page numbers: If you want to set page numbering characteristics from the first page onwards, you should explicitly add the first page of the document using AddPage(). Note that this is normally not required, as mPDF creates a new first page automatically if required when first using WriteHTML(). So, call AddPage() after setting the footer like this: $mpdf = new mPDF(); $mpdf->setFooter('{PAGENO}'); $mpdf->AddPage('', '', 43);
{ "pile_set_name": "StackExchange" }
Q: Hand-over-hand locking with Rust I'm trying to write an implementation of union-find in Rust. This is famously very simple to implement in languages like C, while still having a complex run time analysis. I'm having trouble getting Rust's mutex semantics to allow iterative hand-over-hand locking. Here's how I got where I am now. First, this is a very simple implementation of part of the structure I want in C: #include <stdlib.h> struct node { struct node * parent; }; struct node * create(struct node * parent) { struct node * ans = malloc(sizeof(struct node)); ans->parent = parent; return ans; } struct node * find_root(struct node * x) { while (x->parent) { x = x->parent; } return x; } int main() { struct node * foo = create(NULL); struct node * bar = create(foo); struct node * baz = create(bar); baz->parent = find_root(bar); } Note that the structure of the pointers is that of an inverted tree; multiple pointers may point at a single location, and there are no cycles. At this point, there is no path compression. Here is a Rust translation. I chose to use Rust's reference-counted pointer type to support the inverted tree type I referenced above. Note that this implementation is much more verbose, possibly due to the increased safety that Rust offers, but possibly due to my inexperience with Rust. use std::rc::Rc; struct Node { parent: Option<Rc<Node>> } fn create(parent: Option<Rc<Node>>) -> Node { Node {parent: parent.clone()} } fn find_root(x: Rc<Node>) -> Rc<Node> { let mut ans = x.clone(); while ans.parent.is_some() { ans = ans.parent.clone().unwrap(); } ans } fn main() { let foo = Rc::new(create(None)); let bar = Rc::new(create(Some(foo.clone()))); let mut prebaz = create(Some(bar.clone())); prebaz.parent = Some(find_root(bar.clone())); } Path compression re-parents each node along a path to the root every time find_root is called. To add this feature to the C code, only two new small functions are needed: void change_root(struct node * x, struct node * root) { while (x) { struct node * tmp = x->parent; x->parent = root; x = tmp; } } struct node * root(struct node * x) { struct node * ans = find_root(x); change_root(x, ans); return ans; } The function change_root does all the re-parenting, while the function root is just a wrapper to use the results of find_root to re-parent the nodes on the path to the root. In order to do this in Rust, I decided I would have to use a Mutex rather than just a reference counted pointer, since the Rc interface only allows mutable access by copy-on-write when more than one pointer to the item is live. As a result, all of the code would have to change. Before even getting to the path compression part, I got hung up on find_root: use std::sync::{Mutex,Arc}; struct Node { parent: Option<Arc<Mutex<Node>>> } fn create(parent: Option<Arc<Mutex<Node>>>) -> Node { Node {parent: parent.clone()} } fn find_root(x: Arc<Mutex<Node>>) -> Arc<Mutex<Node>> { let mut ans = x.clone(); let mut inner = ans.lock(); while inner.parent.is_some() { ans = inner.parent.clone().unwrap(); inner = ans.lock(); } ans.clone() } This produces the error (with 0.12.0) error: cannot assign to `ans` because it is borrowed ans = inner.parent.clone().unwrap(); note: borrow of `ans` occurs here let mut inner = ans.lock(); What I think I need here is hand-over-hand locking. For the path A -> B -> C -> ..., I need to lock A, lock B, unlock A, lock C, unlock B, ... Of course, I could keep all of the locks open: lock A, lock B, lock C, ... unlock C, unlock B, unlock A, but this seems inefficient. However, Mutex does not offer unlock, and uses RAII instead. How can I achieve hand-over-hand locking in Rust without being able to directly call unlock? EDIT: As the comments noted, I could use Rc<RefCell<Node>> rather than Arc<Mutex<Node>>. Doing so leads to the same compiler error. For clarity about what I'm trying to avoid by using hand-over-hand locking, here is a RefCell version that compiles but used space linear in the length of the path. fn find_root(x: Rc<RefCell<Node>>) -> Rc<RefCell<Node>> { let mut inner : RefMut<Node> = x.borrow_mut(); if inner.parent.is_some() { find_root(inner.parent.clone().unwrap()) } else { x.clone() } } A: We can pretty easily do full hand-over-hand locking as we traverse this list using just a bit of unsafe, which is necessary to tell the borrow checker a small bit of insight that we are aware of, but that it can't know. But first, let's clearly formulate the problem: We want to traverse a linked list whose nodes are stored as Arc<Mutex<Node>> to get the last node in the list We need to lock each node in the list as we go along the way such that another concurrent traversal has to follow strictly behind us and cannot muck with our progress. Before we get into the nitty-gritty details, let's try to write the signature for this function: fn find_root(node: Arc<Mutex<Node>>) -> Arc<Mutex<Node>>; Now that we know our goal, we can start to get into the implementation - here's a first attempt: fn find_root(incoming: Arc<Mutex<Node>>) -> Arc<Mutex<Node>> { // We have to separate this from incoming since the lock must // be borrowed from incoming, not this local node. let mut node = incoming.clone(); let mut lock = incoming.lock(); // Could use while let but that leads to borrowing issues. while lock.parent.is_some() { node = lock.parent.as_ref().unwrap().clone(); // !! uh-oh !! lock = node.lock(); } node } If we try to compile this, rustc will error on the line marked !! uh-oh !!, telling us that we can't move out of node while lock still exists, since lock is borrowing node. This is not a spurious error! The data in lock might go away as soon as node does - it's only because we know that we can keep the data lock is pointing to valid and in the same memory location even if we move node that we can fix this. The key insight here is that the lifetime of data contained within an Arc is dynamic, and it is hard for the borrow checker to make the inferences we can about exactly how long data inside an Arc is valid. This happens every once in a while when writing rust; you have more knowledge about the lifetime and organization of your data than rustc, and you want to be able to express that knowledge to the compiler, effectively saying "trust me". Enter: unsafe - our way of telling the compiler that we know more than it, and it should allow us to inform it of the guarantees that we know but it doesn't. In this case, the guarantee is pretty simple - we are going to replace node while lock still exists, but we are not going to ensure that the data inside lock continues to be valid even though node goes away. To express this guarantee we can use mem::transmute, a function which allows us to reinterpret the type of any variable, by just using it to change the lifetime of the lock returned by node to be slightly longer than it actually is. To make sure we keep our promise, we are going to use another handoff variable to hold node while we reassign lock - even though this moves node (changing its address) and the borrow checker will be angry at us, we know it's ok since lock doesn't point at node, it points at data inside of node, whose address (in this case, since it's behind an Arc) will not change. Before we get to the solution, it's important to note that the trick we are using here is only valid because we are using an Arc. The borrow checker is warning us of a possibly serious error - if the Mutex was held inline and not in an Arc, this error would be a correct prevention of a use-after-free, where the MutexGuard held in lock would attempt to unlock a Mutex which has already been dropped, or at least moved to another memory location. use std::mem; use std::sync::{Arc, Mutex}; fn find_root(incoming: Arc<Mutex<Node>>) -> Arc<Mutex<Node>> { let mut node = incoming.clone(); let mut handoff_node; let mut lock = incoming.lock(); // Could use while let but that leads to borrowing issues. while lock.parent.is_some() { // Keep the data in node around by holding on to this `Arc`. handoff_node = node; node = lock.parent.as_ref().unwrap().clone(); // We are going to move out of node while this lock is still around, // but since we kept the data around it's ok. lock = unsafe { mem::transmute(node.lock()) }; } node } And, just like that, rustc is happy, and we have hand-over-hand locking, since the last lock is released only after we have acquired the new lock! There is one unanswered question in this implementation which I have not yet received an answer too, which is whether the drop of the old value and assignment of a new value to a variable is a guaranteed to be atomic - if not, there is a race condition where the old lock is released before the new lock is acquired in the assignment of lock. It's pretty trivial to work around this by just having another holdover_lock variable and moving the old lock into it before reassigning, then dropping it after reassigning lock. Hopefully this fully addresses your question and shows how unsafe can be used to work around "deficiencies" in the borrow checker when you really do know more. I would still like to want that the cases where you know more than the borrow checker are rare, and transmuting lifetimes is not "usual" behavior. Using Mutex in this way, as you can see, is pretty complex and you have to deal with many, many, possible sources of a race condition and I may not even have caught all of them! Unless you really need this structure to be accessible from many threads, it would probably be best to just use Rc and RefCell, if you need it, as this makes things much easier.
{ "pile_set_name": "StackExchange" }
Q: Regular expression with decimal and character I'm trying to write a regular expression that will accept the following: s#.# f#.# Where # can be an integer of any size (so really, a decimal preceded by s or f). I also need this to accept nothing else. So if it's something like: As#.# would not be accepted because there's an A before the s s#.#X would not be accepted because there's an X after the decimal. There will always be either an s or an f to start, then a number, a period, and another number. All those parts are required and the numbers can be any size and any number of integers. A: Try this regular expression: /^[sf]\d+\.\d+$/ Explanation ^ is an anchor that matches the start of the string. [sf] is a character class and means an s or an f. \d means a digit. + means one or more. \. matches a literal dot. $ is an anchor that matches the end of the string.
{ "pile_set_name": "StackExchange" }
Q: Unable to Delete Directories Older Than Three Days I need to delete all sub-directories that are older than three days. The below code should work but it isn't... for i in `find ~/web/smsng/ -maxdepth 1 -type d -mtime +3 -print`; do echo -e "Deleting directory $i";rm -rf $i; done Full ls-l listing of directory: (uiserver):u83749873:~/models/ndfd > ls -l total 1536 drwx---r-x 2 u83749873 ftpusers 12288 Apr 8 12:41 2016040816 drwx---r-x 2 u83749873 ftpusers 12288 Apr 8 13:41 2016040817 drwx---r-x 2 u83749873 ftpusers 12288 Apr 8 14:40 2016040818 drwx---r-x 2 u83749873 ftpusers 12288 Apr 8 15:41 2016040819 drwx---r-x 2 u83749873 ftpusers 12288 Apr 9 00:41 2016040904 drwx---r-x 2 u83749873 ftpusers 12288 Apr 9 01:41 2016040905 drwx---r-x 2 u83749873 ftpusers 12288 Apr 9 02:41 2016040906 drwx---r-x 2 u83749873 ftpusers 12288 Apr 10 03:41 2016040907 drwx---r-x 2 u83749873 ftpusers 12288 Apr 10 04:41 2016040907 drwx---r-x 2 u83749873 ftpusers 12288 Apr 11 07:41 2016040907 A: Change -mtime +3 to -mtime +2: for i in `find ~/web/smsng/ -maxdepth 1 -type d -mtime +2 -print`; do echo -e "Deleting directory $i" rm -rf $i done According to the find(1) man page: -mtime n File was last accessed n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. Other improvements There are some improvements you could make to your script to improve hardiness with regard to being able to process any possible file name. Currently, your script will fail to work if: Any directory has a space, tab, or newline character in it The $i variable starts with a hyphen (-) You can fix both these issues if if you write the script like so: find ~/web/smsng/ \ -maxdepth 1 -type d -mtime +2 \ -exec echo 'Deleting directory {}' \; \ -exec rm -rf -- {} \; Because it's never interpreted as an argument list by the shell, split-on-whitespace never happens. Because it's passed to rm with the option-terminating -- the filename can begin with a hyphen and not get interpreted as a flag to rm.
{ "pile_set_name": "StackExchange" }
Q: How to demonize face in a video What program can I use to turn a human face into a devil or demon face in a video easily? There are some examples on Youtube (1,2,3). Apparently, they have used a user-friendly and easy-to-use software for that. A: This definitely wasn't user-friendly or easy-to-use software, or at least not a one-click solution. The third video you posted is "the original" and I know I've seen it before. Probably some viral marketing scheme. The second one is a "ripoff", if you can say that, and my best guess is that you can use After Effects for it, like this guy. Turns out, there are a couple of tutorials on the very same subject, do a Google search for it.
{ "pile_set_name": "StackExchange" }
Q: Disable IntelliJ / RubyMine Spellchecking for Filenames? I may be way off base here, but RubyMine appears to be spellchecking my filenames: Problem is, I have spellchecking turned off. This occurs for some directory names as well, including simple names like "views". How do I disable this? A: It's not spellchecking, such underline indicates that there are errors inside this file.
{ "pile_set_name": "StackExchange" }
Q: Using arrays in SAS I've got a data file that has five test scores for 20 students. Each test score has its own passing grade of 68, 70, 72, 74, 76 respectively. I read in this data from a .dat file but need to calculate the number of tests passed by each student. This is fairly easy to do using if statements, but I need to utilize arrays here. So my code looks like data test_scores; infile '---------------------------------'; input t1 t2 t3 t4 t5; array test_scores{5} t1 t2 t3 t4 t5; do n=1 to 5; if tests[i] = This is where I am stuck. I realize I can say that if the index is 1 and test score is greater than 68, add to the accumulator variable tests_passed and then do for all 5 but that seems redundant and where I started with. Any help would be appreciated! A: Since your score cutoffs are evenly spaced, you could do: do n=1 to 5; if test_scores[n] >= 66 + 2 * n But that's not very extensible, so perhaps the better method is to have an array of cutoff scores: array pass_cutoff{5} 68 70 72 74 76; do n=1 to 5; if test_scores[n] >= pass_cutoff[n] This way, if a cutoff changes, you just update the array initialization, and everything still works.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap Tour, How do I force stop the auto start? I could really use help turning off the "auto start" function of Bootstrap Tour plugin for a webpage I am building. The tour itself works great. It hops from step to step as intended. BUT, the tour starts on It's own when a user views the page for the first time. The user can press "end tour" and the tour won't auto start anymore. But, I'd like to prevent the auto-start all together. I need your help to find a way (or a setting) to prevent the tour from auto-starting on it's own. I don't want the user to have to press "end tour"... They should only press "Start Tour" when they want the tour to start! See code below. Note, I left out the majority of the page's code because I didn't want to overwhelm you. Please help, how do I STOP the tour from auto-starting? <!-- Bootrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- Tour CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/css/bootstrap-tour.css"> <a id="MSL-initialize-tour"> START TOUR <span class="glyphicon glyphicon-play"></span> </a> <!-------- JQuery JS --------> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-------- Bootsrap JS --------> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-------- Bootsrap Tour JS --------> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/js/bootstrap-tour.js"></script> <!-------- Bootsrap Tour Steps --------> <script> // Instance the tour var tour = new Tour({ steps: [ { element: "#MSL-initialize-tour", placement: "bottom", title: "<span class='glyphicon glyphicon-star'></span> Welcome to MSL!", content: "Press 'next' to see page features." } ]}); tour.init(); tour.start(); $('#MSL-initialize-tour').click(function(){ tour.restart(); }); </script> A: You need to move tour.init(); tour.start(); inside of a function. Right now they are being called as soon as the Javascript is loaded. Here is a JSFiddle example You can see how init, start, and restart are all in the same function which is called when the user clicks the "Start Tour" button.
{ "pile_set_name": "StackExchange" }
Q: File explorer show nothing I'm using Eclipse Indigo, I'm root on my device. When I'm running application and looking at File explorer in eclipse I see nothing. (can't see folders at all) The windows is empty. What can I do? A: You need to select the device to see something either in logcat or in file explorer Window->show view -> other -> Android -> device -> you will get device icon in you eclipse. open that device to check what are the connected devices (emulators also) if you get the device for which you want to see either logcat or file explorer. in the list then select it if you dont find any list there then restart the device (same for emulators also) If this doesnt work then restart your eclipse and do these steps again.
{ "pile_set_name": "StackExchange" }
Q: How do I actually replace a resources (.resx) file in a running application for a .Net DLL? Here's my scenario: I have a .Net (3.5) DLL being referenced by an ASP.Net web application. One of the classes in the DLL has a .resx file containing an error message string that ultimately gets shown by the calling .aspx page. The DLL makes use of multiple namespaces, I've set the .resx file to the same namespace as the class that calls it, and the .resx file has the same folder location and filename as the class that uses is, postfixed with 'Resources': i.e. Class: ClassName.cs .resx: ClassNameResources.resx It reads the .resx string (which is compiled in the DLL as an embedded resource) without issue. The problem I'm having is trying to replace the error message string in the deployed web application - how do I actually do it? Can you point me at a guide? - the best I've found so far is this one, which says use regen.exe and al.exe, but the resulting .resources file doesn't get used because the error message doesn't change. At this stage I'm not trying to localize for any culture, I'm trying to modify the strings returned for the default culture. Thanks for any suggestions you can make :o) A: As Lasse V. Karlsen said above, resources files are not the right thing to use for what you want. Basically, the byte code for the class and the resources are compiled into an assembly, which is a single unit in the end. C# allows you to easily use the resources contained within the resource file through Properties.Resources.... So far so good. If you were localizing your application, you'd get another Assembly (DLL) which contains the localized resources. The internal mechanisms use that DLL to retrieve the resource data instead of your standard assembly. The fact that resources are actually stored within the assembly (use Reflector to see what I mean) makes it impossible to just put another resources file into the same folder for the new resources to be used. Resource files are not like configuration files, which are copied to the deployment folder (or to another location) and then loaded as external files. If you want to replace resources on the fly as you described, you'd have to use your own resource loading mechanism. I'm pretty sure that you can not use the built-in resource mechanisms for that.
{ "pile_set_name": "StackExchange" }
Q: Child div needs to overlap on its parent such that it gets parent's background color I have the below structure: <li style="border-left-color: green"> <div class="some icon"> <div class="another icon"> </div> </div> </li> I need to allow the div that has "some icon" overlap the left border of my li element such that the icon appears within the green color bar. Can the child div overlap on it's parent? A: Yes. Something like the following should work, however, your class names should not contain spaces: li { position: relative; height: // whatever your desired height is border-left: 20px solid green; } .some_icon { position: absolute; top: 0; left:-20px; // this should be the same as, or similar to, the li border width } Here's an example.
{ "pile_set_name": "StackExchange" }
Q: Populate from One Model to Another Using Mongoose/MongoDB in Node/Express Application I am struggling to understand the populate method in Mongoose, while having trouble populating fields from one Mongoose model to another. The first model Schema is: var MprnSchema = new mongoose.Schema({ mprNo: {type: Number, unique: true, required: true}, siteName: String, buildingNo: Number, streetAddress: String, secondAddress: String, townCity: String, postCode: String, supplier: String, siteContactName: String, siteContactNo: String, }); module.exports = mongoose.model("Mprn", MprnSchema); And another Schema is: var FaultSchema = new mongoose.Schema({ jobRef: Number, mprNo: Number, requestedDate: {type: Date, default: Date.now}, attendedDate: {type: Date, default: null}, siteDetails: {type: mongoose.Schema.Types.ObjectId, ref: 'Mprn'}, faultIssue: String, }); However, when I try to populate the 'siteDetails' with the contents of Mprn, I get [] when using thhe code below: Fault.find(reportQuery).populate('siteDetails', 'siteName postCode').exec((err, faultResults) => { if(err){ req.flash("error", err.message); res.redirect("/"); } console.log(faultResults); res.render("reportResults", { queryResults: faultResults }); }); The object passed to be rendered (queryResults) only contains the Fault data and NOT the 'siteDetails' that should be populated. I think the problem may be when I am using the Fault.Create() method in the first place, should I be saving a reference to the MPRN model at this point, so that the there is an Id to be referenced when populating? My samples collections are: Fault { "jobRef": 60000, "mprNo": 123456, "faultIssue": "Test" } Mprn { "mprNo": 123456, "siteName": "Smithson Gates", "buildingNo": 76, "streetAddress": "Garden Place", "secondAddress": "Greater Manchester", "townCity": "Salford", "postCode": "M5 3AP", "supplier": "test", "siteContactName": "Mr B Jones", "siteContactNo": "0161 000 0000" } A: Well you are using latest version of mongodb... So, You can try below $lookup aggregation... and the plus point of using this is you don't need to store _id of Mprn collection in the Fault... You can easily join both the collections with mprn number Fault.aggregate([ { "$match": reportQuery }, { "$lookup": { "from": Mprn.collection.name, "let": { "mprNo": "$mprNo" }, "pipeline": [ { "$match": { "$expr": { "$eq": [ "$mprNo", "$$mprNo" ] } } } ], "as": "siteDetails" }}, { "$unwind": "$siteDetails" } ])
{ "pile_set_name": "StackExchange" }
Q: Shifting hex value left and the most-significant bit should disappear (or lost) using Python I have hex values (8-bit length) which I want to shift to the left and the leading significant bit should disappear. But I did not find an easy way to do it. Here are some examples. h = hex(0xFF << 1) print h Output_1: 0x1fe h = hex(0xFF << 2) print h Output_2: 0x3fc h = hex(0xFF << 3) print h Output_3: 0x7f8 However, I am expecting the MSB should disappear and the hex value remains in 8-bit length. The expected output must be like this: Output_1: 0xfe Output_2: 0xfc Output_3: 0xf8 Can anyone please help me on this? A: Unfortunately, I did not get any reply for my ques. However, as a beginner, I came up with the below code: h = '0xFF' count = 0 for i in range(0, 8, 1): y = int(h, 16) count = count + (2**i) y = 255 - count ## 255 is decimal value of 0xFF print hex(y) Output: 0xfe 0xfc 0xf8 0xf0 0xe0 0xc0 0x80 0x0 This is the output, I was looking for.
{ "pile_set_name": "StackExchange" }
Q: time efficient key value store for fast lookup Let's state a collection of key/values. Key is an unsigned integer (0 - 2^32-1). Hense there are comparable. Value is few bytes fixed size. There are 4M items in the collection. Keys are not evenly spread in the key space i.e there is no way to predict hole size between two consecutive keys. This collection is created once and never modify after that, even if not prohibited. The aim is to lookup a value by its key. But if key is not found then the previous one (as in integer natural order) must be returned. I'm looking for a data-structure that can be mmap on disk which would be reasonably space efficient but most importantly very time efficient for the lookup function. There is no known pattern on how the keys are queried. A: Make a table with 2^22 entries to lookup the highest 22 bits of the key. Each entry is responsible for one value on average (but may contain up to 1024). Entry #i in the table, which is responsible for 0 to 1024 values with keys from 1024i to 1024i + 1023, contains the following: 1. The number of keys in that range. 2. If there are 0 keys, the value of the next lower available key. If there is 1 key, the lower 10 bit of the key in that range, and its value. If there are two or more keys, an index j into a second table. In the second table, we store the lower 10 bit of the key, plus the value, for every key where there are two or more keys in the range from 1024i to 1024i + 1023. For values in the second table, we use binary search.
{ "pile_set_name": "StackExchange" }
Q: Formating output from bat file wmic product get name,version > "C:\myInformation.txt" ECHO. >> "C:\myInformation.txt" ECHO %username% >> "C:\myInformation.txt" I'm trying to write a batch file that will generate the software installed on the users computer as well as get their username for id purposes. The code above works individually. However, when I try to write out to the file, I get †਍敨瑣牯洮牡楴敮⁺਍ instead of "john.doe" My question is, how can I get the software dump from wmic followed by the username without it spitting out garbage. I've flipped the order of commands. Doing so results in getting the username but not the software, in a neat output any ways. Creating two files is not really something I want to do. I'd like one file per user. Thanks in advance. A: Use /APPEND:"myfile.txt" to output wmic in a file. i.e. echo. >"c:\myinformation.txt" wmic /APPEND:"c:\myinformation.txt" product get name,version >nul echo. >> "c:\myinformation.txt" echo %username% >> "c:\myinformation.txt"
{ "pile_set_name": "StackExchange" }
Q: SQL and DevExpress ASPx Grid data (display data 'M' as 'Male') I have an ASPx Gridview control which displays a bunch of data. In the database, a person gender is listed as M or F. And when I display that information in the grid, it comes up as the same M or F. But I need it to display Male or Female. How can I make it so that the the result is converted to that string before displaying? <dx:GridViewDataTextColumn FieldName="Gender" VisibleIndex="14" Caption="Patient's Gender" Width="100px" CellStyle-HorizontalAlign="Left"> </dx:GridViewDataTextColumn> A: <asp:Label ID="lbl" runat="server" <%# Eval("Gender").ToString() == "M" ? "Male" : "Female" %> ></asp:Label>
{ "pile_set_name": "StackExchange" }
Q: Regular expression for A123ABC I have a string in the format A123ABC First letter cannot contain <I,O,Q,U,Z> Next 3 digits (0-9) from 21-998 Last 3 letters cannot include <I,Q,Z> I used the following expression [A-HJ-NPR-TV-Y]{1}[0-9]{2,3}[A-HJ-PR-Y]{3} But I am not able to restrict the number in the range 21-998. A: Your letter part is fine, below is just the numbers portion: regex = "(?:2[1-9]|[3-9][0-9]|[1-8][0-9][0-9]|9[0-8][0-9]|99[0-8])" (?:...) group, but do not capture. 2[1-9] covers 21-29 [3-9][0-9] covers 30-99 [1-8][0-9][0-9] covers 100-899 9[0-8][0-9] covers 900-989 99[0-8] covers 990-998 | stands for "or" Note: [0-9] may be replaced by \d. So, a more concise representation would be: regex = "(?:2\d|[3-9]\d|[1-8]\d{2}|9[0-8]\d|99[0-8])" A: One option would be matching (\d+) and checking if that falls in the range 21 - 998 outside a regex, in the language you're using, if possible. If that is not feasible, you have to break it up (just showing the middle part): (2[1-9]|[3-9]\d|[1-8]\d\d|9[0-8]\d|99[0-8]) Breakdown: 2[1-9] matches 21 - 29 [3-9]\d matches 30 - 99 [1-8]\d\d matches 100 - 899 9[0-8]\d matches 900 - 989 99[0-8] matches 990 - 998 Also, the {1} is superfluous and can be omitted, making the complete regex [A-HJ-NPR-TV-Y](2[1-9]|[3-9]\d|[1-8]\d\d|9[0-8]\d|99[0-8])[A-HJ-PR-Y]{3}
{ "pile_set_name": "StackExchange" }
Q: How to implement a trait for any sequence of elements? I am trying to implement a trait for any sequence of elements, so that it will work for vectors, arrays and slices. So far I've tried several approaches, but I can't compile any of them :( I have this trait, and a function that uses it, and a basic data type implementing the trait: trait Hitable { fn hit(&self, val: f64) -> bool; } fn check_hit<T: Hitable>(world: &T) -> bool { world.hit(1.0) } struct Obj(f64); impl Hitable for Obj { fn hit(&self, val: f64) -> bool { self.0 > val } } I'd like to be able to implement that trait for sequence of Obj's. It works fine if I just restrict it to vectors: impl<T> Hitable for Vec<T> where T: Hitable, { fn hit(&self, val: f64) -> bool { self.iter().any(|h| h.hit(val)) } } fn main() { let v = vec![Obj(2.0), Obj(3.0)]; println!("{}", check_hit(&v)); } But I want to make it more generic so that it works for arrays and slices; how can I do that? I tried the following four attempts: Attempt #1: for iterator on Hitables. // It's not clear how to call it: // vec.iter().hit(...) does not compile // vec.into_iter().hit(...) does not compile // impl<T, U> Hitable for T where T: Iterator<Item = U>, U: Hitable, { fn hit(&self, val: f64) -> bool { self.any(|h| h.hit(val)) } } Attempt #2: for something which can be turned into iterator. // Does not compile as well: // // self.into_iter().any(|h| h.hit(val)) // ^^^^ cannot move out of borrowed content // impl<T, U> Hitable for T where T: IntoIterator<Item = U>, U: Hitable, { fn hit(&self, val: f64) -> bool { self.into_iter().any(|h| h.hit(val)) } } Attempt #3: for slices. // This usage doesn't compile: // let v = vec![Obj(2.0), Obj(3.0)]; // println!("{}", check_hit(&v)); // // It says that Hitable is not implemented for vectors. // When I convert vector to slice, i.e. &v[..], complains about // unknown size in compilation time. impl<T> Hitable for [T] where T: Hitable, { fn hit(&self, val: f64) -> bool { self.iter().any(|h| h.hit(val)) } } Attempt #4: for Iterator + Clone // let v = vec![Obj(2.0), Obj(3.0)]; // println!("{}", check_hit(&v.iter())); // // does not compile: // println!("{}", check_hit(&v.iter())); // ^^^^^^^^^ `&Obj` is not an iterator // impl<T, U> Hitable for T where T: Iterator<Item = U> + Clone, U: Hitable, { fn hit(&self, val: f64) -> bool { self.clone().any(|h| h.hit(val)) } } Playground link A: 1. Iterator-based This cannot work because iterators need to be mutable in order to advance them, but your trait requires &self. 2. IntoIterator-based I'd change the trait to take self by value and then only implement it for references to Obj. This also allows implementing it for any type that implements IntoIterator: trait Hitable { fn hit(self, val: f64) -> bool; } fn check_hit<T: Hitable>(world: T) -> bool { world.hit(1.0) } struct Obj(f64); impl Hitable for &'_ Obj { fn hit(self, val: f64) -> bool { self.0 > val } } impl<I> Hitable for I where I: IntoIterator, I::Item: Hitable, { fn hit(self, val: f64) -> bool { self.into_iter().any(|h| h.hit(val)) } } fn main() { let o = Obj(2.0); let v = vec![Obj(2.0), Obj(3.0)]; println!("{}", check_hit(&o)); println!("{}", check_hit(&v)); } See also: When should I not implement a trait for references to implementors of that trait? 3. Slice-based I find that reading the entire error message, not just the one line summary, can help: error[E0277]: the size for values of type `[Obj]` cannot be known at compilation time --> src/main.rs:28:20 | 28 | println!("{}", check_hit(&v[..])); | ^^^^^^^^^ doesn't have a size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `[Obj]` = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait> note: required by `check_hit` --> src/main.rs:5:1 | 5 | fn check_hit<T: Hitable>(world: &T) -> bool { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Specifically, this bit: note: required by check_hit — check_hit requires that T be Sized. Removing that restriction allows this version to work: fn check_hit<T: Hitable + ?Sized>(world: &T) -> bool { // ^~~~~~~~ world.hit(1.0) } See also: Why does a reference to a trait in a generic function have to implement `Sized`? What does the question mark mean in a type parameter bound?
{ "pile_set_name": "StackExchange" }
Q: Duplicate fields in RECORD,TABLE or argument list are not permitted Im getting error for my stored procedure...any idea for how to solve it ? PROCEDURE is as below : CREATE OR REPLACE PROCEDURE prc_medic_check_status(v_task_id IN VARCHAR, v_request_id IN VARCHAR, v_task_desc IN VARCHAR, v_task_status IN VARCHAR) IS v_task_id task.task_id%TYPE; v_request_id task.request_id%TYPE; v_medical_id Varchar(30); v_medical_status Varchar(30); BEGIN SELECT request_id INTO v_request_id FROM Request WHERE request_type = "Medical"; SELECT task_id INTO v_task_id FROM task WHERE request_id = v_request_id ; SELECT medical_status INTO v_medical_status FROM Medical m, medicalRequest mr, Request r WHERE mr.request_id = r.request_id AND mr.medical_id = m.medical_id; IF (v_medical_status = "Available") THEN UPDATE Task SET task_status = "Done"`enter code here WHERE request_id = v_request_id; DBMS_OUTPUT.PUT_LINE('Medical Task Done'); ELSE DBMS_OUTPUT.PUT_LINE('Medical Task Not Done'); DBMS_OUTPUT.PUT_LINE('Due To The Medical Product Is Currently Not Available'); END IF; END; / A: Your parameter variables are defined as a local variable in the stored procedure thus the error. Usually, we use p_* for passing parameters so I strongly suggest you define your stored procedure as below: CREATE OR REPLACE PROCEDURE prc_medic_check_status(p_task_id IN VARCHAR, p_request_id IN VARCHAR, p_task_desc IN VARCHAR, p_task_status IN VARCHAR) Then change the new parameter names in your query: SELECT task_id INTO v_task_id FROM task WHERE request_id = p_request_id ;
{ "pile_set_name": "StackExchange" }
Q: CUPS have no configuration file I removed the cups from my Linux Mint and now when I reinstall it I cannot see the configuration file anymore: /etc/cups $ ls interfaces ppd raw.convs raw.types How can I restore everything? I need to reinstall the linux mint from scratch? A: try to purge your cups package from the system with apt-get purge cups and after reinstall it with apt-get install cups here you can find all the info you'll need on how configure your printer. https://wiki.debian.org/SystemPrinting
{ "pile_set_name": "StackExchange" }
Q: Ordernar por quantidades de dias faltando para vencer Tenho esse script no meu código: $sql = "SELECT * FROM os WHERE status2 <> 'Fechado' ORDER BY XXXXXXX "; $resultado = mysql_query($sql) or die ("Erro na consulta"); while ($linha = mysql_fetch_assoc($resultado)) { $vencimento = $linha["vencimento"]; $a = explode("-","$vencimento"); $b = explode("-","$hoje"); $antiga= mktime(0, 0, 0, $b[1], $b[2], $b[0]); $atual= mktime(0, 0, 0, $a[1], $a[2], $a[0]); $diferenca= $atual-$antiga; $dias = floor($diferenca/84600); echo $dias = (int) $dias; } Onde retorna quantos dias faltam para o x vencimento. Minha Duvida é como Ordenar a consulta no MySQL por registro com datas mais próximas a vencer. Exemplo abaixo: Sendo Hoje - dia 10/01 data_entrada | vencimento | Dias 01/01 | 05/01 | - 5 "Dias Atrasado" 01/01 | 11/01 | 1 "Para Vencer" 01/01 | 12/01 | 2 "Para Vencer" 01/01 | 13/01 | 3 "Para Vencer" 01/01 | 14/01 | 4 "Para Vencer" A: Não tem porque você ordenar pela quantidade de dias para vencer, principalmente porque você nem filtra só o que está a vencer. Basta uma ordenação pela data de vencimento. Data de vencimento ou quantidade de dias para vencer produzirão a mesma ordem. Você não dá muitas informações mas posso inferir alguma coisa pelo que utilizou e ficaria assim: SELECT * FROM os WHERE status2 <> 'Fechado' ORDER BY vencimento O resto do código não deve ser afetado, apesar de usar um lógica bem esquisita que pode ser bem melhorada ou mesmo retirada se preferir fazer uma query que lhe dê os resultados como deseja. A: O campo vencimento é a data de vencimento da fatura, correto? Então a lógica do seu código fica assim: $sql = " SELECT *, DATEDIFF(vencimento, CURDATE()) dias_para_vencimento FROM os WHERE status2 <> 'Fechado' AND dias_para_vencimento >= 0 ORDER BY dias_para_vencimento"; $resultado = mysql_query($sql) or die ("Erro na consulta"); while ($linha = mysql_fetch_assoc($resultado)) { $dias = $linha['dias_para_vencimento']; echo $dias . '<br>'; } PS: Só não lembro agora se DATEDIFF(vencimento, CURDATE()) retorna um valor positivo ou não. Se for negativo, é só trocar a ordem dos argumentos. :)
{ "pile_set_name": "StackExchange" }
Q: QGIS Export Satellite Imagery We cannot seem to find any way to export our projects as PNG/JPEG through the print layout/composer. We draw normal line and point SHP files over the Bing/Google Earth etc layers, but the exported image is simply blank with only our line and point layers showing. We can sometimes get exports succesfully when the scale is over 3000, but due to the detailed information we need to depict, we need to get down to a scale of 1000. Does anyone have any solutions or alternative options we can try? A: The vendor is not allowing those images to be called/exported at large scale. I've had the same experience with trying to export Esri basemaps in the layout. You'll have to download the aerial image files (tif, jpeg, sid...etc) and load them in manually into Q, hit a public aerial WMS (in the US many states provide this or USGS provides a 1m service), or create and serve out your own aerial WMS to export against from your own image file repository.
{ "pile_set_name": "StackExchange" }
Q: error:undefined reference to 'pthread_testcancel' when compile with NDK I have a third-party library written by C and I want to use it in my Android project by JNI. The issue is that a error occured when I compile it like below: error: undefined reference to 'pthread_testcancel' and the code is #if !defined(WIN32) && !defined (WINCE) && !defined(ITRON) && !defined(BTRON) && !defined(TENGINE) && !defined(PROCESS_BASE) pthread_testcancel(); #endif And only this method compile failed, some other methods are all ok like pthread_kill, pthread_join, pthread_create... Anybody can help me to resolve it? Thanks very well. A: Android's NDK doesn't support pthread_cancel due to the complexity also implementation of it is error prone and harmful to performance (of all code). so you can have look on pthread_cancel() alternatives in Android NDK.
{ "pile_set_name": "StackExchange" }
Q: Iteration counter for double loops I am trying to find the formula to count every iteration of this double for loop (in python for instance): for i in range(5): for j in range(5): count = MYSTERIOUS_FORMULA print count Here the final value of count should be 25. I tried count=(i+1)*j but it produce 0,1,2,3,4,0,2,4 etc. A: The mysterious formula is quite simple: {count} = {index of current loop} + {size of current loop}*{count of parent loop} As an example, consider a single loop: x = 5 for i in range(x): count = i To be explicit, count = i + x*0 but the second term is irrelevant because there is no parent loop. An example of two loops might be more illuminating: x = 5 y = 6 for i in range(x): for j in range(y): count = j + y*(i) Notice that I put i in parentheses to emphasize that it is the {count of parent loop}. This formula can be easily expanded to a third loop: x = 5 y = 6 z = 7 for i in range(x): for j in range(y): for k in range(z): count = k + z*(j + y*(i)) and so on... A: The Double-for-loop (a.k.a. Nested loops). # Set count to 0 before loop starts count = 0 for i in range(5): for j in range(5): # solved mysterious formula (short hand 'count = count + 1') count += 1 # displaying count after loop print(count) Expanding on the formula count = count + 1, this sets count to be equal itself + 1: count = count + 1 A: If you want to compute the number in each iteration: for i in range(5): for j in range(5): count = 5*i+j+1 print count
{ "pile_set_name": "StackExchange" }
Q: Enable backups of Digital Ocean Instances using Salt Cloud I have set up a Salt Master and have got everything to work well but there has been one thing I have not been able to figure out and trying to search for the answer is proving to be difficult so I thought I would see if anyone else has come across this. I have a profile setup in digital ocean that is setup up like the following: digitalocean-ubuntu: provider: my-digitalocean-config image: Ubuntu 14.04 x32 size: 512MB location: New York 1 backups_enabled: True When I run the profile it creates the proper instance with all the options correct but the backups_enabled doesn't seem to work. I have tried going on both digital ocean's website as well as looking through the salt documents but I can't figure out if the command changed or isn't supported anymore? If someone knows the answer I would be very grateful to learn what I'm doing wrong. A: Salt has two versions of their digital ocean API. One for V1 and one for V2. I wasn't using the newer version so there were issues trying to enable new features.
{ "pile_set_name": "StackExchange" }
Q: haskell list of tuples, with unique tuples I come from a Python and Java background so Haskell is quite different for me. I'm trying little activities to learn but I am stuck on this . I have an ordered list of tuples, [(name, studentNumber)], and I want to filter this list so that each student and each studentNumber appears only once. Since the tuples are ordered, I want to keep the first instance of a name or studentNumber and remove any others that may show up. I tried doing a list comphrenshion, but I'm not sure how to check if a name or number has already been added to the list. A: It sounds as if you'd want (as a first, inefficient approximation) something like this: import Data.List (nubBy) import Data.Function (on) filt = nubBy ((==) `on` snd) . nubBy ((==) `on` fst) The first call to nubBy will result in a list in which each name appears only once, and that will then be passed to the second, resulting in a list in which each number appears only once. Just using nub will result in a list in which each (name,number) pair occurs only once; there might still be repetitions of names with different numbers and numbers with different names. (Of course something custom with an accumulator would be faster.)
{ "pile_set_name": "StackExchange" }
Q: In phpmyadmin, how would I link two specific rows to each other from two different tables inside a single database and keep it automated? I have 2 tables within a single phpmyadmin database- one that stores basic user account info when they sign up (username, email, etc.) and another that stores whatever the user types in the text field where they input the names of their classes but also takes the username from the first table and stores it in another row inside the second table next to all the classes. The first table does what its supposed to and the user data appears there after they click sign up. After the user clicks sign up, they are directed to the classes page where they type the data for the second table. However after you click submit, there is an "object not found" error message and the second table is completely empty. Not even the username from the first table appeared within the second. For reference- inside the URL of the webpage whatever the user typed into the class boxes appears, however the end of the URL it says "submit=". I tried searching for a few hours but really couldn't find a solution (hence what brought me here). I tinkered with my code a lot, but still couldn't figure out the issue. From what I could tell everything seemed to be right- but obviously the result wasn't. I had my connection file that connects my code to the phpymadmin database, my HTML file that provides the basic text layout which must be working fine since everything appears, and finally my file that provides the backend mechanics written exclusively in PHP- which is where I'm guessing the problem(s) most likely is/are. I've tried several functions for hours to no avail, watched videos to try to get a better idea but still cannot change the result- not even the error "object not found". I also made it so that the user has to retype their username on the classes page, which also ended with the exact same result. For reference, I am using sublimetext3, the latest version of XAMPP (Running Apache and MySQL) which comes with PHPmyadmin (where my database and tables are that store user info). This is my backend PHP code (I have some required files that define the buttons, and names like "class1". if (isset($_GET['submit'])) { $box1 = $_GET['class1']; $box2 = $_GET['class2']; $box3 = $_GET['class3']; $box4 = $_GET['class4']; $username = $_POST['uid']; $stmt = mysqli_stmt_init($conn); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) { $userCheck = username_verify($username, $row['uid']); if ($userCheck == true) { header("Location: ../class_result.php?"); exit(); } /n order to recreate the text fields the user types into known as "classes" see the code below (NOTE THIS IS A SEPARATE FILE): <form action="classcreation.inc.php" method="GET"> <input type="text" name="uid" placeholder="Username"> <input type="text" name="class1" placeholder=""> <input type="text" name="class2" placeholder=""> <input type="text" name="class3" placeholder=""> <input type="text" name="class4" placeholder=""> <input type="text" name="class5" placeholder=""> <input type="text" name="class6" placeholder=""> <input type="text" name="class7" placeholder=""> <input type="text" name="class8" placeholder=""> <button type="submit" name="submit">Submit</button> </form> //And finally my connection file- though I am almost certain this is correct, I'm posting it in order for answerers to see that I have established a connection and the method in which I did so: $dbservername = "localhost"; $dBUsername = "root"; $dBPassword = ""; $dBName = "loginsystem"; $conn = mysqli_connect($dbservername, $dBUsername, $dBPassword, $dBName); As previously stated, after the user clicks submit on the classes page, whatever they inputted in the text fields known as "classes", should appear in the corresponding second table. In addition to that, the second table should receive the username of the user typing the information- which was already collected from the first table. But instead the second table is completely empty. Furthermore, they are to be directed to another page that for now just says "Welcome!" (using simple echo statements for the message), but instead receive an "object not found error. Whether the last part is related to the database emptiness I am not 100% sure, but I believe that it is. A: You never executed a SQL query with the class data. I recommend changing the HTML so you name all the class input fields name="class[]". This will make $_GET['class'] an array that you can loop over. if (isset($_GET['submit'])) { $username = $_GET['uid']; $stmt = $conn->prepare("SELECT username FROM users WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt->bind_result($result_user); $userCheck = username_verify($username, $result_user); if ($userCheck) { $stmt = $conn->prepare("INSERT INTO user_classes (username, class) VALUES (?, ?)"); $class = null; $stmt->bind_param("ss", $username, $class); foreach ($_GET['class'] AS $class) { if (!empty($class)) { // skip empty input fields $stmt->execute(); } } } } Of course, change the table and column names in the query to match your actual table. When creating the form from the login page, you can fill in the uid input like this: <input type="text" name="uid" value="<?php echo $username; ?>" placeholder="Username"> However, putting the username in the form is a bad idea, since the user can edit it to submit data for a different user. Making it readonly or hidden doesn't help much, since the user can still change it using Developer Tools. It would be better if the login page put it in a session variable, and used that on all subsequent pages. This can't be modified by the user.
{ "pile_set_name": "StackExchange" }
Q: How to give wiggle animation effect with fixed position? I want an element to be animated like a swaying plant. I am looking to animate a div in the following manner. Fix the bottom Move the head back and forth Looking for full css solution. I have tried this, @keyframes wiggle { 0% { transform: rotate(0deg); } 25% { transform: rotate(-1deg); } 50% { transform: rotate(2deg); } 75% { transform: rotate(-0.4deg); } 100% { transform: rotate(1deg); } } A: You can set transform-origin property to bottom. .el { margin: 30px 50px; width: 0; height: 0; border-style: solid; border-width: 150px 50px 0 50px; border-color: #007bff transparent transparent transparent; animation: wiggle infinite 3s alternate; transform-origin: bottom; } @keyframes wiggle { 0% {transform: rotate(0deg);} 25% {transform: rotate(-3deg);} 50% {transform: rotate(5deg);} 75% {transform: rotate(-1deg);} 100% {transform: rotate(2deg);} } <div class="el"></div>
{ "pile_set_name": "StackExchange" }
Q: How to make the date become the first column? I want to make the date become the first column of SBUX, which means there should be a total of 7 column for SBUX. What should I do to the code? library(quantmod) stocks <- getSymbols("SBUX", from="2017-01-01", periodicity = "weekly") SBUX A: index is what you want - it will extract the dates from SBUX as a vector. However, the data in SBUX is stored in a matrix, and in R, a matrix can only contain data of a single type (in this case, a double). If you want to add a Date column, you'll first need to make it a data frame. So the following should work: library(quantmod) stocks <- getSymbols("SBUX", from="2017-01-01", periodicity = "weekly") dates <- index(SBUX) SBUX <- as.data.frame(SBUX) SBUX <- cbind(date = dates, SBUX)
{ "pile_set_name": "StackExchange" }
Q: Replacing one by one when searching in Vim I am currently search vim using /Paul If I had a sentence like this: Paul likes to play with Paul Now when I type: /Paul The two pauls on the line are highlighted in yellow. The first n takes me to the first Paul and the second n takes me to the last Paul. How could I replace the Paul that is currently next (or in view)? A: Let's do it again: Let's start. Paul likes to play with Paul - /PaulEnter Let's start. Paul likes to play with Paul - n Let's start. Paul likes to play with Paul - ciwAndrew Let's start. Paul likes to play with Andrew - Is it what you want to do? A: Use a substitution with the c flag for confirm. :%s/Paul/Ringo/gc Or you can just do the search like you are and use the gn motion along with . to accomplish this. cgnRingo<esc> . to repeat. You can also use n to go to the next location or skip one. For more help see: :h :s :h gn :h .
{ "pile_set_name": "StackExchange" }
Q: Problem sending data over UDP sockets This is kind of a followup to the question I had yesterday. I had a homework assignment to send and receive data with a client/server TCP socket connection. I would like to make a version of it using UDP. The idea is that I can redirect standard I/O and send the streams using UDP. For example, if I type in: server: java UDPServer 5555 < file1.txt client: java UDPClient localhost 5555 > file2.txt It should send the data in file1.txt from the server to client's file2.txt. When I run the client/server pair in separate terminals, file2.txt is created but the data is never actually sent. Instead it seems like I am stuck in an infinite loop, where I cannot enter anything into the terminal unless I kill the application. The server code is: public static final int BUF_SIZE = 256; public static void main(String[] args) throws IOException{ port = Integer.parseInt(args[0]); DatagramSocket serverSocket = new DatagramSocket(port); BufferedInputStream input = new BufferedInputStream(System.in); BufferedOutputStream output = new BufferedOutputStream(System.out); byte[] receiveData = new byte[BUF_SIZE]; byte[] sendData = new byte[BUF_SIZE]; byte[] buf = new byte[BUF_SIZE]; String sentence; if(System.in.available() > 0) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); InetAddress address = receivePacket.getAddress(); int bytesRead = 0; while((bytesRead = input.read(buf, 0, BUF_SIZE)) != -1) { sentence = new String(buf, 0, bytesRead); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port); serverSocket.send(sendPacket); } } else { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); sentence = new String(receivePacket.getData()); output.write(sentence.getBytes()); } serverSocket.close(); input.close(); output.close(); } And the client code is: public static final int BUF_SIZE = 256; public static void main(String[] args) throws IOException{ String hostName = args[0]; port = Integer.parseInt(args[1]); DatagramSocket clientSocket = new DatagramSocket(); InetAddress address = InetAddress.getByName(hostName); BufferedInputStream input = new BufferedInputStream(System.in); BufferedOutputStream output = new BufferedOutputStream(System.out); byte[] sendData = new byte[BUF_SIZE]; byte[] receiveData = new byte[BUF_SIZE]; byte[] buf = new byte[BUF_SIZE]; String sentence; if(System.in.available() > 0) { int bytesRead = 0; while((bytesRead = input.read(buf, 0, BUF_SIZE)) != -1) { sentence = new String(buf, 0, bytesRead); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port); clientSocket.send(sendPacket); } } else { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); sentence = new String(receivePacket.getData()); output.write(sentence.getBytes()); } clientSocket.close(); input.close(); output.close(); } I am still new to socket programming so I am basing this off of example code in my textbook. Is there some glaring mistake that I am making that is preventing the data from being transferred? Thanks very much for your patience and help! A: The first problem you have is that client.main doesn't run because your shell command is wrong. For some reason, with Java you can't redirect output how it's traditionally done. You can simply put a few print statements at the beginning of client.main to see nothing executes. Try this: java UDPClient localhost 5555 | tee file2.txt See redirect Java output. The other problem you have is that both the client and server are waiting to receive a datagram. You have in the server code: if(System.in.available() > 0) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); And you have in the client code: else { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); sentence = new String(receivePacket.getData()); output.write(sentence.getBytes()); } Note that the else statement will always execute because System.in.available will always return 0. Remember your not redirecting input to the client, so there's nothing in System.in. To fix this you need to first send a client datagram so that the server can respond with the contents of file2.txt.
{ "pile_set_name": "StackExchange" }
Q: How to keep server listen running in Grunt task? I have a HTTP server I'm running as part of one Grunt task. The listen method is asynchronous (as is most Node.js code), so immediately after the Grunt task has called the method it finishes execution and thus closes the server. grunt.registerTask('serveProxy', 'Start the proxy to the various servers', function() { var server = http.createServer(function(req, res) { // ... }); server.listen(80); }); How can I keep this running or perhaps make the method block so it doesn't return? A: The solution was to instruct Grunt to wait as per the documentation by telling Grunt this is an asynchronous method and using a callback to indicate when we are done. grunt.registerTask('serveProxy', 'Start the proxy to the various servers', function() { var done = this.async(); var server = http.createServer(function(req, res) { // ... }); server.listen(80); });
{ "pile_set_name": "StackExchange" }
Q: Four downvotes all right next to each other And on unrelated questions no doubt. See recent activity. Now will this get caught by that script? Not that I'm worried about the rep, but the answers vote count goes down and that sucks more then the rep. A: If you have concerns about specific downvotes, and they persist for more than 24-36 hours, email the address at the bottom of every web page.
{ "pile_set_name": "StackExchange" }
Q: Is it better to separate twins in the kindergarden? My friend has twins and they are about to start at the kindergarden. However teachers suggest to put them into two different groups. I know it's a common practice in many countries, but does anyone know what's actually the best for twins in that situation? If that matters they are currently 2 years old, a boy and a girl. A: I don't have twins myself, but a few friends of mine do. I live in Germany and I'm French, just to give you a cultural context. My observation and my experience talking to parents of twins is that there is no "good recipe" when it come to keeping twins together or separating them. There are many different dynamics in twin brothers and sisters. What I have gathered is: If the twins are really close to one another and somewhat dependant on each other, in a balanced way, you probably don't want to have them separated, because you don't want to break that balance and you want to give them as much comfort as possible. Being together for a while longer might be beneficial to their development. If on the contrary, the balance is that one or the other is completely dependant on the other one, and that one "rules" the life of the other, separating them might be a good way to restore independance and make sure one of the twins does not dictate the life of the other. Breaking them apart can be a beneficial thing as it allows them to grow independantly, have their own set of friends and experiences. If they form a block, ie. are very close to one another, but at the expense of other kids (they won't mingle with other kids because they have each other), you might want to separate them in order to socialize better, but then they might have a hard time on their own. This will depend on kids. If both are very independant to start with, you can choose to separate them or to leave them together, it probably does not matter, they'll do well either way. In the end, your friend is the best judge of what her twins interact with each other and with other people, and I think she probably can go with her guts of what she thinks is best for them both. She should feel comfortable asking the kindergarten to keep them together or separate them, depending on what she has observed so far in the way they act between themselves and with other kids. If she's not sure, she can maybe tell the peole at the kindergarten to try one thing or the other and observe how that plays out, and maybe change groups along the way if she realizes that separating them was a mistake. We all make mistakes, the important thing is to observe and learn and be able to change course.
{ "pile_set_name": "StackExchange" }
Q: Check Multiple and module of two BigDecimal in java BigDecimal x = new BigDecimal(1.95); BigDecimal y = new BigDecimal(0.65); BigDecimal rem = x.remainder(y); if (rem.compareTo(BigDecimal.ZERO) != 0.) { System.out.println("Not In mutilple of"); } else { System.out.println("In mutilple of"); } System.out.println(rem); Not giving correct result for the above scenario. given the input condition but giving incorrect result if it is in multiple of the second value A: Explanation Useing new BigDecimal(double) might lose precision, see the doc: The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding. and: BigDecimal x= new BigDecimal(1.95); BigDecimal y = new BigDecimal(0.65); System.out.println(x); // 1.9499999999999999555910790149937383830547332763671875 System.out.println(y); // 0.65000000000000002220446049250313080847263336181640625 Solution Use BigDecimal(String val): The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one. and BigDecimal x = new BigDecimal("1.95"); BigDecimal y = new BigDecimal("0.65"); System.out.println(x); // 1.95 System.out.println(y); // 0.65 System.out.println(x.remainder(y)); // 0.00 A: Instantiate like BigDecimal x= new BigDecimal("1.95"); BigDecimal y= new BigDecimal("0.65"); as not all float point number can be represented exactly as doubles. The output in your code shows 0.65 ss 0.64999999999999995559107901499373838305473327636718750 see https://study.com/academy/lesson/java-floating-point-numbers.html
{ "pile_set_name": "StackExchange" }
Q: How do I verify a user over the telephone? We have users -they can call us on the telephone. How do we validate that the users are who they say they are? Here are some possible solutions: Check personal information such as date of birth: DOB can be guessed from Facebook and Linkedin + there are data-protection issues around storing DOB Check the telephone number of the user: I was told that it's easy for an attacker to forward calls to a device that they control Create a database of security questions and answers: we would have to create and maintain a database Is there a standard robust way of doing this? A: Relying on publicly know information is problematic. Storing personal security questions+answers is unlikely to scale well if many others adopt the same approach. If you want to authenticate someone who is using your service, ask them questions about their association with you. Examples include: Give all users an account number, transaction number for the issue, etc. Ask about past transactions / orders (and make sure this is something that they can access easily) Calling them back on a given telephone number is also a useful approach, and adds defense-in-depth. However, you then need to think about mutual authentication-- how can you ensure that the user trusts the call. If done right, this can further boost the security of your system. Make sure you use some form of rate limiting and track when authentication attempts are made. Make sure these attempts are communicated back to the user "out-of-band".
{ "pile_set_name": "StackExchange" }
Q: Palindrome-testing Java program for an interview In an interview I was asked to write a function that would take an input word and return true if the word is a palindrome. At first I used an approach using StringBuilder but the interviewer said that wasn't allowed and to use a for loop instead. I scored 7/9 so I'm guessing it's possible to improve this: public static boolean isPalinedrome(String word) { for(int i = 0; i < word.length(); i++) { if(word.charAt(i) != word.charAt(word.length() - 1 - i)) { return false; } } return true; } I added the following to the main() section to test String input = "racecar"; if(isPalinedrome(input)) { System.out.println(input + " is a palinedrome"); } else { System.out.println(input + " is not a palinedrome"); } The way I test it seems to be ugly. Is there a standard way to test a new function? I guess if you're in an advanced enough environment you would have test cases for JUnit to run against it, but anything simpler that could be done in an interview with a cloud IDE? A: It's enough to loop until word.length() / 2, as this will compare the first half with the second half, so no need to go until the end. As you use word.length() multiple times, you could extract it to a helper variable. There is a typo in the method name. As for testing, yes, JUnit is the way to go. In a cloud IDE, you could create a helper method that takes a single string, calls isPalindrome and prints the result. That way you can test multiple cases easily, by adding one line per case. It's important to try to cover corner cases and potentially interesting cases, not just the "happy path". For example: palindrome with even length palindrome with odd length single letter empty string non-palindromes During an interview, it might also be worth mentioning the trade-off between comparing characters using .charAt, or using the array of characters returned by .toCharArray.
{ "pile_set_name": "StackExchange" }
Q: Area bounded between the curve $y=x^2 - 4x$ and $y= 2x/(x-3)$ I've determined the intersects to be $x = 0, 2, 5$ and that $\frac{2x}{x-3}$, denoted as $f(x)$, is above $x(x-4)$, denoted as $g(x)$, so to find the area, I'll need to find the integral from $0$ to $2$ of $f(x) - g(x)$. But I've been stuck for a while playing around with this question. A: First, simplify the difference between the two functions: $$ \begin{eqnarray} f(x) - g(x) &=& \frac{2x}{x-3} - x(x - 4) \\ &=& \frac{-x^3 + 7x^2 - 10x}{x-3} \\ \end{eqnarray} $$ Then, integrate by substituting $u = x-3$: $$ \begin{eqnarray} \int_0^2 \! \frac{-x^3 + 7x^2 - 10x}{x-3} \, \textrm{d}x &=& \int_{-3}^{-1} \! \frac{-(u+3)^3 + 7(u+3)^2 - 10(u+3)}{u} \, \textrm{d}u \\ &=& \int_{-3}^{-1} \! \frac{-u^3 - 2u^2 + 5u + 6}{u} \, \textrm{d}u \\ &=& -\frac{u^3}{3} - u^2 + 5u + 6\ln(u) \bigg|_{-3}^{-1} \\ &=& \frac{28}{3} - 6\ln(3) \\ \end{eqnarray} $$
{ "pile_set_name": "StackExchange" }
Q: Integrating Skype, speech recognition and MS Access I need to achieve the following, in order to avoid having to develop a very costly web app. Please advise if it is feasible to use Skype (or another PDA friendly VOIP) to call a computer that is running an MS Access form. The MS Access form would be integrated with speech-recognition and text-to-speech, to communicate back and forth via Skype VOIP. The remote Skype user would use voice commands to run MS Access macros. Some of these macros would use text-to-speech to prompt the user to verbally input data into the MS Access form fields. I have already tested the apps "Windows 7’s Speech Recognition" and "Dragon Naturally Speaking", but they don’t work with VOIP, because they require the speech to be inputted from a microphone and can not work if the speech is inputted from the speaker, so the speech-recognition needs to be running on the computer that is running the MS Access app and should not be running on the user’s side. I am hoping that such a setup can be achieved using another app or with some custom programming. Please outline the proper procedure and/or provide insight. Thank you very much in advance, Nathaniel A: Here are some points just to clarify a few things from your question. Microsoft Speech Recognition is not limited to microphone input. You can capture audio to a wav file and then process the captured audio. See SpeechRecognitionEngine.SetInputToWaveFile - http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognitionengine.setinputtowavefile.aspx. Note that this requires the use of an inproc recognizer (SpeechRecognitionEngine) instead of the shared recognizer (SpeechRecognizer). This means you must have your own speech recognition application, this method does not use the Windows desktop speech recognition to control applications. Many IVR systems accept VOIP input using standards like SIP. The Microsoft Speech Server product that got consumed by Microsoft Lync supports VOIP input. See SIP Peers - http://msdn.microsoft.com/en-us/library/lync/bb812717(v=office.12).aspx. However, I believe Skype does not use VOIP standards like SIP without extra costs - http://www.skype.com/intl/en-us/business/skype-connect/ When you are trying to voice enable your access application, are you using standard voice control for access like http://office.microsoft.com/en-us/access-help/speech-recognition-commands-in-access-HA001034591.aspx ?
{ "pile_set_name": "StackExchange" }
Q: Skip ads from YouTube Since ads are almost inevitable on official YouTube app on Android device, I was wondering if those can be skipped automatically? This post is only about those ads which can be skipped, lets ignore ads which can not be skipped. For example: When YouTube video starts, for some ads, there is an option to "Skip this ad in 5 sec". Once "Skip ad" label is enabled, we can click on it to move to video. Of course this is all manual, and as a user you need to focus on EXACT timing to HIT the skip button. And it becomes worse if the video is having multiple Ads(few of which will be shown in future time), where when Ad plays, user need to again click manually to skip it. Can this be AUTOMATED, meaning when there is an Ad which can be "Skipped", then just let the YouTube skip it without user's intervention. This will be specially useful for those videos which has multiple Ads spanned across the video length and few of them can be skipped. Looking for a solution on non-rooted device. Update: It seems like Google is introducing new ad format called Bumpers. Bumpers, which are unskippable 6-second shorts placed in front of videos. So, soon we may not see an ad which can be skipped, forget about skipping it via automation! A: You're interested in the Youtube AdAway Xposed Module. It requires root access and the Xposed Framework. It completely removes the following: YouTube ads channel logos video suggestions information card teasers To the best of my knowledge, what you've requested (auto skipping advertisements in the stock Youtube application) cannot be done without root access. Root access is required to 1) draw over other apps and 2) record/replay touches. See: Bot Maker for Android RepiTouch Free HiroMacro Auto-Touch Macro A: As @Six stated very correctly, it is NOT possible to do without root access at all. His answer is pretty good but there is still some things I can add. A non-rooted phone quite literally means a phone that can only be used the way manufacturer wants it to be. Its power is limited to how much the manufacturer wants you to have (and for good reason according to some people, which sometimes includes me too) On a non-rooted phone, no third party app can emulate screen touches, modify the loaded or running copies of other apps or access to data of other apps. All for security reasons. So your wish can't be granted without root access.
{ "pile_set_name": "StackExchange" }