text
stringlengths
175
47.7k
meta
dict
Q: WordNet - Parts-Of-Speech required? To figure out if the two words are SYNONYMS (SIMILAR_TO), do I need to find the Parts-Of-Speech for the two words first? Can I do this in a single 'operation' in the WordNet or will I have to loop through the senses first for each word? A: Synsets are categorized according to the POS. So there is no way to avoid it.
{ "pile_set_name": "StackExchange" }
Q: Validation of EditText's does not work I have a signup screen. It contains a place for the user's full name, email address and password (the user has to confirm their password). However, it does not work as expected. For the signup button to be enabled the fields have to filled in, in order: top to bottom (this wasn't intended). Moreover, the red colour on the confirm password field does not go away and the signup button does not enable unless the characters are shown. The checking to see if there are characters in all the fields seem to be malfunctioning and I am not sure why. The checking works sometimes and doesn't work other times. Please can someone help me optimize this. There are comments in the code to show what each method does. This is the Layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="@string/hintNameField" android:ems="10" android:id="@+id/txtSName" android:layout_marginTop="30dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:hint="@string/hintEmailField" android:ems="10" android:id="@+id/txtSEmailAddress" android:layout_marginTop="15dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/txtSPassword" android:hint="@string/hintPasswordField" android:layout_marginTop="15dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/txtSPasswordConfirm" android:hint="@string/hintPasswordConfirmField" android:layout_marginTop="15dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/showPasswordCheckBox" android:id="@+id/showPasswordCheckBox" android:layout_marginTop="10dp" android:layout_marginLeft="5dp"/> <Button android:layout_width="200dp" android:layout_height="wrap_content" android:text="@string/btnSignUp" android:id="@+id/btnSignUp" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:enabled="false" /> </LinearLayout> This is the Java class for the layout: //this is the full name field snameTxt = (EditText) findViewById(R.id.txtSName); snameTxt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); snameTxt.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Please enter your full name", Toast.LENGTH_SHORT).show(); return false; } }); //this is the email address field semailTxt = (EditText) findViewById(R.id.txtSEmailAddress); semailTxt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); semailTxt.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Please enter the email address to be associated with your account", Toast.LENGTH_SHORT).show(); return false; } }); //this is the password field spasswordTxt = (EditText) findViewById(R.id.txtSPassword); spasswordTxt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //the code to enable the button. This needs the most optimization if (String.valueOf(spasswordTxt.getText()).trim().length() > 3 && String.valueOf(snameTxt.getText()).trim().length() > 0 && String.valueOf(semailTxt.getText()).trim().length() > 0) { signupBtn.setEnabled(true); } else { signupBtn.setEnabled(false); } if (String.valueOf(spasswordTxt.getText()).trim().length() < 3) { signupBtn.setEnabled(false); } if (String.valueOf(snameTxt.getText()).trim().length() < 1) { signupBtn.setEnabled(false); } if (String.valueOf(semailTxt.getText()).trim().length() < 1) { signupBtn.setEnabled(false); } } @Override public void afterTextChanged(Editable s) { } }); spasswordTxt.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Please enter a password with a minimum of 4 characters", Toast.LENGTH_SHORT).show(); return false; } }); spasswordconfirmTxt = (EditText) findViewById(R.id.txtSPasswordConfirm); spasswordconfirmTxt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //if the password and the password confirm fields do not match //then the password confirm field goes red. This also needs optimization if (spasswordconfirmTxt.getText().toString().equals(spasswordTxt.getText().toString())) { spasswordconfirmTxt.getBackground().clearColorFilter(); } else { spasswordconfirmTxt.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP); signupBtn.setEnabled(false); } } @Override public void afterTextChanged(Editable s) { } }); //this allows the password field characters to be shown final CheckBox showPasswordCheckBox = (CheckBox) findViewById(R.id.showPasswordCheckBox); showPasswordCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(!isChecked){ spasswordTxt.setTransformationMethod(PasswordTransformationMethod.getInstance()); spasswordconfirmTxt.setTransformationMethod(PasswordTransformationMethod.getInstance()); } else { spasswordTxt.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); spasswordconfirmTxt.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); } } }); A: I sugget you to use some convenience methods, this would help you to write code which is clearer. For example use this method to check if a field contains a valid strihg: / Checks if a String actually carries information public static boolean isValidString(String string) { if (string == null) { return false; } else { String s = string.trim(); // Remove blank spaces at start and at end if ((s.length() == 0) || (s.equalsIgnoreCase(""))) return false; else return true; } } Going specifically to your problem, I see that the actual validation of the fields is done in the onTextChanged(...) method of the password field, therefore it's obvious that filling the password field at last would carry out the validation, otherwise if you fill the password for first and then go to the other fields, their onTextChanged(...) simply does nothing, therefore the validation isn't carried out. You should add a method which is called in every single onTextChanged(...) callback! For the red colored field, I am not sure if that's the correct approach to adopt, just try to use some different ways to give visual clues, See my blog post for example. However I see that you're not doing the check and therefore not enabling properly the submit button when onTextChanged(...) is fired in the confirmation field, I think you forgot something: @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //if the password and the password confirm fields do not match //then the password confirm field goes red. This also needs optimization if (spasswordconfirmTxt.getText().toString().equals(spasswordTxt.getText().toString())) { spasswordconfirmTxt.getBackground().clearColorFilter(); signupBtn.setEnabled(true); // Enable the button if everything is ok } else { spasswordconfirmTxt.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP); signupBtn.setEnabled(false); } } So bottom line is, create another method from which you check all the fields together, which will also enable the button if all check are ok, and make a call to that method whenever ANY of onTextChanged(...) callbacks is fired! Cheers!
{ "pile_set_name": "StackExchange" }
Q: Connection with Wi Fi in android device I am facing a strange problem with my Android ACE phone. I am able to connect to Wi-Fi and able to browse Google. But unable to connect to my Internal Servers / network. What is the problem? Will it be an issue with the device or is it the problem with router? Same Server is accessible through my IPAD2!! My client is telling me that they have not blocked my device from accessing their network.. But my device displays "DNS Error" when i try hitting their server. So is there any way that I can detect if my user agent or device is blocked by the internal router or network?? Thanks in advance, Sneha A: First of all this is not the place to ask this type of questions. This site is for development/programming related questions. Why don't you use https://android.stackexchange.com/. However I think your issue can be fixed by using custom DNS servers like 8.8.8.8 or 8.8.8.4. Or you could run a port scan on your network and see if they have a DNS server.
{ "pile_set_name": "StackExchange" }
Q: Changing URL through html select What is the best way to change your URL through an html select? <select> <option selected="selected">Change to URL X</option> <option>Change to URL Y</option> </select> What Javascript should be used? A: <script type="text/javascript"> function navigateTo(sel, target, newWindow) { var url = sel.options[sel.selectedIndex].value; if (newWindow) { window.open(url, target, '--- attributes here, see below ---'); } else { window[target].location.href = url; } } </script> <select onchange="navigateTo(this, 'window', false);"> <option selected="selected" value="http://www.example.com/#X">Change to URL X</option> <option value="http://www.example.com/#Y">Change to URL Y</option> </select> Some useful values of target might be 'window' (the current window) or 'top' (to break out of a frameset or iframe). If you want to open a new window instead, you could use navigateTo(this, 'someWindow', true); The value of '--- attributes ---' is set using various properties as documented here for Mozilla and here for IE. For example: 'height=300,width=400,top=100,left=100,statusbar=0,toolbar=1' A: If you have jQuery you could do... javascript: $('#select_url').change(function(evnt){ location.href = $(this).val(); }); html: ...
{ "pile_set_name": "StackExchange" }
Q: How to sum up this series or find a closed expression or argument? We know the following (Taylor expansion) $$\sum_{n=0}^\infty \frac{(-1)^n}{n!} (x^2)^n = e^{-x^2}.$$ Which is integrable in $x$ on $\mathbb{R}$. Nevertheless, imagine we instead have: $$\sum_{n=0}^\infty \frac{(-1)^n}{n!} (x^2)^n \frac{\Gamma(1+n)}{\Gamma(1+a+n)},$$ where $a>0$ is some fixed value. Clearly, $$\frac{\Gamma(1+n)}{\Gamma(1+a+n)}\leq 1$$ so one should expect that this factor does not contibute to the sum and that the remaining function in $x$ is still integrable on $\mathbb{R}$. Of course, one can say: $$\sum_{n=0}^\infty \frac{(-1)^n}{n!} (x^2)^n \frac{\Gamma(1+n)}{\Gamma(1+a+n)}\leq e^{x^2}.$$ Using the inequality, but this implies destroying the $-1$ which is crucial. Does any one have an idea or argument that can help to either "keep" the $-1$ or to conclude that the remaining function is integrable on $\mathbb{R}$? Thanks a lot for any ideas you may have! :) A: For $a\in\mathbb N$ and $n\in\mathbb N$, we have $$\frac{\Gamma(1+n)}{\Gamma(1+a+n)}=\frac{n!}{(n+a)!}$$ Notice that $$\frac{x^n}{n!}\frac{\Gamma(1+n)}{\Gamma(1+a+n)}=\frac{x^n}{n!}\frac{n!}{(n+a)!}=\frac{x^n}{(n+a)!}$$ $$\sum_{n\ge0}\frac{x^n}{n!}\frac{\Gamma(1+n)}{\Gamma(1+a+n)}=\sum_{n\ge0}\frac{x^n}{(n+a)!}=\frac1{x^a}\left(e^x-\sum_{n=0}^{a-1}\frac{x^n}{n!}\right)$$ And one can set bounds on this by seeing that $$\frac{\Gamma(1+n)}{\Gamma(1+\lceil a\rceil+n)}\le\frac{\Gamma(1+n)}{\Gamma(1+a+n)}\le\frac{\Gamma(1+n)}{\Gamma(1+\lfloor a\rfloor+n)}$$ So your series/function is bounded by $$\left|\frac1{x^{\lceil a\rceil}}\left(e^x-\sum_{n=0}^{\lceil a\rceil-1}\frac{x^n}{n!}\right)\right|\le|S|\le\left|\frac1{x^{\lfloor a\rfloor}}\left(e^x-\sum_{n=0}^{\lfloor a\rfloor-1}\frac{x^n}{n!}\right)\right|$$ For $x>0$. And finally let $x\to-x^2$ (Note that the negative sign may cause some problems with the bounds on this.)
{ "pile_set_name": "StackExchange" }
Q: Removing and re-adding a subview with autolayout When using autolayout, my understanding is that removing a subview ( while holding a reference to it of course), the removed subview still knows its autolayout constraints. However, when adding it back to the super view later, the subview no longer knows its frame size. Rather it seems to get a zero frame. I assumed that autolayout would auto size it to meet the constraints. Is that not the case? I thought auto layout meant don't mess with frame rects. Do I still need to set the initial frame rect when adding the subview, even with auto layout? A: When removing the subview, all the constraints that relate to that subview will be lost. If you need to add the subview again later, then you must add constraints to that subview again. Typically, I create the constraints in my custom subview. For example: -(void)updateConstraints { if (!_myLayoutConstraints) { NSMutableArray *constraints = [NSMutableArray array]; // Create all your constraints here [constraints addWhateverConstraints]; // Save the constraints in an ivar. So that if updateConstraints is called again, // we don't try to add them again. That would cause an exception. _myLayoutConstraints = [NSArray arrayWithArray:constraints]; // Add the constraints to myself, the custom subview [self addConstraints:_myLayoutConstraints]; } [super updateConstraints]; } updateConstraints will be called automatically by the Autolayout runtime. The code above goes in your custom subclass of UIView. You're right that in working with Autolayout, you don't want to touch frame sizes. Instead, just update the constraints in updateConstraints. Or, better still, set up the constraints so you don't have to. See my answer on that topic: Autolayout UIImageView with programatic re-size not following constraints You don't need to set the initial frame. If you do use initWithFrame, just set it to CGRectZero. Your constraints will - in fact must - detail either how big something should be, or other relationships that mean the runtime can deduce the size. For example, if your visual format is: @"|-[myView]-|", that's everything you need for the horizontal dimension. Autolayout will know to size myView to be up to the bounds of the parent superview denoted by |. It's pretty cool.
{ "pile_set_name": "StackExchange" }
Q: How to filter response with query parameters on POST methods on Microsoft Graph API? I am attempting to make a simple room booking application within my office. Users can select a time frame, see the available rooms, and book the room (create an event in their calendar in that time frame in that room). In order to see what rooms are available, I am attempting to use the Microsoft Graph REST API, and specifically the POST method - getSchedule. An example request for getSchedule looks like this { "schedules": ["adelev@contoso.onmicrosoft.com", "meganb@contoso.onmicrosoft.com"], "startTime": { "dateTime": "2019-03-15T09:00:00", "timeZone": "Pacific Standard Time" }, "endTime": { "dateTime": "2019-03-15T18:00:00", "timeZone": "Pacific Standard Time" }, "availabilityViewInterval": "60" } I place all of the rooms in the office in the schedules list, and then can see their availabilities in the response based on the availability view. "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.scheduleInformation)", "value": [ { "scheduleId": "adelev@contoso.onmicrosoft.com", "availabilityView": "000220000", "scheduleItems": [ { "isPrivate": false, "status": "busy", "subject": "Let's go for lunch", "location": "Harry's Bar", "start": { "dateTime": "2019-03-15T12:00:00.0000000", "timeZone": "Pacific Standard Time" }, "end": { "dateTime": "2019-03-15T14:00:00.0000000", "timeZone": "Pacific Standard Time" } } ], "workingHours": { "daysOfWeek": [ "monday", "tuesday", "wednesday", "thursday", "friday" ], "startTime": "08:00:00.0000000", "endTime": "17:00:00.0000000", "timeZone": { "name": "Pacific Standard Time" } } }, However, I don't need any of the other information provided in the response. I only want to see the scheduleId and the availabilityView, because the response takes forever to load with many rooms in the schedules request. I've been looking at the available ways to filter a response through parameters in the POST request at: https://docs.microsoft.com/en-us/graph/query-parameters. However, any of the filters I seem to apply to my address do not seem to have any affect on the response. I've tried https://graph.microsoft.com/v1.0/me/calendar/getschedule?$select=availabilityView for the request and other similar variants without any success. They all return the full JSON response. A: It is a OData protocol limitation. Querying Data is only possible on GET requests as documented here. Besides asking for less rooms to begin with. a shorter period or a bigger interval, I don't think there a way to get less data today.
{ "pile_set_name": "StackExchange" }
Q: Combination of smartphones' pattern password Have you ever seen this interface? Nowadays, it is used for locking smartphones. If you haven't, here is a short video on it. The rules for creating a pattern is as follows. We must use four nodes or more to make a pattern at least. Once a node is visited, then the node can't be visited anymore. You can start at any node. A pattern has to be connected. Cycle is not allowed. How many distinct patterns are possible? A: I believe the answer can be found in OEIS. You have to add the paths of length $4$ through $9$ on a $3\times3$ grid, so $80+104+128+112+112+40=576$ I have validated the $80$, $4$ number paths. If we number the grid $$\begin{array}{ccc}1&2&3\\4&5&6\\7&8&9 \end{array}$$ The paths starting $12$ are $1236, 1254, 1258, 1256$ and there were $8$ choices of corner/direction, so $32$ paths start at a corner. Starting at $2$, there are $2145,2147,2369,2365,2541,2547,2587,2589,2563,2569$ for $10$ and there are $4$ edge cells, so $40$ start at an edge. Starting at $5$, there are $8$ paths-four choices of first direction and two choices of which way to turn Added per user3123's comment that cycles are allowed: unfortunately in OEIS there are a huge number of series titled "Number of n-step walks on square lattice" and "Number of walks on square lattice", and there is no specific definition to tell one from another. For $4$ steps, it adds $32$ more paths-four squares to go around, four places to start in each square, and two directions to cycle. So the $4$ step count goes up to $112$. For longer paths, the increase will be larger. But there still will not be too many. A: I don't have the answer as "how to mathematically demonstrate the number of combinations". Still, if that helps, I brute-forced it, and here are the results. $1$ dot: $9$ $2$ dots: $56$ $3$ dots: $320$ $4$ dots: $1624$ $5$ dots: $7152$ $6$ dots: $26016$ $7$ dots: $72912$ $8$ dots: $140704$ $9$ dots: $140704$ Total for $4$ to $9$ digits $:389,112$ combinations A: Was bored at work and solved it total combinations are 389432 if using 3 or more 389112 is using 4 or more.
{ "pile_set_name": "StackExchange" }
Q: Knockout validation on dynamic viewmodel I am creating knockout viewmodel dynamically and this code is working fine. I want to add validation in this viewmodel. Can I add validation in this viewmodel? Is this good approach or should I create viewmodel myself and add validation attributes myself? Or does any client side validation work with data annotations? var viewModel = function () { var self = this; self.States =ko.observableArray(); self.Countries =ko.observableArray(); self.showStates = ko.observable(false); self.saveData = function (self) { //save data function }; } var VM= new viewModel(); $.ajax({ success: function(data) { var newVM = ko.mapping.fromJS(data, {}, VM); // newVM.FirstName, newVM.LastName // I want to add validation in this newVM } A: Since you are using KO Mapping plug-in to load data, you also have the option to hook into the 'create' event and add validation for individual items if you want. Like in the following: $.ajax({ success: function(data) { var mappingOption = { 'FirstName': { create: function (option) { return ko.observable(option.data).extend({ required: true }); } }, 'LastName': { create: function (option) { return ko.observable(option.data).extend({ required: true }); } } } // Now load your viewModel with the mapping option you just specified var newVM = ko.utils.arrayMap(data, function (item) { return ko.mapping.fromJS(item, mappingOption); }); // ... From now on... in your newVM... firstName and lastName will be 'required' } Hope this helps. Thanks.
{ "pile_set_name": "StackExchange" }
Q: Javascript Trigger "right arrow" key event - Force Label Deselection I want to trigger a keyboard event to press "right arrow" key. The purpose is to cancel the highlight. I used the code below to insert a hyper link into the editor content. var range = document.getSelection().getRangeAt(0); var nnode = document.createElement("a"); range.surroundContents(nnode); nnode.innerHTML = url; nnode.setAttribute(url); nnode.focus(); It is highlight by default. I want to trigger an "right arrow" key in order to cancel the highlight and move the cursor to the right. I did many searchs, I tried the most of solutions, but I still get one works. My environment is IE 11. Can I get some help? Thanks! A: So.. here are the resources you're asking for, but I have a solution for your highlighting problem which is none of these. Resources: How to trigger click on page load? Detecting arrow key presses in JavaScript Trigger an UP or DOWN ARROW key event through javascript The actual solution uses JQuery & this resource: JavaScript Set Window selection $("document").ready(function() { window.getSelection().removeAllRanges(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="myDiv"> I am some text! </div> See the JSFiddle: JSFiddle
{ "pile_set_name": "StackExchange" }
Q: Reordering columns in DataGridView then reading DisplayIndex with hidden columns I have a DataGridView containing some columns - some added automatically and some added when a user performs a certain action. Some of the auto-generated columns are not visible, and the visible columns are frozen and read-only. From the user-added columns that are visible, a user can re-order these, and I use the order of these columns for something else later in my code. The auto-generated columns are of the custom type DataGridViewUnincludedMetadataColumn and the user-generated columns are normal DataGridViewColumns. The problem: I am trying to get a DataGridViewColumn[] (called orderedColumnList) which is just the user-generated, visible columns. I use this code to count the number of auto-generated, visible columns: int unincludedVisibleColumnCount = 0; foreach (var unincludedCol in dataGridView_Metadata.Columns.OfType<DataGridViewUnincludedMetadataColumn>()) { if (unincludedCol.Visible) { unincludedVisibleColumnCount++; } } I use this code to get my orderedColumnList: foreach (DataGridViewColumn col in dataGridView_Metadata.Columns) { if (col.GetType() != typeof(DataGridViewUnincludedMetadataColumn)) { //if the column is going to be visible //add the column to the orderedcolumnlist orderedColumnList[col.DisplayIndex - unincludedVisibleColumnCount] = col; } } The problem is that the DisplayIndex doesn't seem to match up with the actual index of where each column is being displayed. In my tests I'm getting this: Index | DisplayIndex | Where the column actually is in the display 0 | 0 | 0 1 | 1 | 1 2 | 4 | n/a - Visible == false 3 | 6* | 5* 4 | 3 | 3 5 | 2 | 2 6 | 5* | 4* Initially I thought it was just the last column that was off but then I tested by adding another user-generated column and it made the last two columns off by one, so I'm confused as to what the pattern here might be. Why are the starred values different, and how can I check for this in my code? A: I have now figured this out thanks to @stuartd's comment, code is below. This uses the GetFirstColumn() and GetNextColumn() methods on the DataGridViewColumnCollection object with DataGridViewElementStates.Visible. List<DataGridViewColumn> orderedColumnList = new List<DataGridViewColumn>(); DataGridViewColumn firstCol = dataGridView_Metadata.Columns.GetFirstColumn(DataGridViewElementStates.Visible); DataGridViewColumn nextCol = dataGridView_Metadata.Columns.GetNextColumn(firstCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None); while (nextCol != null) { if (nextCol.GetType() != typeof(DataGridViewUnincludedMetadataColumn)) { orderedColumnList.Add(nextCol); } nextCol = dataGridView_Metadata.Columns.GetNextColumn(nextCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None); }
{ "pile_set_name": "StackExchange" }
Q: Fastest way to check whether image (img HTML element) is not protected by CORS I occurred to have a problems when I copied image from a site (context menu->copy image) and pasted it in my script (in contenteditable div). <img> appears in the div, however an attempt to drawImage it on <canvas> will cause errors if you try to get image data of the canvas: You can draw on the canvas without errors, but not retrieve the pixel data or DataURL. In cases of such images, I'd like to use CORS proxy to have full access to the data. How can detect that I have no right to access data of <img> tag or URL? What's the fastest way? I had this problem (and still have) in a image paste upload script for StackExchange. Edit: Further explanations of the problem if you're still not sure what do I mean: Why try/catch is not a solution? You can draw any image on canvas and you can even perform further draw operations: The image source. It doesn't allow CORS! Why parsing the URL doesn't help? Some remote images allow CORS and do not throw any errors. For example the avatars from Gravatar. A: I came up with the solution which actually uses try ... catch as @wwwmarty suggested. It's probably not very fast as of CPU speed and a little bit retarded, but it works: HTMLImageElement.prototype.isTainting = function() { var canvas = document.createElement("canvas"); canvas.getContext("2d").drawImage(this,0,0); try { canvas.toDataURL(); return true; } catch() {return false;}; return false; } I also created quite big fiddle where you can inspect behavior of the crossorigin attribute.
{ "pile_set_name": "StackExchange" }
Q: Add custom Javascript to Prestashop After asking on the Prestashop forum and receiving no reply I wanted to ask you guys and hope for an answer. I am trying to add an animated snow plugin to my shop but after looking at the header.tpl file which instructs you to not edit - how do I add my own Javascript to the head of my template? I duplicated the default-theme and I am working from that. A: If the theme is default-bootstrap, then yes, you probably shouldn't modify it, if you intend to upgrade it (can be automatically upgraded using autoupgrade module). Same can be true for 3rd party themes which are actively updated. But usually 3rd party themes don't get upgraded at all, which means you can modify theme templates. Because the templates are sort-of too complex to be extended by a child theme, it is ok to edit them directly. PretaShop doesn't have child-parent theme system. Just edit the templates directly. If you would like your changes to be portable accross themes, then you should probably make a module. Inside the module use special functions to add .js and .css files to header: mymodule.php ... public function install() { ... $this->registerHook('displayHeader'); ... } public function hookDispayHeader() { $this->context->controller->addJS($this->_path.'js/script.js'); $this->context->controller->addCSS($this->_path.'css/style.css'); } If you need a quick way to add, just edit theme's global.css and global.js You may also add the stysheet and script to autload folder: themes/theme1/css/autoload/ and themes/theme1/js/autoload/. Files inside these folder will be loaded for all pages.
{ "pile_set_name": "StackExchange" }
Q: discordjs/nodejs , How can i check if a message only contains custom emotes? I'm building my own discordbot in NodeJS by using discordjs. With the code below you can recognize if the message contains only a emote client.on("message", function(message){ var bool = message.content.match(/^(:[^:\s]+:|<:[^:\s]+:[0-9]+>|<a:[^:\s]+:[0-9]+>)$/); an emote shows like this when you do an console.log (the emote Kappa as an example) : <:Kappa:731053321502326797> Now it only matches when 1 emote is in the message But it doesnt match if a message contains 2 emotes with a space between it. How can i make this possible? A: Use ^(:[^:\s]+:|<:[^:\s]+:[0-9]+>|<a:[^:\s]+:[0-9]+>)+$ See proof. Explanation: NODE EXPLANATION -------------------------------------------------------------------------------- ^ the beginning of the string -------------------------------------------------------------------------------- ( group and capture to \1 (1 or more times (matching the most amount possible)): -------------------------------------------------------------------------------- : ':' -------------------------------------------------------------------------------- [^:\s]+ any character except: ':', whitespace (\n, \r, \t, \f, and " ") (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- : ':' -------------------------------------------------------------------------------- | OR -------------------------------------------------------------------------------- <: '<:' -------------------------------------------------------------------------------- [^:\s]+ any character except: ':', whitespace (\n, \r, \t, \f, and " ") (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- : ':' -------------------------------------------------------------------------------- [0-9]+ any character of: '0' to '9' (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- > '>' -------------------------------------------------------------------------------- | OR -------------------------------------------------------------------------------- <a: '<a:' -------------------------------------------------------------------------------- [^:\s]+ any character except: ':', whitespace (\n, \r, \t, \f, and " ") (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- : ':' -------------------------------------------------------------------------------- [0-9]+ any character of: '0' to '9' (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- > '>' -------------------------------------------------------------------------------- )+ end of \1 (NOTE: because you are using a quantifier on this capture, only the LAST repetition of the captured pattern will be stored in \1) -------------------------------------------------------------------------------- $ before an optional \n, and the end of the string
{ "pile_set_name": "StackExchange" }
Q: How to force a Manipulator inside a Manipulate to auto-run? I want to use a slider (not drop-down list) for a list of discreteValues to do the Manipulate (I used Sin[x] below for simplicity, but the actual one is much more complicated). At the same time, I needed to show a function of x next to the slider (below I used x^2 as an example). Besides, since the output would be used by other notebook, I would use SaveDefinitions -> True. discreteValues = {0, 0.2, 0.4, 0.8, 1.6, 2.0, 2.2}; Manipulate[Sin[x],Row[{Control[{x, discreteValues, Manipulator, AutoAction -> False}], Dynamic[x^2]}], SaveDefinitions -> True] By default, the slider won't auto-run. How can I force the slider to auto-run by default? I tried to simply change Manipulate to Animate, but I got the error. Many thanks! A: Replace Manipulator with Animator: Manipulate[Sin[x], Row[{Control[{x, discreteValues, Animator}], Dynamic[x^2]}], SaveDefinitions -> True]
{ "pile_set_name": "StackExchange" }
Q: How to update MS Access database I need a simple program to update MS Access database fields. I followed an online tutorial which was simple and had the code working. But it doesnt seem to work anymore when I reimplement it. Here's my code. public partial class Form1 : Form { public Form1() { InitializeComponent(); } OleDbConnection conn; OleDbDataAdapter da; DataSet ds; OleDbCommandBuilder cb; DataRow row; private void Form1_Load(object sender, EventArgs e) { conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\\test.mdb"); da = new OleDbDataAdapter("select* from user", conn); ds = new DataSet(); conn.Open(); da.Fill(ds, "user"); conn.Close(); } private void button1_Click(object sender, EventArgs e) { cb = new OleDbCommandBuilder(da); row = ds.Tables["user"].Rows[0]; row[3] = "hello"; da.Update(ds, "user"); } } user is the table name of my database. What I tried to do is update the field row[0] (first row) and column[3] (4th column) with the string hello.. The error i get is Synatx error in FROM clause. After some internet reading, I found user has to be in square brackets. So I made it this. public partial class Form1 : Form { public Form1() { InitializeComponent(); } OleDbConnection conn; OleDbDataAdapter da; DataSet ds; OleDbCommandBuilder cb; DataRow row; private void Form1_Load(object sender, EventArgs e) { conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\\test.mdb"); da = new OleDbDataAdapter("select* from [user]", conn); ds = new DataSet(); conn.Open(); da.Fill(ds, "user"); conn.Close(); } private void button1_Click(object sender, EventArgs e) { cb = new OleDbCommandBuilder(da); row = ds.Tables["user"].Rows[0]; row[3] = "hello"; da.Update(ds, "user"); } } When I do this, I get a new error, Syntax error in UPDATE statement. I did a lot of internet reading but none seems to address this. They all have used Update command differently. I know only this way. What's wrong in my code? Especially since this worked before. Or isn't this way of updating a proper technique? Please help me with the code and not technical terms which I don't follow. Or any other procedure to update in ms access? Thanks. A: I've never tried to access an Access database with a .NET DataSet before, but I think you could replace the code in button1_Click with something like this: private void button1_Click(object sender, EventArgs e) { conn.Open(); string query = "UPDATE [user] SET [columnname] = ? WHERE id = ?"; var accessUpdateCommand = new OleDbCommand(query, conn); accessUpdateCommand.Parameters.AddWithValue("columnname", "hello"); accessUpdateCommand.Parameters.AddWithValue("id", 123); // Replace "123" with the variable where your ID is stored. Maybe row[0] ? da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); conn.Close(); } Yes, I know you'd be losing some of the benefits of the DataSet, but research suggests that the regular OleDbDataAdapter.Update function doesn't play well with Access.
{ "pile_set_name": "StackExchange" }
Q: Distributivity of lattice $\left(N,\:\le \right)$ The exercises asks me to prove/verify the distributivity of the lattice $\left(N,\:\le \right)$ I've no clue on how to approach this problem, because at the seminar we didn't really study lattices as ordered sets(not sure if this is the correct English term), but only as algebraic structures(even though the professor insists that we know both). Anyhow, how do I go about solving this? A: Note that $(\mathbb{N}, \le )$ as an ordered set is isomorphic to a sublattice of $(\mathcal{P}(\mathbb{N}) , \subseteq)$ by the embedding $$n \mapsto \{ 1, \dots , n\}$$ Now, it is well known that for any set $X$ the lattice $(\mathcal{P}(X) , \subseteq)$ is distributive (because $\cap, \cup$ distribute each other), hence distributivity follows.
{ "pile_set_name": "StackExchange" }
Q: Interpreting an integral under the Riemann Stieltjes form. I've long ago solved an exercise that was as follows: This problem provides a new way of finding $ \displaystyle \int\limits_a^b {{x^p}dx} $ for $ 0 < a < b $. It consists of using partitions $t_i$ for which the quotient $\displaystyle \frac{t_i}{t_{i-1}}$ is constant, instead of being $ t_i - t_{i-1} $ constant. The solutions produced $ t_i = a c^{\frac{i}{n}} $ where $ c = \frac{b}{a} $ and upper and lower sums being: $$ U \left( f, P \right) = \left( {{b^{p + 1}} - {a^{p + 1}}} \right)\frac{{{c^{\frac{p}{n}}}}}{{1 + {c^{\frac{1}{n}}} + {c^{\frac{2}{n}}} + \cdots + {c^{\frac{p}{n}}}}} $$ $$L\left( f, P \right) = \left( {{b^{p + 1}} - {a^{p + 1}}} \right)\frac{1}{{1 + {c^{\frac{1}{n}}} + {c^{\frac{2}{n}}} + \cdots + {c^{\frac{p}{n}}}}}$$ Thus you have $$U \left( f, P \right) - L \left( f, P \right) = \left( {{b^{p + 1}} - {a^{p + 1}}} \right)\left[ {\frac{{{c^{\frac{p}{n}}} - 1}}{{1 + {c^{\frac{1}{n}}} + {c^{\frac{2}{n}}} + \cdots + {c^{\frac{p}{n}}}}}} \right]$$ which implies that for some $\epsilon > 0$ and $N$ sufficiently large. $$ U \left( f, P \right) - L \left( f, P \right) < \epsilon $$ Finally you get the expected result $$\int\limits_a^b {{x^p}dx} = \frac{{{b^{p + 1}} - {a^{p + 1}}}}{{p + 1}} $$ I' m wondering if this change in the differential $ t_i - t_{i-1} = \Delta{t_i}$ versus $\displaystyle \frac{t_i}{t_{i-1}}= \Delta{t_i}$ can be interpreted as changing the integrator $d\alpha$. I've started reading about the Riemann Stieltjes integration so it rang a bell, but don't expect me to know a lot about it, just the basics. A: Just for the sake of closing, the integrator would we $$\log x$$ so one has $$\int_a^b x^{p} dx=\int_a^b x^{p+1} d({\log x})$$ as Riemann integral. Thus with $a_n=\log u_{n}$ and $\dfrac {u_{n+1}}{ u_{n}}=\rm const.$ $$\Delta a_n=a_{n+1}-a_n=\log u_{n+1} - \log u_{n}=\log \dfrac {u_{n+1}}{ u_{n}}=\log c =\rm const.$$
{ "pile_set_name": "StackExchange" }
Q: MySQL: Add stoplist How could I add a own stoplist to MySQL 5? A: Guessing you're asking about how to set the stopwords list for MySQL FULLTEXT search, this portion of the manual page 11.8.6. Fine-Tuning MySQL Full-Text Search could interest you (quoting) : To override the default stopword list, set the ft_stopword_file system variable. (See Section 5.1.3, “Server System Variables”.) The variable value should be the path name of the file containing the stopword list, or the empty string to disable stopword filtering. The server looks for the file in the data directory unless an absolute path name is given to specify a different directory. After changing the value of this variable or the contents of the stopword file, restart the server and rebuild your FULLTEXT indexes. The stopword list is free-form. That is, you may use any nonalphanumeric character such as newline, space, or comma to separate stopwords. Exceptions are the underscore character (“_”) and a single apostrophe (“'”) which are treated as part of a word. The character set of the stopword list is the server's default character set; see Section 9.1.3.1, “Server Character Set and Collation”.
{ "pile_set_name": "StackExchange" }
Q: Show that a graph with with exactly 1 vertex of degree 1, contains a cycle I realize this question has been asked before, but I'm still confused about the answers, so bare with me. I was asked this question on an Exam recently, and tried to prove it by constructing the graph: "Start with a vertex $v_0$ which is the only vertex with degree 1, then it's neighbour $v_1$ must have degree at least 2, such that it must be connected to a vertex $v_2$ and $v_2$ $\ne$ $v_0$, and now $v_2$ having degree 2, either has an edge back to $v_1$, forming a cycle or is connected to another vertex $v_3$, and giving that the number of vertices is n, vertex $v_n$ must be connected to a vertex belonging to the set S, such that S={$v_1$, $v_2$, ........, $v_{n-1}$}, thus, the graph must have a cycle". My proof was dismissed as it didn't cover all possibilities, and i was told to never construct graphs in problems, always destruct them, which didn't make any sense, and still doesn't. What irritated me even more was that the proof that got the highest points, started with, and i quote: "Suppose that g is a connected acyclic graph, which has exactly 1 vertex of degree 1, so by definition of a tree, g must be a tree". Completely wrong, since a tree must have 2 vertices of degree 1. Which brings me to my second point. I saw other proofs that start with "Let G be a graph with exactly 1 vertex of degree 1, and let's assume it's acyclic" and then they go on to show that it contradicts with a tree having the longest path containing 2 vertices of degree 1. Now if we assume it's acyclic, doesn't that straight away contradict the theorem that says "A graph with 1 vertex of degree 1 must have a cycle" and we're done, nothing more to proof. One more proof i managed to come up with is as follows: "Since every vertex in this graph G has degree at least 2, then there must be 2 distinct paths between any 2 vertices in G, except for $v_0$ ($v_0$ being the only vertex with degree 1), and thus the graph must contain a cycle. I'm really confused about this question, it looks straight forward, but clearly not, apologies for ranting a bit, it's just frustrating. I hope somebody can clear the confusion. A: The idea of your proof is fine and can be adapted into a working proof. However it's character is that of a "constructive proof" so it's very important that all the steps in the conctruction be motivated and phrased well. Whatever issues there may have been probably lie embedded in your specific formulations and we don't have that. For example it feels a bit weird to talk about constructing a graph when what you really should be doing is investigate the object you've been given. Rather than saying you're constructing the graph you should phrase it as if the graph already exists and you're talking about that object. You're instead describing how one constructs the cycle given the graph. This sort of argument basically mirrors the proof of the existence (and uniqueness) of the greatest common denominator where you get a sequence of remainders where you eventually stop when you've reached your result so it's entirely legitimate. Regarding the other proof: What irritated me even more was that the proof that got the highest points, started with, and i quote: "Suppose that g is a connected acyclic graph, which has exactly 1 vertex of degree 1, so by definition of a tree, g must be a tree". Completely wrong, since a tree must have 2 vertices of degree 1. As stated its a bit of a clumsy formulation but the idea is still clear that its an "(indirect) proof by contradiction" and in terms of complexity it's probably the easiest way to prove this result. You assume there is a graph with only one vertex of degree 1 and no cycles and prove that such an object cannot exist (by contradiction), and then conclude all graphs with a single vertex of degree 1 have cycles (are not trees) The contradiction is the proof. One more proof i managed to come up with is as follows: "Since every vertex in this graph G has degree at least 2, then there must be 2 distinct paths between any 2 vertices in G, except for $v_0$($v_0$ being the only vertex with degree 1), and thus the graph must contain a cycle. Unless you refer to theorems which support the "Since"-claim this is just a statement without any justification and thus doesn't work as a proof. Also I'm not entirely sure that its true either at least not unless we say how distinct the paths are to be.
{ "pile_set_name": "StackExchange" }
Q: Why can not I use "TermDocumentMatrix"? Why can not I use "TermDocumentMatrix"? I used the following command to unify plural words in singular form, but I get an error. crudeCorp <- tm_map(crudeCorp, gsub, pattern = "smells", replacement = "smell") crudeCorp <- tm_map(crudeCorp, gsub, pattern = "feels", replacement = "feel") crudeDtm <- TermDocumentMatrix(crudeCorp, control=list(removePunctuation=T)) Error in UseMethod("meta", x) : no applicable method for 'meta' applied to an object of class "character" How should I solve it? 1. Is there a command to change from singular to cleaning? 2. Is this command I used wrong? I will attach the following code to the sentence processing and matrix. library(tm) library(XML) crudeCorp<-VCorpus(VectorSource(readLines(file.choose()))) #(Eliminating Extra Whitespace) crudeCorp <- tm_map(crudeCorp, stripWhitespace) #(Convert to Lower Case) crudeCorp<-tm_map(crudeCorp, content_transformer(tolower)) # remove stopwords from corpus crudeCorp<-tm_map(crudeCorp, removeWords, stopwords("english")) myStopwords <- c(stopwords("english"), "can", "will","got","also","goes","get","much","since","way","even") myStopwords <- setdiff(myStopwords, c("will","can")) crudeCorp <- tm_map(crudeCorp, removeWords, myStopwords) crudeCorp<-tm_map(crudeCorp,removeNumbers) crudeCorp <- tm_map(crudeCorp, gsub, pattern = "smells", replacement = "smell") crudeCorp <- tm_map(crudeCorp, gsub, pattern = "feels", replacement = "feel") #-(Creating Term-Document Matrices) crudeDtm <- TermDocumentMatrix(crudeCorp, control=list(removePunctuation=T)) example : my data 1. I'M HAPPY 2. how are you? 3. This apple is good (skip) A: Whyn't use below code for stemming & Punctuation removal? crudeCorp <- tm_map(crudeCorp, removePunctuation) crudeCorp <- tm_map(crudeCorp, stemDocument, language = "english") crudeDtm <- DocumentTermMatrix(crudeCorp) Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Updateable Data Grid using Linq to SQL in WinForms I'm populating a datagrid using Linq--standard kind of stuff (code below). For some reason however my ultraDataGrid is stuck in some kind of read-only mode. I've checked all the grid properties I can think of. Is that a result of binding to a Linq data source? Anyone have example code of an updatable grid that uses Linq? db = New DataContext myData = New dataClass dataUltraGrid.DataSource = From table _ In db.profiles _ Select table.field1, table.field2... A: Found the solution: use lambda expressions to filter the entity and bind directly to the entity.
{ "pile_set_name": "StackExchange" }
Q: Moving a 2D numpy subarray efficiently I have a numpy array that represents a greyscale image, such as image = numpy.array([ [.0, .0, .0, .0, .1, .3, .5, .0], [.0, .0, .0, .0, .4, .4, .6, .0], [.0, .0, .0, .0, .3, .3, .7, .0], [.0, .0, .0, .0, .0, .0, .0, .0], [.0, .0, .0, .0, .0, .0, .0, .0], [.0, .0, .0, .0, .0, .0, .0, .0], ]) I would like to move a sub-array to a new location, filling the values left behind with some constant (say 0.0). For example, moving the 3x3 sub-array from center position of (1, 5) to center position (3, 3) would result in: numpy.array([ [.0, .0, .0, .0, .0, .0, .0, .0], [.0, .0, .0, .0, .0, .0, .0, .0], [.0, .0, .1, .3, .5, .0, .0, .0], [.0, .0, .4, .4, .6, .0, .0, .0], [.0, .0, .3, .3, .7, .0, .0, .0], [.0, .0, .0, .0, .0, .0, .0, .0], ]) Is there an efficient way to perform such a move? A: Since you know the starting index of where you want to move from and move to, we can use np.zeros_like and numpy indexing: h = w = 3 sub = image[0:0+w,4:4+h] out = np.zeros_like(image) Then assign: out[2:2+w, 2:2+h] = sub Output: array([[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0.1, 0.3, 0.5, 0. , 0. , 0. ], [0. , 0. , 0.4, 0.4, 0.6, 0. , 0. , 0. ], [0. , 0. , 0.3, 0.3, 0.7, 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
{ "pile_set_name": "StackExchange" }
Q: Putting an array into a table with SimpleXMLobject using php Array ( [0] => Array ( [Title] => SimpleXMLElement Object ( [0] => aa ) [Pubdate] => SimpleXMLElement Object ( [0] => aa ) [Link] => SimpleXMLElement Object ( [0] => aa ) ) [1] => Array ( [Title] => SimpleXMLElement Object ( [0] => bb ) [Pubdate] => SimpleXMLElement Object ( [0] => bb ) [Link] => SimpleXMLElement Object ( [0] => bb ) ) I want to put this into a table which has (Title, Pubdate, Link) as its columns. I am really confused to how to put it into mysql table when there is SimpleXMLElement Object and [0] in the way. If those were not in the way, I would easily be able to put it into the table, but because those are there and I have never seen them before, I am terribly confused. This is what I have tried: foreach($string as $item){ INSERT into table (Title, Pubdate, Link)VALUES($item->title, $item->pubDate, $item->link) } FYI this is how I made the array: $string = $con->channel->item; $table = array(); foreach ($string as $item) { $table[] = array( 'Title' => $item->title, 'Pubdate' => $item->pubDate, 'Link' => $item->link ); } A: You can't just insert that in the database. Implode first the array. Try this: $string = $con->channel->item; $table = array(); foreach ($string as $item) { $sql = mysqli_query("INSERT INTO table (Title, Pubdate, Link)VALUES('$item->title', '$item->pubDate', '$item->link')"; ); }
{ "pile_set_name": "StackExchange" }
Q: Using SQL Statement in TO_DATE Function? I have to use SQL statement in TO_DATE function. Like: TO_DATE((select MAX(VERSION) from TABLE_B),'MM/DD/YYYY') When I use TO_DATE like that, I encounter an error. Like: [Error] Execution (9: 32): ORA-01858: a non-numeric character was found where a numeric was expected Is there a way for using TO_DATE function like that? A: select to_date(max(version), 'mm/dd/yyyy') from table_b might be a better choice. Note, though, that if VERSION column (it is ... what? A string?) contains something that doesn't match that date format, TO_DATE will fail, exactly with an error you got. Therefore, make sure that data is correct.
{ "pile_set_name": "StackExchange" }
Q: Phone number duplication detector I am doing the POJ 1002 question. My code works fine but the website says the compilation time is more than 2000ms, which is not accepted. How can I improve my time-wise performance? Problem Statement Input — The input will consist of one case. The first line of the input specifies the number of telephone numbers in the directory (up to 100,000) as a positive integer alone on the line. The remaining lines list the telephone numbers in the directory, with each number alone on a line. Each telephone number consists of a string composed of decimal digits, uppercase letters (excluding Q and Z) and hyphens. Exactly seven of the characters in the string will be digits or letters. Output — Generate a line of output for each telephone number that appears more than once in any form. The line should give the telephone number in standard form, followed by a space, followed by the number of times the telephone number appears in the directory. Arrange the output lines by telephone number in ascending lexicographical order. If there are no duplicates in the input print the line: No duplicates. import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class Main{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int total = scan.nextInt(); scan.nextLine(); // But why? String[] numbers = new String[total]; Map<String, Integer> dict = new TreeMap<String, Integer>(); for(int i = 0; i < total; i++) { numbers[i] = scan.nextLine(); numbers[i] = convert(numbers[i]); if(!dict.containsKey(numbers[i])) { dict.put(numbers[i], 1); } else { dict.put(numbers[i], dict.get(numbers[i]) + 1); } } scan.close(); boolean hasDuplication = true; for(String number: dict.keySet()) { if(dict.get(number) > 1) { hasDuplication = false; System.out.println(number + " " + dict.get(number)); } } if(hasDuplication) { System.out.println("No duplicates."); } } public static String convert(String raw) { raw = raw.replaceAll("-", ""); raw = raw.toLowerCase(); String number = ""; for(int i = 0; i < raw.length(); i++) { number += parse(raw.charAt(i)); } number = number.substring(0, 3) + "-" + number.substring(3); return number; } public static char parse(char digit) { if(digit >= 'a' && digit < 'q') { digit = (char) ((digit-'a') / 3 + '2'); } else if(digit > 'q' && digit < 'z') { digit = (char) ((digit-'q') / 3 + '7'); } return digit; } } A: Chomp the new line scan.nextLine(); // But why? Nothing to do with performance, but Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()? explains this. Remove unnecessary data structure String[] numbers = new String[total]; You never use numbers as an array. You could get rid of it entirely. numbers[i] = scan.nextLine(); numbers[i] = convert(numbers[i]); if(!dict.containsKey(numbers[i])) { dict.put(numbers[i], 1); } else { dict.put(numbers[i], dict.get(numbers[i]) + 1); } Replace numbers[i] with a single String. String number = convert(scan.nextLine()); Integer count = dict.get(number); if (count == null) { count = 0; } count++; dict.put(number, count); Now we don't keep an array around for nothing. I also changed the get/put pattern. This saves having to do both the containsKey check and the get. Consider other data structures Map<String, Integer> dict = new TreeMap<String, Integer>(); I would expect a TreeMap to be slower than a HashMap for most applications that depend on insert and read efficiency. This is especially so since it sorts on keys and what you want is to find all with at least value 2. You'd need to override the comparison to get that behavior. You don't use the read behavior that would be helpful. And you accept the slower writes. Map<String, Integer> dict = new HashMap<>(); This should perform faster for larger inputs. Pick the right method for(String number: dict.keySet()) { if(dict.get(number) > 1) { hasDuplication = false; System.out.println(number + " " + dict.get(number)); } } This is the use case for an entrySet. for (Map.Entry<String, Integer> entry : dict.entrySet()) { if (entry.getValue() > 1) { hasDuplication = true; System.out.println(entry.getKey() + " " + entry.getValue()); } } Now we don't have to do an expensive get lookup operation on each iteration. I'd also switch the meaning of hasDuplication to match the name. Don't forget to switch it the other two places as well. boolean hasDuplication = true; to boolean hasDuplication = false; and if(hasDuplication) { to if (!hasDuplication) { Other possibilities If this doesn't help, consider splitting reading the input from processing it. So something like for (int i = 0; i < numbers.length; i++) { numbers[i] = scan.nextLine(); } scan.close(); for (String number : numbers) { number = convert(number); Integer count = dict.get(number); if (count == null) { count = 0; } count++; dict.put(number, count); } I didn't test this, so you may have to declare a new variable rather than reusing number. A: Use a profiler to measure where the time is spent! That said, your convert method is very inefficient. It uses multiple string operations. You can make it one-pass using the characters as they come by. We need some extra cases to be able to prevent upper/lowercasing. public static String toBaseForm(String raw) { StringBuilder sb = new StringBuilder(); for (char ch : raw.toCharArray()) { if (ch >= 'A' && ch < 'Q') { sb.append((char) ((ch - 'A') / 3 + '2')); } else if (ch >= 'Q' && ch < 'Z') { sb.append((char) ((ch - 'Q') / 3 + '7')); } else if (ch >= 'a' && ch < 'q') { sb.append((char) ((ch - 'a') / 3 + '2')); } else if (ch >= 'q' && ch < 'z') { sb.append((char) ((ch - 'q') / 3 + '7')); } else if (ch >= '0' && ch <= '9') { sb.append(ch); } if (sb.length() == 3) { sb.append('-'); } } return sb.toString(); } A: String allocations You make a number of allocations that may not be obvious: public static String convert(String raw) { raw = raw.replaceAll("-", ""); // possibly new string, if contains hyphen raw = raw.toLowerCase(); // possibly new string, if contains uppercase String number = ""; for(int i = 0; i < raw.length(); i++) { number += parse(raw.charAt(i)); // definitely new string, raw.length() times! } number = number.substring(0, 3) + "-" + number.substring(3); // three new strings: sub + sub + result return number; } String is immutable in Java, meaning any operations that result in different char data will result in a different string. String.substring also (usually) creates a new string. The input "888-GLOP" ends up creating eleven new strings before returning its final, twelfth string! Map.get + Map.put = Map.merge if(!dict.containsKey(numbers[i])) { // Θ(log n) dict.put(numbers[i], 1); // Θ(log n) } else { dict.put(numbers[i], dict.get(numbers[i]) + 1); // Θ(log n) + Θ(log n) } // --> dict.merge(numbers[i], 1, Integer::sum); Still, you are sorting/comparing strings each time you want to update your map. You could split into two parts: one part that checks whether you have already seen the input before (doesn't need to be sorted), and another that keeps track of your actual duplicates: HashSet<String> seen; TreeMap<String, Integer> duplicates; // Set.add returns false if already contained if ( !seen.add(number) ) { // Θ(1) duplicates.merge(number, 1, Integer::sum); // Θ(log n) } // printing later -- don't forget to add 1 to dupe count! duplicates.forEach( (k,v) -> System.out.println( ... (v + 1) ... ); ) Alternatively, you can turn the data around: HashMap<String, Integer> frequency; TreeSet<String> duplicates; if ( frequency.merge(number, 1, Integer::sum) > 1 ) { // Θ(1) duplicates.add(number); // Θ(log n) } duplicates.forEach( k -> System.out.println( ... frequency.get(k) ... ); ) Alternative implementation Consider that: Phone numbers have a normal form, which is NNN-NNNN, with N being a digit. This makes phone numbers contain 7 digits worth of information. That fits in an int. → Less memory usage, better cache usage. You don't need to retain the original form. → We can use destructive methods. Your incoming alphabet is limited: uppercase letters, decimal digits, and the hyphen. → switch-case and/or table parsing are viable. You need to output only the duplicates. → We don't need to store everything, but we might end up having to. You need to output the duplicates in lexicographical order. → We don't need to keep everything sorted; only the duplicates. Leading to: import java.util.*; public class Main { public static void main(String[] args) { final Scanner in = new Scanner(System.in); int count = in.nextInt(); /* We split duplicate detection in an unsorted part that just saves whether * we've seen it before, and a sorted part that stores actual duplicates in * lexicographical order. */ final Set<Integer> seen = new HashSet<>(); final NavigableMap<Integer, Integer> duplicates = new TreeMap<>(); while ( count-- > 0 ) { String strnum = in.next(); final Integer number = parse(strnum); if ( !seen.add(number) ) { // number of dupes is number of encounters minus one duplicates.merge(number, 1, Integer::sum); } } if ( duplicates.isEmpty() ) { System.out.println("No duplicates."); } else { for ( Map.Entry<Integer, Integer> duplicate : duplicates.entrySet() ) { // don't forget to add one to the dupe count to get total count System.out.println(format(duplicate.getKey()) + " " + (duplicate.getValue() + 1)); } } } /** Formats a parsed phone number to its normal form (NNN-NNNN). */ static String format(int phoneNumber) { final int prefix = phoneNumber / 10000; final int suffix = phoneNumber % 10000; return String.format("%03d-%04d", prefix, suffix); } /** Parses an unformatted phone number string, considering only the alphanumerics. * Does not guard for overflow. */ static int parse(String number) { int retval = 0; for ( int i = 0; i < number.length(); i++ ) { int digit; final char c = number.charAt(i); switch ( c ) { case '0': digit = 0; break; case '1': digit = 1; break; case '2': case 'A': case 'B': case 'C': digit = 2; break; case '3': case 'D': case 'E': case 'F': digit = 3; break; case '4': case 'G': case 'H': case 'I': digit = 4; break; case '5': case 'J': case 'K': case 'L': digit = 5; break; case '6': case 'M': case 'N': case 'O': digit = 6; break; case '7': case 'P': case 'R': case 'S': digit = 7; break; case '8': case 'T': case 'U': case 'V': digit = 8; break; case '9': case 'W': case 'X': case 'Y': digit = 9; break; default: continue; } retval = 10 * retval + digit; } return retval; } }
{ "pile_set_name": "StackExchange" }
Q: ADx analytics android integration issue I try to integrate ADx mobile analytics into my android application. Maby something wrong with my AndroidManifest file. Can anyone provide me with rigth manifest integration. Thanks. I have such error log: 02-09 13:33:38.328: E/AdXAppTracker(13547): Add APP_ID to AndroidManifest.xml file. For more detail integration document. 02-09 13:33:38.328: I/AdXAppTracker(13547): URL parameters: udid=&androidID=447b5493f5e9c26f&device_name=&device_type=&os_version=&country_code=&language=&app_id=&clientid=&app_version=&tag_version=2.0a& 02-09 13:33:38.339: I/AdXAppTracker(13547): baseURL: http://ad-x.co.uk/atrk/android? 02-09 13:33:38.339: I/AdXAppTracker(13547): requestURL: http://ad-x.co.uk/atrk/android?udid=&androidID=447b5493f5e9c26f&device_name=&device_type=&os_version=&country_code=&language=&app_id=&clientid=&app_version=&tag_version=2.0a& 02-09 13:33:38.910: I/AdXAppTracker(13547): -------------------- 02-09 13:33:38.921: I/AdXAppTracker(13547): response status: 200 02-09 13:33:38.929: I/AdXAppTracker(13547): response size: 62 02-09 13:33:38.933: I/AdXAppTracker(13547): response: 02-09 13:33:38.933: I/AdXAppTracker(13547): <?xml version="1.0" encoding="UTF-8"?><Success>false</Success> 02-09 13:33:38.937: I/AdXAppTracker(13547): -------------------- 02-09 13:33:38.953: E/AdXAppTracker(13547): AdX Connect call failed. A: Maby my solution will be helpfull to anyone. So I was integrating this into the project on flash for Android. I have to write an native extention to include Ad-x analytics into my project. This error I got, because I have added xml properties to AndroidManifest.xml file, not in MyProj-app.xml file. When I added it into proper place - all works great.
{ "pile_set_name": "StackExchange" }
Q: Need Listbox to capture first selecteditem property as SelectedItem, rather than the PropertyChanged *TO* I have a listbox that, when an item is selected, invokes a method that executes a Stored Procedure. The problem is that when the first item is selected, my PropertyChanged event doesn't fire unless the selection is changed from one item to another. Thus the second item SelectedItem PropertyChanged notification is fired, but it looks like selecting the first item is just seen as entering the listbox, instead of entering the listbox AND selecting the item the click occurs on. Also, I can't just click twice on the same item to get the notification to fire, I have to actually select a different property for the event to occur. What is the best way to get the item I first click on upon entering the listbox to be the SelectedItem, having the PropertySelected/Property Changed event firing on this item? I hope this is clear. Below is my code, thanks in advance! In my viewmodel: public ObjectClass SelectedObject { get { return _SelectedObject; } set { _SelectedObject = value; base.OnPropertyChanged("SelectedObject"); } } void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case "SelectedObject" : UpdateSelectedStuffList.StoredProcedureMethod(this); } } In my view: <ListBox ItemsSource="{Binding Path=ObjectCollection, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="objectName" SelectedItem="{Binding Path=SelectedObject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> I was thinking that instead of using PropertyChangedEventArgs, there would be something like "PropertySelectedEventArgs." OR, maybe I need to implement INotifyPropertyChanging? A: If you want this to fire even if you select the same item twice in a row, I would look at OnClick. Otherwise, consider setting the selected index to -1 so that when the first item is selected by the user, it will have a changed value.
{ "pile_set_name": "StackExchange" }
Q: Swift changing different labels labelData in every loop So i would like to simplify this chunk of code to a simple for loop. But UITextFields and UILabels are giving me some hard time. @IBOutlet var thingsIUse: UITextField! @IBOutlet var orThis: UILabel! saveProgress(year: year, season: season, day: "1", value: "\(Int(day1new.text!)! + Int(day1newExtra.text!)!)") saveProgress(year: year, season: season, day: "2", value: "\(Int(day2new.text!)! + Int(day2newExtra.text!)!)") saveProgress(year: year, season: season, day: "3", value: "\(Int(day3new.text!)! + Int(day3newExtra.text!)!)") saveProgress(year: year, season: season, day: "4", value: "\(Int(day4new.text!)! + Int(day4newExtra.text!)!)") saveProgress(year: year, season: season, day: "5", value: "\(Int(day5new.text!)! + Int(day5newExtra.text!)!)") saveProgress(year: year, season: season, day: "6", value: "\(Int(day6new.text!)! + Int(day6newExtra.text!)!)") saveProgress(year: year, season: season, day: "1Taki", value: day1new.text!) saveProgress(year: year, season: season, day: "2Taki", value: day2new.text!) saveProgress(year: year, season: season, day: "3Taki", value: day3new.text!) saveProgress(year: year, season: season, day: "4Taki", value: day4new.text!) saveProgress(year: year, season: season, day: "5Taki", value: day5new.text!) saveProgress(year: year, season: season, day: "6Taki", value: day6new.text!) To something like this... for k in 1...10{ saveProgress(year: year, season: season, day: "\(k)", value: "\(Int(day\(k)new.text!)! + Int(day\(k)newExtra.text!)!)") saveProgress(year: year, season: season, day: "\(k)Taki", value: day\(k)new.text!) } Any suggestions? A: You can solve this a few ways. One is to use IBOutlet collections. In swift, you define them as such: @IBOutlet var dayLabels: [UILabel]! Then make sure you go in your Xib/Storyboard and add references to your labels by clicking the little "+" beside the collecting name and dragging it to the various labels. Since this is a collection, you can drag like this to many labels just make sure you add them in the order you want them updated. Another way to solve this, is to create the array of the labels you want updated dynamically at runtime, like this: let labelsToUpdate: [UILabel] = [day1new,day2new,day3new,day4new,day5new,day6new] for k in 0...5 { let day = "\(k+1)" let label = labelsToUpdate[k] ... } There are several other optimizations you could do to keep your code clean, but this will be a good start to achieve what you want. Good luck!
{ "pile_set_name": "StackExchange" }
Q: apt - checking if a similar package has been installed This question explains how to find out if a given Debian package has been installed, but it does not take into account "synonyms" when installing via apt-get. For instance, if I try apt-get install libncurses-dev, apt-get replies: Note, selecting 'libncurses5-dev' instead of 'libncurses-dev' And then it installs that package (libncurses5-dev), which is fine by me. But what if I want to make a script to detect if the package has already been installed? dpkg -s libncurses-dev replies that the package is not installed, which is indeed correct, since it's libncurses5-dev that was installed. But I'd like my script to detect that, in this case, it no longer needs to install libncurses-dev. I could not find an option in apt-get to check if the given package or one of its providers has already been installed, such that my script would work when checking for libncurses-dev as well as for libncurses5-dev. A: If you want to write a script to check to see if package libncurses-dev or its alias has been installed, consider the following program flow: Check if the package has been installed with dpkg using the exact name, libncurses-dev in this case. If the above does not evaluate to true, then search apt for the package you are looking for using the non-aliased name: $ apt-cache search libncurses-dev libncurses5-dev - developer's libraries for ncurses It appears that apt-cache search will return the 'alias' if the package has one. If #1 evaluates false and #2 returns an alias, just grab the package's alias and try #1 again. Check dpkg again with the alias name of the package, in this case it would be libncurses5-dev. If dpkg does not find the package by an alias (actually a superseded package) then it must not be installed.
{ "pile_set_name": "StackExchange" }
Q: using groovyxmlslurper from EL in JSP I've been tasked with creating a JSP tag that will allow developers to pass a URI to an xml document, and have an object returned that can be navigated using EL. I have been using groovy and grails quite a bit so I thought of trying something like rval = new XmlSlurper().parseText(myXml); and throwing that into the request so that back in the JSP they might do something like: <mytag var="var"/> ${var.rss[0].title} but that approach doesn't work. Does anyone have any suggestions? A: Gizmo is correct that the problem is that JSPs assume everything is Java, but I doubt that switching to GSP is a practical answer. To work around this, you need to know how Groovy code gets translated to Java. The Groovy code: var.rss[0].title Is roughly equivalent to this Java: var.getProperty("rss").getAt(0).getProperty("title") It may also be necessary to cast each result to a GPathResult, e.g., ((GPathResult)((GPathResult)var.getProperty("rss")).getAt(0)).getProperty("title") Java sucks, huh?
{ "pile_set_name": "StackExchange" }
Q: android basic auth okhttpclient I am connecting to my rest api using retrofit and okHttp client. When I disable Basic authentication on Tomcat everything works flawlessly. When Basic Auth is enabled on Tomcat I get 404 Page not found. Here is my authentication and error output. okHttpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { String credential = Credentials.basic(rest_user, rest_pw); return response.request().newBuilder().header("Authorization", credential).build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); Error log D/YOUR_LOG_TAG: <--- HTTP 404 https://myserver:8443/RestWS/objects/barcodes (4462ms) D/YOUR_LOG_TAG: Server: Apache-Coyote/1.1 D/YOUR_LOG_TAG: Cache-Control: private D/YOUR_LOG_TAG: Expires: Thu, 01 Jan 1970 01:00:00 CET D/YOUR_LOG_TAG: Set-Cookie: JSESSIONID=*********************; Path=/; Secure; HttpOnly D/YOUR_LOG_TAG: Content-Type: text/html;charset=ISO-8859-1 D/YOUR_LOG_TAG: Content-Length: 127 D/YOUR_LOG_TAG: Date: Tue, 26 Apr 2016 09:31:22 GMT D/YOUR_LOG_TAG: OkHttp-Selected-Protocol: http/1.1 D/YOUR_LOG_TAG: OkHttp-Sent-Millis: 1461663081883 D/YOUR_LOG_TAG: OkHttp-Received-Millis: 1461663081973 D/YOUR_LOG_TAG: <html> D/YOUR_LOG_TAG: <head> D/YOUR_LOG_TAG: <title>404-Page Not Found</title> D/YOUR_LOG_TAG: </head> D/YOUR_LOG_TAG: <body> The requested URL was not found on this server. </body> D/YOUR_LOG_TAG: </html> D/YOUR_LOG_TAG: <--- END HTTP (127-byte body) A: Problem solved using RequestInterceptor. restAdapter = new RestAdapter.Builder() .setConverter(new GsonConverter(gson)) .setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade request) { String credentials = DownloadService.rest_user + ":" + DownloadService.rest_pw; String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); request.addHeader("Authorization", "Basic " + base64EncodedCredentials); } }) .setEndpoint(DownloadService.URL) .setClient(new OkClient(okHttpClient)) .build();
{ "pile_set_name": "StackExchange" }
Q: Fetching results from a prepared select query I'm trying to create a basic log-in system. Username and password are entered into a form and the results are sent to this page. If I enter the correct details, it works fine, but if I try to log-in with nonsense it never displays the error message. The line seems to be skipped every single time. if(isset($_POST['submit'])) { $sql = "SELECT username,password FROM tbl_users WHERE username = ? AND password = ?"; $stmt = $mysqli->prepare($sql); if(!$stmt) { die("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error); } $username = $_POST['username']; $password = $_POST['password']; $bind_result = $stmt->bind_param("ss", $username, $password); if(!$bind_result) { echo "Binding failed: (" . $stmt->errno . ") " . $stmt->error; } $execute_result = $stmt->execute(); if(!$execute_result) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; } $stmt->bind_result($returned_username, $returned_password); while($stmt->fetch()) { if($_POST['username'] == $returned_username && $_POST['password'] == $returned_password) { echo "You are now logged in!"; } else { echo "Incorrect username or password"; } } echo $stmt->fetch(); include 'disconnect.php'; } A: this should work... $username = $_POST['username']; $password = $_POST['password']; $sql = "SELECT password FROM tbl_users where username = ?"; $stmt= $conn->prepare($sql); $result->bind_param('s',$username); $result->execute(); $result->bind_result($pass); $stmt->fetch() // echo "<pre>"; print_r($pass); if($pass == $password) { echo "You are now logged in! <br><br>"; } else{ echo 'Incorrect username or password<br>'; } comment if not working...
{ "pile_set_name": "StackExchange" }
Q: TDD basics - do I add or replace tests? I'm completely new to TDD and am working my way through this article. It's all very clear except for a basic thing that probably seems too obvious to mention: Having run the first test (module exists), what do I do with my code before running the next one? Do I keep it so the next test includes results from the first one? Do I delete the original code? Or do I comment it out and only leave the current test uncommented? Put another way, does my spec file end up as long list of tests which are run every time, or should it just contain the current test? A: Quoting the same article linked to in the question. Since I don’t have a failing test though, I won’t write any module code. The rule is: No module code until there’s a failing test. So what do I do? I write another test—which means thinking again. Spec will end up with list of tests which are run every time to check for regression errors for every additional feature. If adding a new feature breaks something that was added before then the previous tests will indicate by failing the test.
{ "pile_set_name": "StackExchange" }
Q: How to change this.state status during authentication? Firebase + React-Router I use react-router and Firebase for authentication. For this function onButtonClick from file SignIn must change state in App.js for true. How to do this? Maybe there are some other ways except my idea? App.js : import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; .... import firebase from './firebase/firebase.js'; class App extends Component { state = { signedInStatus : false }; render(){ const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => ( this.state.signedInStatus ? <Component {...props} /> : <Redirect to='/signIn' /> )} /> ) return( <div> <Header signedInStatus={this.state.signedInStatus} /> <Router> <Switch> <Route exact path="/" component={SignIn}/> <Route path="/signIn" component={SignIn}/> <Route path="/register" component={Register} /> <PrivateRoute path="/home" component={Home} /> </Switch> </Router> </div> ); } } export default App; Second file ensure work with inputing information for getting to user cabinet. SignIn.js : import... class SignIn extends Component { state = { email: '', password: '', }; onButtonClick = (event) =>{ event.preventDefault(); firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password) .then((user) => { this.props.history.push('/home') console.log("ok") /// here i want add something to change }) /// this.state.signedIn for true in App .catch((error) => { console.log(error); alert(error); }); } onChangeInputEmail = (event) => { this.setState({email: event.target.value}) }; onChangeInputPassword = (event) => { this.setState({password: event.target.value}) }; render(){ return ( ... ) }; export default withRouter(SignIn); A: you need to define a method to update state for App.js then you can pass props to components as following <Route path='/signIn' render={(props) => <SignIn {...props} changeSignedInStatus={this.changeSignedInStatus} />} />
{ "pile_set_name": "StackExchange" }
Q: How to sort json data in groovy in alphabetic order? I want to sort an json data which is like this def json = [] for ( int i=10;i>1;i--){ if (i==10 || i==9 ){ json << [ name:"xyz", id:i ] }else if (i==8 || i==7 ){ json << [ name:"abc", id:i ] } } // def jsondata = [success:true, rows:json] def jsondata = [success:true, rows:json.sort(false) { it.name }] print jsondata​ groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.sort() is applicable for argument types: (java.lang.Boolean, com.cs.AdminController$_closure15_closure83) values: [false, com.cs.controllers.AdminController$_closure15_closure83@3e020351] Possible solutions: sort(), sort(java.util.Comparator), sort(groovy.lang.Closure), wait(), size(), size() I want that data to be sorted alphabetic order ascending or descending above one is working in a groovy console but not in my program , do i need to add something else like lib ? A: Your output format seems to have no similarity to your code you posted Also, your code you posted cannot just be run by someone trying to answer this question. So this will be an educated guess... Try: def jsondata = [success:true, rows:json.sort(false) { it.name }, total:totalCount] If you're using groovy from way back in the day for some unknown reason, then just drop the false, but beware as this will mutate your json list... def jsondata = [success:true, rows:json.sort { it.name }, total:totalCount]
{ "pile_set_name": "StackExchange" }
Q: Gmail AppScript mailMessage.getFrom() to return email not name Similar to: Getting only email address to display when using message.getFrom() in JavaMail but could not apply the solution. Trying to use mailMessage.getFrom() on Google AppScript with Gmail. Default script: function loadAddOn(event) { var accessToken = event.messageMetadata.accessToken; var messageId = event.messageMetadata.messageId; GmailApp.setCurrentMessageAccessToken(accessToken); var mailMessage = GmailApp.getMessageById(messageId); var from = mailMessage.getFrom(); var openDocButton = CardService.newTextButton() .setText("open docs") .setOpenLink( CardService.newOpenLink().setUrl("https://developers.google.com/gmail/add-ons/")); var card = CardService.newCardBuilder() .setHeader(CardService.newCardHeader().setTitle("My First Gmail Addon")) .addSection(CardService.newCardSection() .addWidget(CardService.newTextParagraph().setText("The email is from: " + from)) .addWidget(openDocButton)) .build(); return [card]; } var from = mailMessage.getFrom(); This returns the name of the sender, not the actual email address. Tried getFrom().getAddress() trying my luck with post mentioned above, but obviously it didn't work, with getFrom() returning a string. Any Idea how to access an array of data or dictionary with metadata of sender so I can extract email, name etc. myself? A: This appears to be a bug! It appears that when using the getFrom() method in a card, the name appears but not the email address as you described, which is counter to what is contained in the GmailMessage.getFrom() documentation. I have taken the liberty of reporting this behaviour for you on Google's Issue Tracker: GmailMessage.getFrom() not returning email address within CardService. You can hit the ☆ next to the issue number in the top left of this page which lets Google know more people are encountering this and so it is more likely to be seen to faster. Workaround: In the mean time, as the getFrom() method still works within the Apps Script interface, you can obtain the email address from the return string of getFrom(). If you use Logger.log(mailMessage.getFrom()), you get a return in the log of the form: Firstname Lastname <emailaddress@domain.com> So, all you need to do is replace: var from = mailMessage.getFrom(); with: var from = mailMessage.getFrom().split("<")[1].split(">")[0]; I hope this is helpful to you! References: Google Apps Script - GmailMessage.getFrom() Issue Tracker - GmailMessage.getFrom() not returning email address within CardService.
{ "pile_set_name": "StackExchange" }
Q: Can't login to MySQL as root anymore? It looks like I can not login to MySQL (actually MariaDB) as root user anymore in Ubuntu 15.04 (I upgraded from 14.04 via 14.10) I already tried to reset the password. What is working, is sudo mysql - but I want to login as root from an other user using mysql -uroot -p. When I create a new user with full rights and password, it is working. Was there something changed? A: So you've gone from version 5.5.44-1ubuntu0.14.04.1 to 10.0.20-0ubuntu0.15.04.1. Sounds scarier than it is, that's just what they called 5.6 for some reason. It seems that newer versions of MariaDB have added a plugin to the user table to force authentication through a fixed path. In this case, the root database user is forced through the unix_socket plugin. This also seems to be known as auth_socket in some circles. Anyway this plugin restricts things so only the system root user can log in as the database root, with no password. It's a security choice they've made. You can revert this by blanking the plugin field for the root user: shell$ sudo mysql -u root [mysql] use mysql; [mysql] update user set plugin='' where User='root'; [mysql] flush privileges; A specified password should work after this. I'm not sure how advisable this is though.
{ "pile_set_name": "StackExchange" }
Q: Grep, Sed... Awk to modify lines in a file I've searched for this but I didn't find exactly what I'm looking for. What I want to do is replace in the same file all the lines that contains a jar file with "PATTERN" text in the name so that I can add in those lines a new property with the sourcecode for those jar files. The sourcecode for those jars will be always in same relative folder (i.e. path1/lib/a.jar -> path1/src/java) An example of this. This is my original file: <classpathentry path="/sde/ATG/ATG10.1.2/Momentum/Search/I18N/lib/MOM-Search-I18N-0.23-ECI.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/DAS/lib/axis-1.4.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/REST/lib/org.json.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/Momentum/StoreFront/lib/MOM-Search-I18N-Index-0.23-ECI.jar" /> And I want to get this: <classpathentry path="/sde/ATG/ATG10.1.2/Momentum/Search/I18N/lib/MOM-Search-I18N-0.23-ECI.jar" sourcepath="/sde/ATG/ATG10.1.2/Momentum/Search/I18N/src/main/java" /> <classpathentry path="/sde/ATG/ATG10.1.2/DAS/lib/axis-1.4.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/REST/lib/org.json.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/Momentum/StoreFront/lib/MOM-Search-I18N-Index-0.23-ECI.jar" sourcepath="/sde/ATG/ATG10.1.2/Momentum/StoreFront/src/main/java"/> I need to add a sourcepath attribute to the lines with my pattern and that sourcepath value should take the root of the path value. As grep -o 'path="[/-.0-9A-Za-z]*/lib/MOM[-.0-9A-Za-z]*.jar"' test.txt gives me the lines that contain lines with the jars I'm looking for, I thought that this would solve my problem: cat test.txt | sed -r 's|path="[/-.0-9A-Za-z]*/lib/MOM[-.0-9A-Za-z]*.jar"|\1 sourcepath="\2/main/src/main/java"/>|' But gives me this error: sed: -e expression #1, char 91: invalid reference \2 on `s' command's RHS Any idea? Thanks guys! A: You could say: sed 's| \(path=.*\)\(/lib\)\(/MOM[^ ]*\)| \1\2\3 source\1/src/main/java"|' inputfile For your sample input, it'd produce: <classpathentry path="/sde/ATG/ATG10.1.2/Momentum/Search/I18N/lib/MOM-Search-I18N-0.23-ECI.jar" sourcepath="/sde/ATG/ATG10.1.2/Momentum/Search/I18N/src/main/java" /> <classpathentry path="/sde/ATG/ATG10.1.2/DAS/lib/axis-1.4.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/REST/lib/org.json.jar" /> <classpathentry path="/sde/ATG/ATG10.1.2/Momentum/StoreFront/lib/MOM-Search-I18N-Index-0.23-ECI.jar" sourcepath="/sde/ATG/ATG10.1.2/Momentum/StoreFront/src/main/java" />
{ "pile_set_name": "StackExchange" }
Q: CSS webkit scrollbar show/hide I'm using -webkit-scrollbar and what I want to happen is the scrollbar hidden on page load, and it stays hidden until you hover over the container div it is attached to. When you are hovering over a scrollable area, it would appear. I tried adding :hover and :focus affects to various divs and rules in my CSS with no luck. Is there a way to do what I'm referring to using -webkit-scrollbar? I could post code, but its pretty straightforward. Just one outer div with the css rules attached to it, then one inner div with set height and width. Then the css rules for -webkit-scrollbar. #u #trail ::-webkit-scrollbar { width: 9px; height: 9px; } #u #trail ::-webkit-scrollbar-button:start:decrement, #u #trail ::-webkit-scrollbar-button:end:increment { display: block; height: 0; background-color: transparent; } #u #trail ::-webkit-scrollbar-track-piece { background-color: #FAFAFA; -webkit-border-radius: 0; -webkit-border-bottom-right-radius: 8px; -webkit-border-bottom-left-radius: 8px; } #u #trail ::-webkit-scrollbar-thumb:vertical { height: 50px; background-color: #999; -webkit-border-radius: 8px; } #u #trail ::-webkit-scrollbar-thumb:horizontal { width: 50px; background-color: #999; -webkit-border-radius: 8px; } #u #trail-overflow { width: 860px; max-height: 500px; overflow: auto; } A: I seem to have got through the auto hide thing in css. I somehow did it on my app, and was searching how I got it. Here it is, a modification to the existing fiddle by @tim http://jsfiddle.net/4RSbp/165/ This does the trick: body {overflow-y:hidden;} body:hover {overflow-y:scroll;} A: You can use simple CSS to achieve this. Eg. if you have a div #content-wrapperthat scrolls with background-color: rgb(250, 249, 244); #content-wrapper::-webkit-scrollbar-thumb { background-color: rgb(250, 249, 244); /* Matches the background color of content-wrapper */ } #content-wrapper:hover::-webkit-scrollbar-thumb { background-color: gray; } F.Y.I. You could set the thumb's opacity to zero (instead of matching the background color), but the opacity seems to then apply to other scrollbars on the page as well. P.S. This assumes that you're ::-webkit-scrollbar-track's background color also matches the #content-wrapper's background color. A: I ended up going with the slimscroll javascript plugin. It would be cool to have an all-css solution, but this plugin is done very well, and allows the focus-shown/hidden idea. http://rocha.la/jQuery-slimScroll
{ "pile_set_name": "StackExchange" }
Q: Using boost::bind to create a function object binding a auto-release "heap" resource I try to use boost::bind to create a function object, as well, I want to bind a object created on the HEAP to it for a delay call. The example code like below: #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/smart_ptr.hpp> #include <boost/typeof/typeof.hpp> #include <iostream> using namespace boost; class CTest : public noncopyable { public: CTest():mInt(0){ std::cout << "constructor" << std::endl; } ~CTest(){ std::cout << "destructor" << std::endl; } int mInt; }; int getM( CTest * t ) { return t->mInt; } function<int()> makeF() { // create some resource on HEAP, not on STACK. // cause the STACK resource will be release after // function return. BOOST_AUTO( a , make_shared<CTest>() ); // I want to use bind to create a function call // wrap the original function and the resource I create // for delay call. // // I use shared_ptr to auto release the resource when // the function object is gone. // // Compile ERROR!!! // cannot convert parameter 1 from 'boost::shared_ptr<T>' to 'CTest *' // return bind<int>( getM , a ); } int main(int argc, char* argv[]) { BOOST_AUTO( delayFunc , makeF() ); delayFunc(); return 0; } The above is just a example code. But I think it shows what I want and the current error is. Currently, I think I can only use a function object to wrap the original function like below: class CGetM { public: typedef int result_type; int operator() ( shared_ptr<CTest> t ) { return getM( t.get() ); } }; And replace the code like this: return bind<int>( CGetM() , a ); However, if currently I have many original function like getM, for adapting the correct arguments, wrapping it in a function object is really a large job. I don't know if there is some kind of tips or other useful util class in boost can handle such case more intelligently and elegantly ? So any suggestion is appreciated. Thanks. A: You need to use bind composition: return bind<int>( getM, bind(&shared_ptr<CTest>::get, a) );
{ "pile_set_name": "StackExchange" }
Q: C# Add variable value to list name Is it possible to add a variable to a list name when using it? Something like this: string id = "1"; //Could be 2 List<string> List1 = new List<string> {"1","11" }; List<string> List2 = new List<string> {"2","22" }; foreach (var element in List+id) { //code here } IDs could be a dozen different values, so I didn't even try with regular if(). Would that be the only way? A: Use a dictionary: var dict = new Dictionary<string, List<string>>(); dict.Add("1", new List<string> {"1","11" }); dict.Add("2", new List<string> {"2","22" }); Then you can do foreach (var element in dict[id]) { }
{ "pile_set_name": "StackExchange" }
Q: How to sort on hh:mm:ss (duration) in Excel I have a column of data that represents duration, e.g. 33:15 - 30 minutes and 15 seconds; 1:05:00 - 1 hour and 5 minutes, etc. If I try to sort it A-Z, then 1 hour gets sorted before 30 minutes. Is there a way to format the data to make it sort correctly? Formatting solution is preferred to converting this data into seconds or whatnot. A: Welcome to the wonderful world of times in Excel. Puzzling at first, but powerful once you know how they work. I don't think there's a way to do it with just formatting in your situation. However, this should work (I'm assuming all your times are in Column A) -Create this formula in B1 and copy it all the way down: =IF(A1>=1,A1/60,A1) -Format Column B as h:mm:ss -Select Column B and Copy, then Paste Special, Values. -Sorting Column B should now work fine. That's the short answer. If you want to understand what's going on and how that formula was derived, read on: 1. -Start a new sheet. -In A1, type 1:05:00 -Click on A1, then Format, Cells. Note it has applied a custom format of h:mm:ss Excel is pretty clever and that number is fairly unambiguous so it assumes you meant hours:minutes:seconds and formats accordingly. 2. -In A2, type 33:15 -Note how it automagically changed it to 33:15:00 -Click on A2, then Format, Cells. Note a custom format of [h]:mm:ss This is ambiguous. Did you mean "33 minutes and 15 seconds" Or "33 hours and 15 minutes"? Excel isn't sure. Its behaviour is to assume you meant hours and minutes. The [] around the h basically mean "show more than 24 hours in the hour section". 3. -In A3, type 0:33:15 (note the 0: before) -Click on A3, then Format, Cells. Note a custom format of h:mm:ss Since you've taken out the ambiguity, it once again assumes assumes you meant hours:minutes:seconds again and formats accordingly. 4. -In A4, type 23:15 -Note how it leaves it as 23:15 -Click on A4, then Format, Cells. Note a custom format of h:mm W..T..F? How come it formatted it differently than in #2? Because you entered a number less than 24 (i.e. hours) - still ambiguous, and it still assumes you meant hours and minutes...but it formats differently. 5. -In A5, type 1:00:00 -Click on A5, then Format, Cells. Note a custom format of h:mm:ss -Change the format to General and note that the underlying number is .041667 (i.e. the percentage of a day) 6. -In A6, type 24:00:00 -Click on A6, then Format, Cells. Note a custom format of [h]:mm:ss -Change the format to General and note that the underlying number is 1 (i.e. a full day) Almost there... 7. -Now click on B2 and enter this formula: =A2/60 (i.e. convert from hours to minutes) -Click on B2, then Format, Cells. Note a custom format of [h]:mm:ss -Note that it now shows 0:33:15, which is what you want 8. -Now click on B1 and enter the same formula: =A1/60 (i.e. convert from hours to minutes) -Click on B1, then Format, Cells. Note a custom format of h:mm:ss -Note that it shows 0:01:05 - damn - that's *not* what you want. Stay on target... 9. -Click on B1 again and enter this formula instead: =IF(A1>=1,A1/60,A1) -Click on B1, then Format, Cells. Enter a custom format of h:mm:ss -Note that it still shows 1:05:00 (i.e. it didn't change it to 0:01:05) So basically that formula: -Checks to see if the number in a cell is greater than or equal to 1 -If it is greater than 1, divide by 60 (i.e. convert hours to minutes) -If it's less than 1, leave it alone. A: If your values are interpreted by Excel as actual times, then they are sorted numerically, not alphabetically. But there are problems. If you enter minutes and seconds as 30:00, Excel is going to interpret is as 30 hours and 0 minutes. You have to enter 30 minutes as 0:30:00 or 0:30. So 30 minutes entered like this will be interpreted as larger than one hour thirty minutes entered as 1:30. You should always check the formula bar after entering numbers to make sure Excel recorded the value you intended to enter. CompWiz missed this intricacy, and Craig's routines just correct for your specific problems. But knowing you have to enter times as h:mm:ss even if the value is less than an hour will mean your values will always be interpreted correctly.
{ "pile_set_name": "StackExchange" }
Q: Multipolygon in DSE Graphs I need to store Multipolygon data in Datastax Graph. They do support some of geo data types like point, line String and polygon . Do they support Multipolygon. Could you please help with this A: DSE Graph does not support explicit Multipolygon data types. If you don't mind sharing, what types of issues/challenges does Multipolygon help you solve?
{ "pile_set_name": "StackExchange" }
Q: How does GNU Radio File Sink work? I want to know how the file sink in GNU Radio works. Does it receive a signal and then write it to the file, and while it's being written signal receiving is not done? I just want to make sure if some portion of the signal is lost without being written to the file because of the time taken for writing. Any help or reading material regarding this would be very much appreciated. A: Depending the sampling rate of the device, writing samples to file without discontinuities may be impossible. Instead writing to disk, you can write the samples in a ramdisk. Ramdisk is an abstraction of file storage, using the RAM memory as storage medium. The great advantage of the ramdisk is the very fast read/write data transfers. However, the file size is limited somehow by the amount of RAM memory that the host has. Here is a good article that will help you to create a ramdisk under Linux. I am sure that you will easily find a guide for Windows too.
{ "pile_set_name": "StackExchange" }
Q: Different aggregate operations on different columns pyspark I am trying to apply different aggregation functions to different columns in a pyspark dataframe. Following some suggestions on stackoverflow, I tried this: the_columns = ["product1","product2"] the_columns2 = ["customer1","customer2"] exprs = [mean(col(d)) for d in the_columns1, count(col(c)) for c in the_columns2] followed by df.groupby(*group).agg(*exprs) where "group" is a column not present in either the_columns or the_columns2. This does not work. How to do different aggregation functions on different columns? A: You are very close already, instead of put the expressions in a list, add them so you have a flat list of expressions: exprs = [mean(col(d)) for d in the_columns1] + [count(col(c)) for c in the_columns2] Here is a demo: import pyspark.sql.functions as F df.show() +---+---+---+---+ | a| b| c| d| +---+---+---+---+ | 1| 1| 2| 1| | 1| 2| 2| 2| | 2| 3| 3| 3| | 2| 4| 3| 4| +---+---+---+---+ cols = ['b'] cols2 = ['c', 'd'] exprs = [F.mean(F.col(x)) for x in cols] + [F.count(F.col(x)) for x in cols2] df.groupBy('a').agg(*exprs).show() +---+------+--------+--------+ | a|avg(b)|count(c)|count(d)| +---+------+--------+--------+ | 1| 1.5| 2| 2| | 2| 3.5| 2| 2| +---+------+--------+--------+
{ "pile_set_name": "StackExchange" }
Q: Validar número Cartão de crédito Como faço para validar números de cartões de crédito? Não farei integração com operadora de cartão, preciso apenas validar o número, assim como ocorre com a validação com CPF. A: Você pode utilizar o atributo CreditCardAttribute para validar. Como está utilizando asp.net-mvc-5 creio que já está familiarizado com o Data Annotations. Ele possui um atributo chamado [CreditCard], que você pode utilizar para esse fim. Para utilizar o mesmo basta fazer a marcação em sua propriedade da seguinte forma: [CreditCard(ErrorMessage = "Cartão de crédito inválido")] public string CartaoCredito { get; set; } Nesta resposta você conseguirá ver mais detalhado. Você pode implementar seus próprios atributos ou métodos para validar, caso deseje. Alguns links para ajudar: Credit Card Validation Client Asp.Net. Credit Card Attribute. A: A validação de números de cartão de crédito normalmente é feita pelo algoritmo de Luhn: Retire o último dígito do número. Ele é o verificador; Escreva os números na ordem inversa; Multiplique os dígitos das casas ímpares por 2 e subtraia 9 de todos os resultados maiores que 9; Some todos os números; O dígito verificador (aquele do passo 1) é o número que você precisa somar a todos os outros números somados pra obter um módulo 10. Exemplo Passo Total Número Original : 4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 5 Tirando o último dígito : 4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 Invertendo : 5 8 9 9 8 6 8 5 7 3 7 6 5 5 4 Multiplicando casas ímpares por 2 : 10 8 18 9 16 6 16 5 14 3 14 6 10 5 8 Subtraia 9 de todos os números acima de 9: 1 8 9 9 7 6 7 5 5 3 5 6 1 5 8 Somando todos os números : 1 8 9 9 7 6 7 5 5 3 5 6 1 5 8 85 Mod 10: 85, módulo 10 = 5 (último dígito do cartão) Formatos de Operadoras Conhecidas Bandeira Intervalo de Início Número de Dígitos ----------------------------------------------------------------------------- American Express 34, 37 15 Diners Club - Carte Blanche 300, 301, 302, 303, 304, 305 14 Diners Club - International 36 14 Diners Club - USA & Canada 54 16 Discover 6011, 622126 até 622925, 644, 16 645, 646, 647, 648, 649, 65 InstaPayment 637, 638, 639 16 JCB 3528 até 3589 16 Laser 6304, 6706, 6771, 6709 16-19 Maestro 5018, 5020, 5038, 5893, 6304, 16-19 6759, 6761, 6762, 6763 MasterCard 51, 52, 53, 54, 55 16-19 Visa 4 13-16 Visa Electron 4026, 417500, 4508, 4844, 4913, 16 4917 Tirei daqui. No ASP.NET MVC Por atributo, conforme a resposta do @Randrade. A: O Algoritmo utilizado para calcular o digito de verificação (Check Digit) de Números de Cartão de Crédito é o Algoritmo de Luhn, porém não basta apenas validar a informação sem levar em conta as características de um número de Cartão de Crédito que são: Possuir somente números Ter entre 12 e 19 dígitos (na verdade não há CC com 17 dígitos) Os 6 primeiros dígitos devem indicar um IIN (Issuer identification number) válido. Ele é chamado de BIN no meio bancário. Passar na validação do Algoritmo de Luhnn A verificação do item BIN necessita de uma base de informações para comparação. Não existe uma lógica na geração dos BINs. Você pode ter faixas por exemplo que tem saltos e dentro destes saltos o BIN pertecer a uma instituição diferente, inclusive de país diferente. É um clássico erro acreditar que todo cartão que comece com 4 é VISA e com 5 seja Mastercard, por exemplo. Atualmente no Brasil isso é até válido, pois temos poucas empresas de Cartão o que acaba reservando o 4 e o 5 apenas para estas duas Bandeiras. Deixando estes aspectos de lado, pois não há como validar um BIN via código sem que seja feita algum tipo de consulta, a validação pode ser feita com o seguinte algoritmo Verificar se o tamanho do numero do cartão está entre 12 e 19. Atualmente no Brasil é raro ter um cartão diferente de 16. Alguns Hipercard tinham 19 mas já estão saindo com 16 também. Verificar se o valor possui somente números Verificar se o número passa pela validação do Algoritmo de Luhnn Abaixo um código em C#. Ele é apenas uma forma de entender pois já há nas versões atuais do ASP.net, validação por Attributes para esta verificação, conforme resposta do @Randrade O Algoritmo de Luhnn está representado na resposta do @Cigano Morrison Mendez com a ressalva que na última linha, onde está Mod 10: 85, módulo 10 = 5 (último dígito do cartão) Deveria estar Mod 10: 85, módulo 10 = 5, Check Digit = 10 - 5 = 5 (último dígito da sequencia) Na verdade, não há a necessidade de calcular o check digit. Basta incluir o termo na soma e calcular o módulo 10 dela. Se for zero é válido. // About the Algorithm /** @See https://en.wikipedia.org/wiki/Luhn_algorithm Steps: 1 - From the rightmost Digit of a Numeric String, Double the value of every digit on odd positions 2 - If the obtained value is greather than 9, subtract 9 from it 3 - Sum all values 4 - Calculate the Modulus of the value on 10 basis, if is zero so the String has a Luhnn Check Valid **/ public static bool IsValidLuhnn(string val) { int currentDigit; int valSum = 0; int currentProcNum = 0; for (int i = val.Length-1; i >= 0; i--) { //parse to int the current rightmost digit, if fail return false (not-valid id) if(!int.TryParse(val.Substring(i,1), out currentDigit)) return false ; currentProcNum = currentDigit << (1 +i & 1); //summarize the processed digits valSum += (currentProcNum > 9 ? currentProcNum - 9 : currentProcNum); } // if digits sum is exactly divisible by 10, return true (valid), else false (not-valid) // valSum must be greater than zero to avoid validate 0000000...00 value return (valSum > 0 && valSum % 10 == 0) ; } public static bool isValidCreditCardNumber(string cc) { // rule #1, must be only numbers if (cc.All(Char.IsDigit) == false) { return false; } // rule #2, must have at least 12 and max of 19 digits if (12 > cc.Length || cc.Length > 19) { return false; } // rule #3, must pass Luhnn Algorithm return IsValidLuhnn(cc); } Pode ser testado aqui
{ "pile_set_name": "StackExchange" }
Q: Ruby on a Mac -- Regular Expression Spanning Two Lines of Text On the PC, the following Ruby regular expression matches data. However, when run on the Mac against the same input text file, no matches occur. Am I matching line returns in a way that should work cross-platform? data = nil File.open(ARGV[0], "r") do |file| data = file.readlines.join("").scan(/^Name: (.*?)[\r\n]+Email: (.*?)$/) end Versions PC: ruby 1.9.2p135 Mac: ruby 1.8.6 Thank you, Ben A: The problem was the ^ and $ pattern characters! Ruby doesn't consider \r (a.k.a. ^M) a line boundary. If I modified my pattern, replacing both ^ and $ with "\r", the pattern matched as desired. data = file.readlines.join.scan(/\rName: (.*?)\rEmail: (.*?)\r/) Instead of modifying the pattern, I opted to do a gsub on the text, replacing \r with \n before calling scan. data = file.readlines.join.gsub(/\r/, "\n").scan(/^Name: (.*?)\nEmail: (.*?)$/) Thank you each for your responses to my question.
{ "pile_set_name": "StackExchange" }
Q: Reloading OpenLayers 5 WMS automatically with new data I am making a weather application. It is almost finished now, but I just have one problem left. I want a WMS-layer to automatically reload every few seconds. I thought I had the solution, but it seems that it doens't quite work. Below (some of) my code. It seems to redraw the WMS, but not with changed data. Only when the datetime or weathertype CHANGES, then the WMS-gets new data and that is shown on the map. But I want it to keep reloading and show the new data for that datetime. (Because the datetime only changes once in a while, but the data keeps rolling in.) I hope I made my question clear. I searched and found some solutions, but they didn't work for me. Besides most solutions I found were for OL2 or OL3 and I am working with OL5. Please help me. A: Adding a dummy parameter (if the name isn't recognised by the server it should ignore it) to the WMS set to the current datetime in milliseconds should force a reload and override browser caching. You could use a javasript setInterval if necessary to update it, e.g. 'TIMESTAMP': new Date().getTime()
{ "pile_set_name": "StackExchange" }
Q: How to get Row data after a button click in datatables can anyone help me on how to get a single row data on a click event. This is the table which is dynamically populated after Success function in AJAX call is executed <div class="table-responsive table-wrap tableFixHead container-fluid"> <table class="table bg-violet dT-contain" id="datatable" > <thead class="thead-dark"> <tr> <th>No.</th> <th>Main</th> <th>Shrinked</th> <th>Clicks</th> <th>Disable</th> <th>Delete</th> </tr> </thead> <tbody> <tr class="bg-violet"> </tr> </tbody> </table> </div> <script src="scripts/jquery-3.5.1.min.js"></script> <script src="scripts/jquery.dataTables.min.js"></script> <script src="scripts/dataTables.bootstrap4.min.js" defer></script> <script src="scripts/dashboard.js" defer></script> This is my ajax success function success: function(data){ $('#datatable').dataTable({ data: data, "autoWidth": true, columns: [ {'data': 'id'}, {'data': 'main'}, {'data': 'shrinked'}, {'data': 'clicks'}, {"defaultContent": "<button id='del-btn'>Delete</button>"} ] }) } I am adding a delete button to each row dynamically, but can't seem to fetch row data using it. I tried this method with some tweaks to my success function $('#datatable tbody').on( 'click', 'button', function () { var data = table.row( $(this).parents('tr') ).data(); alert( data[0] ); } ); But this didn't seem to work. The JSON data returning from the AJAX call is in this format: [{"id":"12","main":"ndkekfnq" ...}, {.....}] I also added an onclick function on the delete button to try to fetch data but that also didn't work. EDIT: whole AJAX request $(document).ready(()=>{ $.ajax({ url: 'URL', method: 'post', dataType: 'json', data: { "email": window.email, "token": window.token }, success: function(data){ let table = $('#datatable').dataTable({ data: data, "autoWidth": true, columns: [ {'data': 'id'}, {'data': 'main'}, {'data': 'shrinked'}, {'data': 'clicks'}, {"defaultContent": "<button id='dis-btn' class='btn btn-warning'>Disable</button>"}, {"defaultContent": "<button id='del-btn' class='btn btn-danger'>Delete</button>"} ] }) $('#datatable tbody').on('click', "#del-btn", function() { let row = $(this).parents('tr')[0]; //for row data console.log(table.row(row).data().id); }); } }) }) What would be the correct way to do this? Thank you A: You need to use column.render instead o defaultContent and then get the data on an outside function, you need to render a button at the render of the table: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" /> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script> </head> <body> <div class="table-responsive table-wrap tableFixHead container-fluid"> <table class="table bg-violet dT-contain" id="datatable" > <thead class="thead-dark"> <tr> <th>No.</th> <th>Main</th> <th>Shrinked</th> <th>Clicks</th> <th>Delete</th> </tr> </thead> <tbody> <tr class="bg-violet"> </tr> </tbody> </table> <script> $('#datatable').dataTable( { "data": [{'id':20,'main':'hola','shrinked':false,'clicks':2000},{'id':21,'main':'hola','shrinked':false,'clicks':283000}], "autoWidth": true, "columns": [ {"data": "id"}, {'data': 'main'}, {'data': 'shrinked'}, {'data': 'clicks'}, {"data": "id", "render": function ( data, type, row, meta ) { return '<button data-id="'+data+'" onclick="deleteThis(event)">Delete</button>' } } ] } ) function deleteThis(e){ console.log(e.target.getAttribute('data-id')) } </script> </body> </html> Haven't tried, but based on Datatables docs, this should work, let me know if it worked.
{ "pile_set_name": "StackExchange" }
Q: how to apply filter in angular js which is not visible? I am trying to apply filter in list view .Whenever I typed anything in input field it filter my list .I am able to filter when I write username which is visible to user .example when I write "pa" it sort my list and display only one row .that is correct.but when I write on "keyword filter" which is not visible to user it doesn't filter .In other words when I type "Angular js" on second input field ("keyword filter") ..It should display pab..Because "pab" have Angular js keyword . here is my code http://plnkr.co/edit/TccgJydcZNkXQGpnbbP0?p=preview // Code goes here angular.module('myApp', []) .controller('myCtrl', function($scope){ $scope.users = [ {firstname: 'john', lastname: 'smith', keywords: ["HTML", "CSS", "JavaScript", "jQuery", "Photoshop"] }, {firstname: 'pab', lastname: 'due', keywords: ["Ruby on Rails", "PostgreSQL", "AngularJS", "Node.js"] }, {firstname: 'bob', lastname: 'rand', keywords: ["java", "php", "test", "jira"] } ]; }); A: In your ng-repeat you are not filtering after your keyword input - you missed it. Just include it as follows: <div ng-repeat="user in users | filter:userSearch | filter:{ keywords: keyword }">
{ "pile_set_name": "StackExchange" }
Q: VBS output in column format I am trying to have my .vbs output be put into columns. However, when I try write the code to organize the output into columns I continue to get an error - Invalid Procedure call or argument: 'Space' I'm looking for some help on this, thanks!! Call FindPCsThatUserLoggedInto Sub FindPCsThatUserLoggedInto() strUser = InputBox("Enter First Name") strLast = InputBox("Enter Last Name") Const ADS_SCOPE_SUBTREE = 2 Set objConnection = CreateObject("ADODB.Connection") Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 1000 objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 's = "Name" & Chr(9) & "Account Name" & Chr(9) & "Location" & Chr(10) & Chr(13) 's = s & "----" & Chr(9) & "------------" & Chr(9) & "--------" & Chr(10) & Chr(13) s = RightJustified("Name", 10) & _ RightJustified("Account Name", 15) & _ RightJustified("Location", 15) & _ vbCrLf objCommand.CommandText = "SELECT ADSPath FROM 'LDAP://dc=hc,dc=company,dc=com' WHERE givenName = '" & strUser & "*' AND sn = '" & strLast & "*'" Set objRecordSet = objCommand.Execute If objRecordSet.Recordcount > 0 Then objRecordSet.MoveFirst Do Until objRecordSet.EOF Set objUser = GetObject(objRecordSet.Fields("ADSPath").Value) 's = s & objUser.DisplayName & Chr(9) & objUser.samaccountname & Chr(9) & objUser.PhysicalDeliveryOfficeName & Chr(10) & Chr(13) ' objRecordSet.MoveNext s = s & _ RightJustified(objUser.DisplayName, 10) & _ RightJustified(objUser.samaccountname, 15) & _ RightJustified(objUser.PhysicalDeliveryOfficeName, 15) & _ vbCrLf Loop MsgBox s Else MsgBox "No users matching that criteria exist in the HC domain in AD." End If End Sub Function RightJustified(ColumnValue, ColumnWidth) RightJustified = Space(ColumnWidth - Len(ColumnValue)) & ColumnValue End Function This is the code that I added to organize the outputs into columns: s = RightJustified("Name", 10) & _ RightJustified("Account Name", 15) & _ RightJustified("Location", 15) & _ vbCrLf And s = s & _ RightJustified(objUser.DisplayName, 10) & _ RightJustified(objUser.samaccountname, 15) & _ RightJustified(objUser.PhysicalDeliveryOfficeName, 15) & _ vbCrLf Here is my output: A: My guess would be that this is a runtime error due to your data exceeding the specified size? RightJustified(objUser.DisplayName, 10) & _ RightJustified(objUser.samaccountname, 15) & _ RightJustified(objUser.PhysicalDeliveryOfficeName, 15) & _ vbCrLf Perhaps this change would be needed: Function RightJustified(ColumnValue, ColumnWidth) If Len(ColumnValue) > ColumnWidth Then ColumnValue = Left(ColumnValue,ColumnWidth) End If RightJustified = Space(ColumnWidth - Len(ColumnValue)) & ColumnValue End Function
{ "pile_set_name": "StackExchange" }
Q: TThread and inheritance I am having a hard time implementing multi-tier inheritance from the basic TThread class. Based on my knowledge of OOP it should be possible but maybe it just can't be applied to threads. My goal is to use TMyBaseThread to implement all the code that will be common to descendent classes. This is what I have have tried: TMyBaseThread = class(TThread) private procedure BuildBaseObjects(aParam : TParam); procedure Execute; virtual; abstract; protected constructor Create(Param : TParam); reintroduce; virtual; end; TMyFileThread = class(TMyBaseThread) private procedure Execute; reintroduce; public constructor Create(OtherParam : TOtherParam); reintroduce; overload; end; TMyDBThread = class(TMyBaseThread) private procedure Execute; reintroduce; public constructor Create(aDB : TDatabase); reintroduce; overload; end; implementation constructor TMyBaseThread.Create(Param : TParam); begin inherited Create(False); Self.BuildBaseObjects(Param); [do some stuff] end; constructor TMyFileThread.Create(OtherParam : TOtherParam); var param : TParam; begin inherited Create(param); [do some other stuff] end; procedure TMyFileThread.Execute; begin while not Terminated do doWork(); <-- this is never called end; constructor TMyDBThread.Create(aDB : TDatabase); var param : TParam; begin inherited Create(param); end; procedure TMyDBThread.Execute; begin while not Terminated do doDatabaseWork(); <-- this is never called end; I see in TThread's implementation that the Executed method is called automatically in the AfterConstruction but how can I have it point to the one declared in the derived classes? Thanks! A: First, I can't support more Craig's comment about using composition instead of inheritance for implementing the common functionality. And although the architecture choice is under question, there is a lot to learn from your example. Before inheriting a class, you should investigate the interface of the parent class that you want to inherit. To do that you can either look for the class definition in the interface section of the source code or look up the relevant documentation - System.Classes.TThread. It seems you have already read the documentation, so let's take a look at an except from the class definition of TThread: TThread = class private ... protected procedure CheckThreadError(ErrCode: Integer); overload; procedure CheckThreadError(Success: Boolean); overload; procedure DoTerminate; virtual; procedure Execute; virtual; abstract; procedure Queue(AMethod: TThreadMethod); overload; procedure Synchronize(AMethod: TThreadMethod); overload; property ReturnValue: Integer read FReturnValue write FReturnValue; property Terminated: Boolean read FTerminated; public constructor Create(CreateSuspended: Boolean); destructor Destroy; override; procedure AfterConstruction; override; procedure Resume; procedure Suspend; procedure Terminate; function WaitFor: LongWord; class procedure Queue(AThread: TThread; AMethod: TThreadMethod); overload; class procedure RemoveQueuedEvents(AThread: TThread; AMethod: TThreadMethod); class procedure StaticQueue(AThread: TThread; AMethod: TThreadMethod); class procedure Synchronize(AThread: TThread; AMethod: TThreadMethod); overload; class procedure StaticSynchronize(AThread: TThread; AMethod: TThreadMethod); property FatalException: TObject read FFatalException; property FreeOnTerminate: Boolean read FFreeOnTerminate write FFreeOnTerminate; property Handle: THandle read FHandle; property Priority: TThreadPriority read GetPriority write SetPriority; property Suspended: Boolean read FSuspended write SetSuspended; property ThreadID: THandle read FThreadID; property OnTerminate: TNotifyEvent read FOnTerminate write FOnTerminate; end; First, ignore anything that is in the private section of the class. If those fields and methods were marked as private, we are not supposed to be able to use them at all in descendant classes. Then, look for any abstract methods. The implementation of abstract methods is left for descendant classes. So those are the methods you are expected to implement in your code. Abstract methods are usually called indirectly by using one of the methods from the parent class. In your case the TThread class has only one abstract method: procedure Execute; virtual; abstract; The documentation says that you need to Define the thread object's Execute method by inserting the code that should execute when the thread is executed. It's true that the documentation sounds a bit vague, but the right way to do that is to "override" the method in the interface, and not to "reintroduce" it: TMyFileThread = class(TMyBaseThread) ... protected procedure Execute; override; ... and then implement it in the implementation: procedure TMyFileThread.Execute; begin while not Terminated do Sleep(1); // do some other stuff end; You probably notice how we declared the overrided definition of Execute method in the protected section. This is required as the definition of the method in the parent class is also in the protected section, so we can only override it in a section with higher visibility (protected or public). You rarely need to increase the visibility when overriding a method, so we just keep the same visibility. We used the override keyword to tell the base class to use this variant of the method instead of its own. If you miss the override keyword the Execute method will not be called at all, and the base class will try calling it's own Execute method, if there is any. Another thing to note is that you don't need to redeclare the Execute method in your base class as you are not implementing it there. That's why you should remove the following definition: TMyBaseThread = class(TThread) ... //procedure Execute; virtual; abstract; <- remove this ... The execute method is already defined in the TThread class. Now, let's look at the constructors. The base class has a regular constructor that is neither virtual, nor dynamic: public constructor Create(CreateSuspended: Boolean); This means you cannot override those constructors and if you want to add additional logic on object creation, you should create your own constructors that wrap those. The proper way to do that is to just declare a constructor with a different set of parameters, without reintroducing, overloading or overriding the base one: public //constructor Create(Param : TParam); reintroduce; virtual; constructor Create(Param : TParam); Also, remember that constructors should almost always be in the public section. You also don't need to make the constructor virtual. You could do that if your TMyFileThread and TMyDBThread classes needed to add some logic inside the constructor, without changing the constructor parameters. When you change the set of parameters all that is required is that you call the inherited constructor as first thing inside the new one: constructor TMyFileThread.Create(OtherParam : TOtherParam); var param : TParam; begin inherited Create(param); // It is enough to call the base constructor at the top // do some other stuff end; The definition requires no keywords: TMyFileThread = class(TMyBaseThread) ... public constructor Create(OtherParam : TOtherParam); Did you notice how we used inherited Create(param) to call the base constructor, but we did not use inherited Execute;? That's because the Execute method was marked as abstract and have no default implementation in the base class. Using inherited on an abstract method would cause an exception as there is no default method to call. As a general rule calling inherited Create is a must if the base constructor you are calling is marked as virtual, but is almost always required even if it is not marked so. Finally, I want to formulate a summary of the relevant keywords and their most common use: virtual - declare a method that can be reimplemented in descendant classes. That is descendant classes can change the behaviour of the method. They can replace all the code inside it with their own, or can both call the base method and then add additional behaviour before/after that. This keyword is used only in the base class that defines the method for the first time. Descendant classes use the other keywords. dynamic - consider it the same as virtual. Can save some memory resources, but only if the method is not reimplemented in all descendant classes and there are many objects created from such classes. Rarely used. override - declare a method that reimplements the base class by providing code that replaces the default one in the base class. You use override in descendant classes. You can use the inherited keyword inside your implementation to call the base method. overload - You declare an alternative variant of the method with another set of parameters. Note that overloading a method has nothing to do with inheritance. An overloaded version of the method is not executed when the base class is calling the original method. Usually overloaded methods normalize the parameters (converting them to other types, adding default values for some parameters) and then call one of the other overloaded methods. Again, this has nothing to do with inheritance and the virtual, override keywords. Although sometimes you can combine both effects. reintroduce - This again is not inheritance. You use this keyword in descendant classes. The purpose is to make calls to the method from inside your class (and only calls from your class, not calls from the base class) to execute that reintroduced version of the method instead of the base one. Calls from the base class still execute the original version. Rarely used. Having said that, here is my interpretation of your code: interface uses Classes, SysUtils; type TParam = class end; TOtherParam = class end; TDatabase = class end; TMyBaseThread = class(TThread) private procedure BuildBaseObjects(aParam : TParam); protected public constructor Create(Param : TParam); end; TMyFileThread = class(TMyBaseThread) private protected procedure Execute; override; public constructor Create(OtherParam : TOtherParam); end; TMyDBThread = class(TMyBaseThread) private protected procedure Execute; override; public constructor Create(aDB : TDatabase); end; implementation { TMyBaseThread } constructor TMyBaseThread.Create(Param : TParam); begin inherited Create(False); Self.BuildBaseObjects(Param); // Do some stuff end; procedure TMyBaseThread.BuildBaseObjects(aParam : TParam); begin // Do some stuff end; { TMyFileThread } constructor TMyFileThread.Create(OtherParam : TOtherParam); var param : TParam; begin inherited Create(param); // Remember to initialize param somehow // Do some other stuff end; procedure TMyFileThread.Execute; begin while not Terminated do Sleep(1); end; { TMyDBThread } constructor TMyDBThread.Create(aDB : TDatabase); var param : TParam; begin inherited Create(param); // Remember to initialize param somehow end; procedure TMyDBThread.Execute; begin while not Terminated do Sleep(1); end; PS. Actually using inheritance on TThread is mostly useful for plugin architectures or task workers. You can look up for examples on that.
{ "pile_set_name": "StackExchange" }
Q: Adding function parameters using a single variable in jQuery I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable. Also the parameters of the functions could be more than one and so I separated them by ,. So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code: function Func (a,b){ alert(a+' | '+b); } var Parameters = 'cool,123'; var Function = Func; $('button').click(Function); Problem demo Thanks in advance A: You can use function.apply(). Pass your list of parameters in as an array and you can even set a scope if you wish to do so: function myFunc(a,b){ alert(a+", "+b); } var args = ["one", "two"]; var func = myFunc; $('button').click(function(){ func.apply(this, args); }); A: Is this what you're after? function Func (a,b){ alert(a+' | '+b); } var Parameters = 'cool,123'; $('button').click(function() { Func.apply(this, Parameters.split(",")); }); Demo: http://jsfiddle.net/6nJx7/14/ https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply
{ "pile_set_name": "StackExchange" }
Q: Who was the first "trap character"? A "trap character"(UrbanDictionary entry, may be NSFW) is a character who appears to be a girl until you get in close enough (plot-wise) to discover they are, in fact, a boy. The inverse trope exists as well; a "reverse trap" character is a girl who appears to be a boy. (Note: The word trap here is not intended to be offensive, or a slur; it is only used to refer to fictional characters of this type.) Some examples are Ruka Urushibara of Steins;Gate and Sora Kamomeya of Tsui☆Teru (pictured below): Who was the first trap character in anime and/or manga, and what media did the trope originate from? A: Tezuka's 1949 manga, Metropolis, features Michi, a synthesised human with a gender switch which can turn it from a boy into a girl and vice versa which is used as a plot device. Tezuka's 1953 manga, Ribbon no Kishi (Princess Knight) features a reverse trap with a girl pretending to be a guy: Taking place in a medieval European-like fairy-tale setting, Princess Knight is the story of young Princess Sapphire who must pretend to be a male prince so she can inherit the throne (as women are not eligible to do so). This deception begins as soon as she is born, as her father the King announces his baby is a boy instead of a girl. The reason for this is that the next-in-line to the throne, Duke Duralumon, is an evil man who would repress the people if he were to become king, and because of this the King will go to any length to prevent him from taking over. Similarly, The Rose of Versailles (1972) is another that has a girl, pretending to be a guy, Oscar François de Jarjayes. For a "straight" trap, 1973's Ara Waga Tono! appears to be the first to fit the bill. This is a slapstick romance, where girls and boys clash in a ‘modern’ co-ed high school. There is a lot of romantic intrigue, quite a bit of gender-bending and some teenage angst when adults Just Don’t Understand. (source: goldbird) Then there's 1974's Oira Sukeban: Oira Sukeban (おいら女蛮?), sometimes called Sukeban Boy, is a Japanese manga created by Go Nagai in 1974. It is a comedy with several erotic touches, where the protagonist Banji Suke (or Sukeban) has to disguise himself as a girl in order to be able to attend an all-female school. As Suke Ban is a rebellious boy, this situation creates several comedic troubles. The manga was adapted to an OVA in 1992 and was released by ADV Films in the US under the name Delinquent in Drag. But my guess is that the trope really took off only after the publication and airing of Ranma ½ in the late 80s. The story revolves around a 16-year old boy named Ranma Saotome who was trained from early childhood in martial arts. As a result of an accident during a training journey, he is cursed to become a girl when splashed with cold water, while hot water changes him back into a boy. Ranma ½ had a comedic formula and a sex changing main character, who often willfully changes into a girl to advance his goals. The series also contains many other characters, whose intricate relationships with each other, unusual characteristics and eccentric personalities drive most of the stories. Although the characters and their relationships are complicated, they rarely change once the characters are firmly introduced and settled into the series.
{ "pile_set_name": "StackExchange" }
Q: Using arrays in function handler parametr I have a problem with finding solution to my problem. Is it possible to use arrays as argument in str2func? Example: A='@(X)10+(X(1)-2)^2+(X(2)+5)^2'; y=str2func(A); y(someArray); where X-array 1x2; A: sure: A='@(X) 10+(X(1)-2)^2+(X(2)+5)^2'; y=str2func(A); y([1 2]) just had to use the variable A instead of test in line 2. BTW, why are you using str2func? This is more straightforward: y=@(X) 10+(X(1)-2)^2+(X(2)+5)^2; y([1 2])
{ "pile_set_name": "StackExchange" }
Q: Why my javascript doesn't work from the server I just uploaded my website on a free host server but it doesn't work properly. I don't know why... can you help me please ? see the link : https://electrophotonique.000webhostapp.com/ A: Your code is fine but you just need to put your scripts at the end of your code before the </body> tag Like this : <html> <head> <link rel="stylesheet" href="CSS/style2.css"> <link rel="shortcut icon" href="IMAGES/PNG/favicon.png"> <meta charset="utf-8"> <title>Electrophotonique Ingenierie</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <!-- YOUR CODE - START --> ..... <!-- YOUR CODE - END --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="JS/sticky_navbar.js"></script> <script src="js/button.js"></script> <script src="js/index.js"></script> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Phonegap or steroid.js? I recently started studying Phonegap when I happen to read about appgyver and steroids.js.The latter seems to be a really easy and fast way to create apps.Now I am confused,should I hop on and give my full focus on learning appgyver or is there an element of phonegap which I should learn as well ? A: It somehow depends on what platform you are going to use. As far as I see, the iOS support of Steroids is much better than of Android, also with a higher priority on the developers future plans. Many important features are not supported on Android, like the Drawer native UI. Also, on one of my test phone(Moto G), the native UI calls in JavaScript are broken. For me, the main reason to consider Steroids is about the native UI stuffs, but disappointing me on Android. What's even worse, Steroids has only iOS simulator support for now. So for Android development, you can only use the AppGyver Scanner on your Android phone. So I would suggest you to do further evaluation if you are only working for iOS, or on Android but doesn't care about native UIs. Anyway, Steroids has a better workflow though. Update 10/18/2014: I've been working on some PhoneGap apps recently, and I think I may have found some more things related to this topic. Today's Steroids is having a much better Android support, with a fresh new Appgyver Scanner. Many native UI components are now working very well. Steroids has a closed-source build system, i.e. you will have to use their build service every time you want to publish a new version of your apps. However, this is somehow necessary, as Steroids is famous for its native UI components and native transitions. Steroids has a rather poor support for some of PhoneGap/Cordova plugins. This is also mainly because of the private build system. You can't build your final app by yourself in Eclipse/Android Studio/XCode like what we are doing for many other PhoneGap/Cordova apps. If you want to take the advantage of native UI transitions provided by Steroids, your web project will be split into several parallel parts (who run in their own corresponding WebViews). This increases the complexity of your project, especially when you are using some web frameworks. So, if you care a lot about native UIs, native transitions, and don't mind be bound to a proprietary platform, you can try Steroids. Otherwise, I would suggest you try Ionic(http://ionicframework.com/), which is a quite pure web implementation based on PhoneGap/Cordova.
{ "pile_set_name": "StackExchange" }
Q: Could you create a game for an older system (say, SNES) and sell it with an emulator as well as the game? I was looking into development for the SNES in assembly, as programming in assembly is my hobby. I then had the thought: what if I could sell my native SNES games for modern use (on steam, bundled with an emulator for example)? A: Yes there should be nothing illegal about emulation in itself (any virtual machines such as Java VM would similarly be illegal, if unsure ask a lawyer) and in this instance the SNES has no BIOS so that isn't an issue either but you'll need to license the rights to the emulator (if it does not permit commercial use freely already) or write the emulator yourself. And you'll likely have to add some custom features to make the emulator and emulated game more user-friendly for the computer user experience, for example: Auto-boot your game with the emulator locked to your game. Allow the game to give achievements? Cloud saves? It certainly has been done before with other platforms. For example Castlevania: Symphony of the Night for XBox 360, and classic games released on Steam already use bundled emulators such as those by Sega.
{ "pile_set_name": "StackExchange" }
Q: workflow task summary throwing error specified cast is not valid using spmetal layer I have created share point data access layer with spmetal, everything is works fine but when I try to query with task summary list through SPMETAL it throws error I tried several techniques to cast , directly use this Iqueryable list but as I try to access it, "it throws error specified cast is not valid" Any help or clue why is throwing this error A: Its solved by changing the types of event type to string and duration field with double . that error was produced by SPMETAL wrong mapping while generating the layer form SharePoint.
{ "pile_set_name": "StackExchange" }
Q: Price change for Configurable products in list Scenario: I have a configurable product with the price X (no special price). One (or more but not all) of the simple products attached to the configurable products has a special price Y (lower than X). In the product view page (works as desired): when the page loads I see the lowest price (Y in my case) along with regular price. when changing the configuration of the product and reaching a configuration that is not discounted I see only one price, the original one (X). changing the configuration to reach the discounted price product I see again, regular price and special price. In the product list page (does not work as desired): when the page loads I see the minimal price of the configurable product (Y) but no regular price or "special price" label changing the product configuration to anything else, changes the price to the price of the configuration (X or Y). Desired Result in the product list page: 1. when page loads, display the minimal price and the regular price (Regular price: X, Special Price: Y). 2. When the configuration changes show/hide the regular price and the special price label according to the selected options. Example: When selecting the configuration for the discounted price show both regular and special price (bonus: any other price type I add custom). When selecting a non-discounted configuration just show one price. Additional Info: I can achieve point 1 from the desired result by editing the final_price.phtml template for configurable products and removing the condition !$block->isProductList(). But in this case, the special price label remains there no matter what configuration I choose. Speculation: Since the regular price is not shown in the product list (see the conditions mentioned above), it makes me thing that by design, not all prices are shown in the product list for configurable products. Question: Is there a reasonable way (not rewriting all the price display logic) to achieve point 2 in the desired result section? A: I kind of got this working. I removed from the configurable product final_price.phtml the condition for not being in the product list !$block->isProductList(). This makes the prices change somehow. But there is a catch. Actually 2. First: If the product is configurable by 2 or more attributes (let's say color and size) and in the product list I only have enabled 1 attribute (color) when changing the color, I see the price of the first product that has that color. If that product does not have a special price I won't see it. If you want to always select the product that has a special price, this can be changed in the file https://github.com/magento/magento2/blob/2.2-develop/app/code/Magento/Swatches/view/frontend/web/js/swatch-renderer.js. This line result = $widget.options.jsonConfig.optionPrices[_.findKey($widget.options.jsonConfig.index, options)]; can be changed to loop through all the matching products and select the one with a discount. Second: When changing from a product with a discount to a product that does not have a discount, the "regular price" disappears, but the label "Special price" still remains. This can be overcome by changing Magento/Catalog/view/base/templates/product/price/amount/default.phtml. change <span class="price-label"><?= /* @escapeNotVerified */ $block->getDisplayLabel() ?></span> to this <span class="price-label <?= $block->getLabelClass()?>"><?= /* @escapeNotVerified */ $block->getDisplayLabel() ?></span> and in the final_price.phtml for the configurable product for the special price renderer this attribute needs to be added label_class => 'sly-old-price'. This kind of works as I need it to. Notes: This is only tested for configurable products. Haven't tested for downloadable or bundle. by "changing" in the code I mean properly overriding the files either in a module or in a custom theme. NOT IN THE CORE.
{ "pile_set_name": "StackExchange" }
Q: Сортировка выбранной строки двумерного массива Пожалуйста, напишите кусок кода, который сортирует выбранную строку двумерного массива. Пишу - не работает, вставляю готовый код - не работает #include "pch.h" #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "Russian"); const int n = 4; // размер массива int arr[n][n]; cout << "Введите массив:" << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << "arr[" << i << "]" << "[" << j << "]" << ": "; cin >> arr[i][j]; // ввод элементов массива } } cout << "=============================================" << endl; cout << "Введенный массив:" << endl; // вывод заполненного массива for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << " "; } cout << '\n'; } cout << "=============================================" << endl; int choice = 0, temp; cout << "Выберите строку, которую вы хотите отсортировать, выберите значение от 0 до 4:" << endl; cin >> choice; // сортировка cout << "Полученный массив:" << endl; // вывод результата for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << " "; } cout << '\n'; } } A: std::sort(arr[choice], arr[choice] + n); Или, если же самому нужно написать, то: int i = 0; int* first = arr[choice], *last = first + n; while (first != last) { for (int* p = arr[choice]; p != last- i - 1; ++p) if (*p > *(p + 1)) { int temp = *p; *p = *(p + 1); *(p + 1) = temp; } ++first; ++i; } Это один из самых простых вариантов сортировки. То же самое без указателей(по просьбе автора): int i = 0; while(i < n) { for (int j = 0; j < n - i - 1; ++j) if (arr[choice][j] > arr[choice][j + 1]) { int temp = arr[choice][j]; arr[choice][j] = arr[choice][j + 1]; arr[choice][j + 1] = temp; } ++i; } P.S. рекомендую изучать разные альгоритмы сортировки. Для строки choice двумерного массива просто рассматриваются элементы от arr[choice][0] и до arr[choice][n], где n это количество столбцов.
{ "pile_set_name": "StackExchange" }
Q: Proper way to say "Look at the sky" I've been learning japanese for quite a few weeks but I'm still pretty new to it so maybe this question will sound silly, if that's the case, I'm sorry. Because I really love the way it sounds and looks, I tryed learning japanese. And now, I'd like to get myself a tattoo. "Look at the sky" (which is one of the last things someone told me before passing away). Then again I'm learning with books (not the best way, is it?) so I'm running into a doubt. Would you rather spell it : 空を見て - Sora o mite or 空を見上げて - Sora wo miagete I'm having a hard time figuring out the difference (as I'm still a newbie in japanese) and as it's an important decision (the tattoo I mean) I'd really like if someone could explain the difference. A: 空を見て is "Looking at the sky," and 空を見上げて is "Looking up at the sky". Both are grammatical and make perfect sense as a Japanese sentence. They are reasonable choices for a book title or a line in a poem, for example. This may also be acceptable on a souvenir T-shirt, a mug or a fan. However, I have to say such a tattoo looks weird and funny to the eye of Japanese people for several reasons. First of all, Japanese people are very wary of tattoos in the first place, and traditional Japanese tattoos do not have any readable character. But I won't go into detail about cultural things for now. Even if we accept the idea of readable character tattoos, this sentence may not be suitable as the design of a tattoo. People usually expect something that looks cool and exotic in a tattoo. However 空を見(上げ)て is a very plain, casual and easy sentence even a 3-year-old Japanese kid can make. In general hiragana has a cute and/or childish image as a design element, which is probably not what you want for a tattoo. If you used this sentence, it might end up looking as if it were a tattoo in Comic Sans to those who can actually read it.
{ "pile_set_name": "StackExchange" }
Q: strange IDE in Visual Studio In my VS2015 there is a strange HTML tree nodes view of my MVC View. This tree nodes view occupies 1/4 of the screen all the time. I don't know what addon I added. There is no way to dismiss it. Does any know? A: I solved the problem by disable the suspected add-on one at a time until the problem goes away. Interestingly, when I re-enable each of the disabled add-on, the problem goes away without removing any add-on.
{ "pile_set_name": "StackExchange" }
Q: Calling functions one after other in event driven programming I'm working on a software where software issues commands for hardware panel and once a command is issued, its response received after few seconds . there are different functions for different hardware commands like public void FunctionA() { StartCommandA(); } and other functions on the same pattern that will be used to run other commands. FunctionB(); FunctionC(); Once we receive the response of command A , I invoke the other function from the response but this approach is not good as per design pattern practices. All i want to do is to make a list of functions and invoke all these functions one after other, But next function will be called once i get response of first functions. I tried this by using Multicast delegate but I'm unable to find out how we can call get the list of functions once i add all functions to that delegates. This is what i'm trying do since. FunList funList_ConfigAndSerialTests = new FunList(StartSerialTest); funList_ConfigAndSerialTests += StartSerialTest; funList_ConfigAndSerialTests += StartMsrTest; funList_ConfigAndSerialTests += StartContactLessTest; //funList_ConfigAndSerialTests.Invoke(); Delegate[] del = funList_ConfigAndSerialTests.GetInvocationList(); foreach (Delegate item in funList_ConfigAndSerialTests.GetInvocationList()) { while (true) { if (IsResponseReceived == true) { // Call function here } } } A: The simplest way to do this is to call the functions one by one: FunctionA(); FunctionB(); FunctionC(); Each method will be called only after the previous has returned. But you said you want to call the next function after the previous one has a response. Now that sounds like your functions run asynchronously. I strongly suggest you use the async keyword to mark your functions and make them return a Task<ResonseType>. You can learn about this here. You'll then be able to do something like this: await FunctionA(); // you obviously want to do something with the returned response // I do not know your requirements so I did not show that part await FunctionB(); await FunctionC();
{ "pile_set_name": "StackExchange" }
Q: Accessible topics with a background of linear Algebra and Calculus I have a background of a one year course in linear algebra (covering most of K&H) and two years of calculus (the first year was a one real variable course at the level of Spivak's Calculus book and then one year of multivariable calculus starting from topology of $\mathbb{R}^n$ and up to Stokes' theorem). I am looking for some interesting and not-so popular topics which I can understand and help me develop my understanding of the topics I already know. A: The subjects that are reasonably accessible after Calculus and Linear Algebra are: Real Analysis. Abstract Algebra. Elementary Number Theory. Elementary Set Theory. Elementary Logic. Combinatorics and Discrete Mathematics. Geometry. Differential Equations. Of these, 1-3 and 6 are "popular", so you want to discard them. 8 is popular among "users" of mathematics (engineers, for example). While Elementary Set Theory and Elementary Logic will probably help with mathematics in general, they are unlikely to give you any particular insight into either calculus or linear algebra. The best possible insight into calculus will be given by Real Analysis; the best possible insight into Linear Algebra will be given by Abstract Algebra. Elementary Number Theory is the source from which many other areas of mathematics sprung, but it will give you no insight into either linear algebra or into calculus (from Number Theory and Real Analysis you can move on to Complex Analysis and Analytic Number Theory, which will likely be useful; from Number Theory you can also move to abstract algebra and from there to Algebraic Number Theory, which would also shed light on the development of a lot of Algebra). Combinatorics and discrete math are quite fun and interesting, but again there is very little connection with calculus or with linear algebra. Likewise with Geometry. Topology is a reach, without some real analysis "in the bag" to fall back on, or a lot more experience with abstraction than provided by one year of Linear Algebra. It's not that real analysis and linear algebra are "independent of other subjects", it's that the gateways from linear algebra and real analysis to those "other subjects" that have intimate connections with them are precisely the subject that you want to avoid and discard because they are "popular." While "the road less traveled" may sound romantic, you may want to avail yourself of 100+ years of experience of mathematicians who have come up with, if not "royal roads", then at least well-traveled roads that help get you to your destination. A: I suggest at least looking over the following book. There's a 2nd edition available, but the 2nd edition is less theoretical and omits some of the linear algebra in the 1st edition. This book was very popular for those with approximately your background when I was an undergraduate (late 1970s), but I don't seem to hear about it much anymore (hence, it might fit your desire for something "not-so popular"). This book ties together and uses much of the calculus and linear algebra background that you have, and it also introduces/previews a few topics that come up in later math courses (e.g. some baby operator theory via exponentiation of matrices). Finally, at least in the U.S., you can find this book in most any college or university library (usually cataloged at QA3.P8). Morris W. Hirsch and Stephen Smale, Differential Equations, Dynamical Systems, and Linear Algebra, Pure and Applied Mathematics #60, Academic Press, 1974, 358 pages. http://www.amazon.com/dp/0123495504
{ "pile_set_name": "StackExchange" }
Q: Removing padding/margin consistently in multiple wraps I’m trying to get the light green to be disappeared (not gone but underneath the dark green). It’s the exact same problem as my previous post (Remove padding/margin between elements in shrink-to-fit container) but the only thing that’s different is the wrap is inside another wrap, and none of the zero margins/paddings, display inline-blocks or overflows work. #footer-left{ float:left; width:700px; height:200px; background:#CC3; } #footer-services-contents-wrap{ background:#030; width:auto; height:auto; display:inline-block; } #footer-services-title-wrap{ background:#0F0; width:auto; height:auto; display:inline-block; } .footer-wrap-left{ width:auto; height:auto; display: inline-block; border-left:1px solid #ccc; padding-left:50px; padding:0; border:none; float:left; } ul.footer { list-style-type:none; padding: 0px; color:#666; font-weight:100; font-family:verdana,arial,"Times New Roman", Times, serif,georgia,serif,helvetica; font-size:20px; margin: 10px 0 0 0; } .footer-wrap-right{ width:auto; height:auto; display: inline-block; border-left:1px solid #ccc; padding-left:50px; padding:0 0 0 50px; border:none; float:left; } <div id="footer-left"> <div id="footer-services-title-wrap"> <div id="footer-services-contents-wrap"> <div class="footer-wrap-left"> <f1>text goes here</f1> <ul class="footer"> <li>text text</li> <li>text text</li> <li>text text</li> </ul> </div> <div class="footer-wrap-right"> <f1>more text goes here</f1> <ul class="footer"> <li>text text</li> <li>text text</li> <li>text text</li> </ul> </div> </div> </div> </div> A: You don't need float:left when using inline-block in your footer-wrap-right and footer-wrap-left classes: #footer-left{ float:left; width:700px; height:200px; background:#CC3; } #footer-services-contents-wrap{ background:#030; width:auto; height:auto; display:inline-block; } #footer-services-title-wrap{ background:#0F0; width:auto; height:auto; display:inline-block; } .footer-wrap-left{ width:auto; height:auto; display: inline-block; border-left:1px solid #ccc; padding-left:50px; padding:0; border:none; } ul.footer { list-style-type:none; padding: 0px; color:#666; font-weight:100; font-family:verdana,arial,"Times New Roman", Times, serif,georgia,serif,helvetica; font-size:20px; margin: 10px 0 0 0; } .footer-wrap-right{ width:auto; height:auto; display: inline-block; border-left:1px solid #ccc; padding-left:50px; padding:0 0 0 50px; border:none; } <div id="footer-left"> <div id="footer-services-title-wrap"> <div id="footer-services-contents-wrap"> <div class="footer-wrap-left"> <f1>text goes here</f1> <ul class="footer"> <li>text text</li> <li>text text</li> <li>text text</li> </ul> </div> <div class="footer-wrap-right"> <f1>more text goes here</f1> <ul class="footer"> <li>text text</li> <li>text text</li> <li>text text</li> </ul> </div> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: What Access Rights am I Missing on my Stored Procedure I'm trying to run a stored procedure from my website that disables a trigger. Here is the code for the trigger: CREATE PROCEDURE [dbo].[DisableMyTrigger] AS BEGIN alter table dbo.TableName DISABLE TRIGGER TriggerName END I've also set the permissions on the stored procedure with: Grant Exec on dbo.DisableMyTrigger To DBAccountName DBAccountName is and has been able to run other stored procedures as well as dynamic SQL statements without issue. Here is the code from my CFM page: <cfstoredproc datasource="myDatasource" procedure="DisableMyTrigger" /> And here is the error I'm getting: [Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][SQL Native Client][SQL Server]Cannot find the object "TableName" because it does not exist or you do not have permissions. A: Does DBAccountName have permissions to TableName? These can be granted or revoked separately from the overall schema (dbo). I'm not a dba, but is DBAccountName allowed to execute DDL statements? (so it can do things like disable triggers programmatically)
{ "pile_set_name": "StackExchange" }
Q: the point of using a webhook secret For a heroku app, I have a webhook for "api:release". Even if I set a secret for the webhook, my webhook app still receives the hook. So what's the point of setting the optional secret ? A: Anyone can hit your webhook and trigger your build because it's a HTTP endpoint with no authentication. To prevent scripts/abusers starting a massive amount of builds the secret can be used. When receiving the webhook the sender has to include a token, this token can be validated by comparing it to the secret. If the tokens match it is same to assume that a valid client send it. If the token doesn't match uo you can ignore the request and thus prevent an unnecessary build that was initiated from an untrusted source. More details about setting up the secrets: https://devcenter.heroku.com/articles/app-webhooks#step-3-subscribe To compare the checksum you can use the following snippet: crypto.createHmac('sha256', '12345').update(Buffer.from(req.rawBody)).digest('base64'); and compare it with the Heroku-Webhook-Hmac-SHA256 header value.
{ "pile_set_name": "StackExchange" }
Q: Pandas to_sql doesn't create a file I'm trying to save my pandas dataframe as a SQL file I followed the documentation and tried from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:') df.to_sql('filename.sql', engine, chunksize=1000) However, when I check the directory with os.listdir(), the file is not there A: The first argument you pass to to_sql should be the name of the table in your database, not the name of the file. Take a look at the docs. Also, if you want to create a sqlite file, you should create an engine with a file database, not in-memory: engine = sqlalchemy.create_engine("sqlite:///mydb.db") # relative path to db df.to_sql("my_table", engine) Now there should be a file named mydb.db in the same directory where you run your application/script, with a table my_table containing the data in df.
{ "pile_set_name": "StackExchange" }
Q: PHPUnit Symfony Test Case error I am new to Symfony, I have wrote small app now have to add unit tests, here is my controller: <?php namespace myBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; class IndexController extends AbstractController { /** * @param \Symfony\Component\HttpFoundation\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function indexAction(Request $request) { if ($this->getRequest()->isMethod('POST')) { // Do Something } // Do Something otherwise } } My test: class IndexControllerTest extends \PHPUnit_Framework_TestCase { protected $testController; public function setUp() { $this->testController = $this->getMockBuilder('myBundle\Controller\IndexController') ->disableOriginalConstructor() ->getMock(); } public function testPostSaveActionWithBadRequest() { $expectation = 'Some text '; $response = $this->testController->indexAction(new Request); $this->assertInstanceOf( 'Symfony\Component\HttpFoundation\JsonResponse', $response ); $content = json_decode($response->getContent()); $this->assertEquals($expectation, $content->error); } } When I run this test I get following: PHP Fatal error: Call to a member function get() which is basically on following line if ($this->getRequest()->isMethod('POST')) { this tells me the container is null (I verified it by printing dump of the container). any idea what am I missing here or is there a way to provide container as dependency for that test. I really appreciate all the help. thanks FI A: You're trying to mock the class you're suppose to test: $this->testController = $this->getMockBuilder('myBundle\Controller\IndexController') ->disableOriginalConstructor() ->getMock(); You should actually instantiate the class you're testing, and mock or stub its collaborators. However, in this particular scenario, instead of writing a unit test, write a functional test. There's a chapter on writing functional tests in Symfony docs that'll help you. Your controller uses lots of framework classes (classes that don't belong to you), and you shouldn't mock them either. That's why functional tests are better in this case. Also, make sure you move as much code as possible out of your controller, so you can properly unit test that part (and write as little functional tests as possible). In the meantime read some books on unit testing (in the following order): TDD by Example Growing Object-Oriented Software Guided by Tests
{ "pile_set_name": "StackExchange" }
Q: How iPad can run terminal as linux system? If I want to develop software on an iPad, how to start a terminal like linux and save the source local? A: Without jailbreaking you can't really. iOS is designed not to allow executables to be created or even files to be moved between apps. Also there is no terminal. If you want to build apps for iOS you generally use code on a mac. However there are some apps that allow programming on the iPad but all run inside the app. Examples of this include Swift Playgrounds from Apple and various interpreters for Python, Javascript and Lua. (I have not provided links as I have not used them and my quick search found low rated or old apps) there are also interpreters that you can build on the Mac and install like Pharo ( a version of smalltalk).
{ "pile_set_name": "StackExchange" }
Q: removing space before new line in java i have a space before a new line in a string and cant remove it (in java). I have tried the following but nothing works: strToFix = strToFix.trim(); strToFix = strToFix.replace(" \n", ""); strToFix = strToFix.replaceAll("\\s\\n", ""); A: myString.replaceAll("[ \t]+(\r\n?|\n)", "$1"); replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
{ "pile_set_name": "StackExchange" }
Q: Eclipse giving errors whenever I try to export to executable jar I'm trying to export a small program that I have made in Eclipse Indigo today to an executable, however, every time I do so one of two problems occur. The program uses one resource which I was hoping to put inside of the JAR but Eclipse will not put in the executable jar no matter which option I tick when I export or which folder the resource is in - the first problem! The second problem is that whenever I tell eclipse to "Extract required libraries into generated JAR" I receive the following error when I double click on the executable Jar: Could not find the main class: main.Launcher. Program will exit. I don't suppose that the second problem is too much of an issue at the minute but the first one is extremely frustrating so I would appreciate any help or advice. Thanks in advance. (Strangely, and even more frustrating, if I go through the same process with a project I made a while ago with a previous version of Eclipse it works perfectly.) The folder structure of the project is as follows: In the project folder there are the following directories .settings, bin, src as default. I have put the resource, which is a png in the bin folder but I have also tried it in the src folder. A: First of all, I would like to thank Mike (marksml) for being so helpful and attempting to provide a solution for my problem. Unfortunately, his answer did not work for me! I began to look at all of my previous projects and noticed that the one I was having trouble with was the odd one out (because it was the only one that didn't work) and the factor that made it the odd one out, I found to be the JRE system library version. The project was using the JavaSE-1.7 library but when I changed it to the JavaSE-1.6 like my other projects were using it miraculously worked and exported flawlessly! I'm still curious as to why this is the case, but at least I have it working now... With thanks and kind regards, Andy
{ "pile_set_name": "StackExchange" }
Q: Custom Key Bindings in SWT Is it at all possible to add custom key bindings to buttons in SWT? I can't use & in the text of the button to set a mnenomic because my buttons have no text (only an image). Is there a good way to do this using key listeners or is there something like the input/action map in swing? A: We are using Actions, but those have to be added to the menu or the toolbar to function. But since this is a usuability standard anyway, be have no problem with doing it so. Inherit from org.eclipse.jface.action.Action, and use a MenuManager to create your Menus. Immediaty satisfaction guaranteed.
{ "pile_set_name": "StackExchange" }
Q: Adding label to tkinter widget changes entire layout I am making a python text editor, and I am now busy with the find function. Then when the last occurance of the users input is found, it jumps back to the beginning again, and it shows the text 'Found 1st occurance from the top, end of file has been reached' at the bottom of the window. But showing this changes the position of all the other items too, as you can see here. Now I want to start out with the layout I get after adding the text to the bottom of the dialog. Here's my relevant code: find_window = Toplevel() find_window.geometry('338x70') find_window.title('Find') Label(find_window, text='Enter text to find:').grid(row=0, column=0, sticky=W) find_text = Entry(find_window, highlightcolor='blue', highlightbackground='blue', highlightthickness=1) find_nextbutton = Button(find_window, text='Find Next', command=find_next) find_allbutton = Button(find_window, text='Find All') find_text.grid(row=0, column=1, sticky=W) find_nextbutton.grid(row=0, column=2, sticky=W) find_allbutton.grid(row=1, column=2, sticky=W) And when the last occurance is found I do this: file_end = Label(find_window, text='Found 1st occurance from the top, end of file has been reached.') file_end.grid(row=2, columnspan=4, sticky=W) A: The simplest solution is not force the window to a specific size, and to always have that label there. Set the width large enough to include the full text of the message. When you are ready to show the value, use the configure method to show the text. Here's a complete example based on your code: from tkinter import * root = Tk() text = Text(root) text.pack(fill="both", expand=True) with open(__file__, "r") as f: text.insert("end", f.read()) def find_next(): file_end.configure(text='Found 1st occurance from the top, end of file has been reached.') find_window = Toplevel() #find_window.geometry('338x70') find_window.title('Find') Label(find_window, text='Enter text to find:').grid(row=0, column=0, sticky=W) find_text = Entry(find_window, highlightcolor='blue', highlightbackground='blue', highlightthickness=1) find_nextbutton = Button(find_window, text='Find Next', command=find_next) find_allbutton = Button(find_window, text='Find All') file_end = Label(find_window, width=50) find_text.grid(row=0, column=1, sticky=W) find_nextbutton.grid(row=0, column=2, sticky=W) find_allbutton.grid(row=1, column=2, sticky=W) file_end.grid(row=2, columnspan=4, sticky="w") find_window.lift(root) root.mainloop()
{ "pile_set_name": "StackExchange" }
Q: Переопределение в классе python(курсы) Необходимо понять, в чем может быть ошибка данного кода, а точнее где, могут возникнуть "вопросы". def __mul__(self, alpha): if isinstance(alpha, Matrix): result = [] numbers = [] for i in range(len(self.lists)): for j in range(len(self.lists[0])): numbers.append(int(alpha * self.lists[i][j])) if len(numbers) == len(self.lists[0]): result.append(numbers) numbers = [] else: result = [] numbers = [] for i in range(len(self.lists)): for j in range(len(self.lists[0])): numbers.append(int(self.lists[i][j] * alpha)) if len(numbers) == len(self.lists[0]): result.append(numbers) numbers = [] return Matrix(result) __rmul__ = __mul__ Использование этой части класса - верное, и результат верный. Но проверяющая система ругается и выдает ошибку типа "Runtime error" Отсюда вопрос, где я неверно или возможно неточно использую класс... Полный код класса и требований ниже: Класс: from sys import stdin from copy import deepcopy class MatrixError(BaseException): def __init__(self, r1, other): self.matrix1 = r1 self.matrix2 = other class Matrix: def __init__(self, lists): self.lists = deepcopy(lists) def __str__(self): strRep = "" amount = 0 for lists in self.lists: if amount != 0: strRep += "\n" new_str = "\t".join(str(elem) for elem in lists) strRep += new_str amount += 1 return strRep def size(self): return len(self.lists), len(self.lists[0]) def __add__(self, other): if len(self.lists) == len(other.lists): lenght = len(self.lists[0]) for row in self.lists: if len(row) != lenght: raise MatrixError(self, other) for row2 in other.lists: if len(row2) != lenght: raise MatrixError(self, other) result = [] numbers = [] for i in range(len(self.lists)): for j in range(len(self.lists[0])): summa = other.lists[i][j] + self.lists[i][j] numbers.append(summa) if len(numbers) == len(self.lists[0]): result.append(numbers) numbers = [] return Matrix(result) else: raise MatrixError(self, other) def __mul__(self, alpha): if isinstance(alpha, Matrix): result = [] numbers = [] for i in range(len(self.lists)): for j in range(len(self.lists[0])): numbers.append(int(alpha * self.lists[i][j])) if len(numbers) == len(self.lists[0]): result.append(numbers) numbers = [] else: result = [] numbers = [] for i in range(len(self.lists)): for j in range(len(self.lists[0])): numbers.append(int(self.lists[i][j] * alpha)) if len(numbers) == len(self.lists[0]): result.append(numbers) numbers = [] return Matrix(result) __rmul__ = __mul__ def transpose(self): t_matrix = list(zip(*self.lists)) self.lists = t_matrix return Matrix(t_matrix) def transposed(self): t_matrix = list(zip(*self.lists)) return Matrix(t_matrix) # Task 2 check 3 m = Matrix([[1, 1, 0], [0, 2, 10], [10, 15, 30]]) alpha = 15 print(m * alpha) print(alpha * m) #exec(stdin.read()) В конце как раз проверка. Результат верный, но способ проверки - нет. Условия задания:Реализуйте класс Matrix. Он должен содержать: Конструктор от списка списков. Гарантируется, что списки состоят из чисел, не пусты и все имеют одинаковый размер. Конструктор должен копировать содержимое списка списков, т. е. при изменении списков, от которых была сконструирована матрица, содержимое матрицы изменяться не должно. Метод str, переводящий матрицу в строку. При этом элементы внутри одной строки должны быть разделены знаками табуляции, а строки — переносами строк. После каждой строки не должно быть символа табуляции и в конце не должно быть переноса строки. Метод size без аргументов, возвращающий кортеж вида (число строк, число столбцов). add, принимающий вторую матрицу того же размера и возвращающий сумму матриц. mul, принимающий число типа int или float и возвращающий матрицу, умноженную на скаляр. rmul, делающий то же самое, что и mul. Этот метод будет вызван в том случае, аргумент находится справа. Для реализации этого метода в коде класса достаточно написать rmul = mul. Иллюстрация: В следующем случае вызовется mul: Matrix([[0, 1], [1, 0]) * 10. В следующем случае вызовется rmul (так как у int не определен mul для матрицы справа): 10 * Matrix([[0, 1], [1, 0]). Разумеется, данные методы не должны менять содержимое матрицы. Добавьте в программу из предыдущей задачи класс MatrixError, содержащий внутри self поля matrix1 и matrix2 — ссылки на матрицы. В класс Matrix внесите следующие изменения: Добавьте в метод add проверку на ошибки в размере входных данных, чтобы при попытке сложить матрицы разных размеров было выброшено исключение MatrixError таким образом, чтобы matrix1 поле MatrixError стало первым аргументом add (просто self), а matrix2 — вторым (второй операнд для сложения). Реализуйте метод transpose, транспонирующий матрицу и возвращающую результат (данный метод модифицирует экземпляр класса Matrix) Реализуйте статический метод transposed, принимающий Matrix и возвращающий транспонированную матрицу В общем, я потерян. A: Я немного упростил и чутка поправил ваш код. Например, критерий правильности аргументов в add& на мой взгляд, должен быть таким if isinstance(other, Matrix) and self.size() == other.size(): весь код class Matrix: def __init__(self, lists): self.lists = deepcopy(lists) def __str__(self): return '\n'.join(['\t'.join(map(str, row)) for row in self.lists]) def size(self): return len(self.lists), len(self.lists[0]) def __mul__(self, alpha): lst = [[ alpha * el for el in row] for row in self.lists] return Matrix(lst) __rmul__ = __mul__ def transpose(self): self.lists = list(zip(*self.lists)) return self @staticmethod def transposed(self): t_matrix = list(zip(*self.lists)) return Matrix(t_matrix) def __add__(self, other): if isinstance(other, Matrix) and self.size() == other.size(): return Matrix([[a+b for a,b in zip(x,y)] for x,y in zip(self.lists, other.lists)]) else: raise MatrixError(self, other)
{ "pile_set_name": "StackExchange" }
Q: How to implement min left/right in css I have an element in my css which look like below .xyz{ position:absolute; left:50%; } Now as expected when I reduce the width of browser window, this element moves towards left. However I want it to stop at a certain point since otherwise it starts overlapping other elements. In principle, this is very similar to min-height and and min-width properties. But there is no such property like min-left or min-top. How can I implement this. A: If you can estimate the window size, where the movement should stop, (let's say 700px) you can use media queries: @media (max-width: 700px) { .xyz { left: 10px; } } Then for windows narrower than 700px, the element is placed fixed at left: 10px (adapt CSS as suited for you).
{ "pile_set_name": "StackExchange" }
Q: Wife does not work but wants “own” money/allowance My wife and I have been married 4 years (United States). We had a baby 6 months ago and 8 months ago my wife quit working, it started to be to much on her physically and now we both like that our child is not in daycare, which means someone has to be home, this ended up being my wife as she worked part time and my income far exceeded what she earned. Originally we had our own bank accounts, she still maintains her own checking account and is now on as a registered user at my credit union on my accounts (checking, savings, special purpose and daughters account). A couple years ago we went to my credit union and got her a debit card to use against my checking account as she felt that if something happened to me she would not have any money. Many years ago, probably 7 or 8 we decided that since I am more disciplined with money that I would be responsible for making sure all of our bills were paid, both personal and joint (credit cards we had before each other, mortgage etc) Since my wife is no longer employed (albeit working pretty hard, babies are demanding little bosses) she has obviously no personal income. This is the point in which we differ in our though process, she feels that money earned from employment is hers or mine, where my thought process is, we are married, and all accounts except her checking are joint, there is no yours and mine, there is only ours. Since she does have a debit card linked to what is now and has been for awhile now, our checking account, my philosophy is, if you need something just swipe the card, that is after all why she wanted it, to be able to access money in what was previously my checking account before she became an authorized user on my accounts (which at the institution is equal to joint). After about two months my wife started to tell me that she wanted a weekly allowance so she can make her own purchases without me seeing what they are as I don't need to. My wife also states that she feels guilty swiping the debit card and that she feels like she needs to get my permission before using it, she only needs to "ask my permission" (which isn't really asking my permission, it's informing your partner of what you intend to do with a larger amount of money which is a reasonable thing to do in my opinion) if the purchase is large, which I always do as well. I choose to do that for purchases of $20 or more, it just keeps her informed of where the money went, other then that, use it for what you need it for, gas, groceries, misc crap at 7-11. Today she forgot her PIN, and this brought up the conversation again of her having her own money. She wants an allowance, so for either me to write her a check every week that she can go deposit in her own bank account (which I am not on) or for me to give her cash. My reply was in my view of the logical sort, "if you need to get something, then swipe the card, that's why you have it." This, as it did in our previous discussion on this matter, make her mad. She stated that "You should not need to see every transaction that I make" so again my response which was taken not so well was "what do you mean I don't need to see every transaction, what are you trying to hide, you have the debit card to use, that's why we got it for you, so use it and if you have to have cash for some transaction, go to the ATM and get it" I personally do not take an allowance, I don't understand the point, if I need something I get it or ask my wife while she is out and about to get it for me. My response was like that because it has happened to me on multiple occasions where a family member has just used my credit card to get what they want without my knowledge or even just coming to me and asking, which I count as theft. I have also had to close and open checking accounts on at least three (3) different occasions due to someone gaining access to my account, so I am always suspicious and always check my bank account, sometimes multiple times a day. How can I approach this to discuss with her so that we can both get our feelings across and understand each other's side? To me it feels like I just have to give her whatever allowance she wants, which leaves me feeling resentful, which I can't stand for obvious reasons. I know I am failing to understand her point of view as I think she is also failing to see mine. As I said, there is, in my opinion, no your money or my money, there is one income in our family unit and it is our income. I am by no means trying to "control her", she can do whatever she wants, she is a human being. As I said in the above, as far as I am concerned we don't have "our own money", we have a joint account where all the bills get paid from, she used to get the groceries on her own from her checking account when she was working, but now she is working at home, meaning taking care of our child. A: You say that money is tight. Do you do all the budgeting on your own or does she get a say? Is it something you decide together or something you handle by yourself? Do you include in your budget an amount for 'personal' use? My husband and I also have the view that our money is ours. We discuss our budget and our expenses and decide on things together. This process includes a discussion about what 'personal' money we thought we needed every month. I proposed how much I need for my hobby, he said how much he'd need for his, we discussed what we could afford, and decided on an amount that we'd each get every month. This isn't giving her whatever allowance she wants, this is having a discussion together about your budget and what you can afford, and what 'allowance' you give both of you. There are two issues here. One is the financial independence and the other is the budget. You can give her the cash in an envelope at the beginning of every month if you want, no bank account necessary. The issue I see here is that she doesn't feel like she is on the same page as you. I sometimes phone my husband to get his opinion on a purchase. I don't ask permission, or even to state what I'm going to be doing. I phone to discuss if it's something we can afford with our money. We have a discussion and decide together if we can afford it or not. As such, purchases fall into two categories: - in the budget so OK by default. - not in the budget so discussion required. Does that mean that if I want to buy myself a chocolate bar I can't because it's not in the food budget, or I have to phone my husband to ask? No, because it comes out of my 'personal' allocation which is in budget. This is why personal allocations are important. She's actually asking to discuss with you a limit on what she can personally spend so she knows where she fits into the budget. This way, she can buy herself something she wants as a treat and not worry she's ruining the budget. The bank account for this is convenient, but not essential. There may be a reason she wants a bank account, perhaps she wants to save her 'treat' money for something bigger over multiple months. Nonetheless, it's important to discuss with her how much you can afford for both of you every month, not just her, and it certainly isn't giving her everything she wants. A: We are in a similar arrangement in our marriage, where I bring in the bulk of our earnings. For a long time my wife did not work, but now as the kids are getting older, she is working a part time job. What works for us is: All money earned is “our money” - my earnings do not trump hers for any decision making. We discuss our budget together. As part of the above, we budget money equally as “personal money” For us, we each get an hour of my time per paycheck, direct deposited into an account we control The rest of our money is all joint, and it covers normal family expenses (mortgage, food, etc) Personal money is no-judgement. If she blows it all on Starbucks or saves up for an expensive gadget then it makes no difference to me. Same goes for my spending out of my personal account. This allows us to communicate on shared goals for trips, savings, retirement, etc while still allowing autonomy. Sometimes we negotiate on things “Hey, I want to visit a friend for a weekend out of town.” If we don’t have much in our travel budget, then personal money becomes a way to make it work. What we do may or may not work for you, and the dollar amounts may be different even if it does. Regardless, we arrived where we are by having a discussion about our needs and working together to design a solution we could both agree to. It sounds like she doesn’t feel the autonomy is there for her in the current arrangement, and that gives her guilt for certain spending. I don’t know that you can get away from that while maintaining a single pooled account. Express your fears and doubts about that second account, and see if you both can find a solution to allay those fears? A: Before the discussion What you need to do to start is take a step back and get your feelings in order. You can't help her understand your side if you can't be completely sure you can explain it clearly. Why do you feel that it makes no sense for you each to have a private account? Do you feel like it's unreasonable for your wife to want you not to be able to see every transaction she makes? Also consider why this is a big enough deal to you that you needed to come to Stack Exchange with it. I'm not saying you're wrong for doing so, just that it shows that you likely feel just as strongly as she does about the situation. Why? Do you feel like this insults you in some way? Is it the insinuation that she doesn't want you to know everywhere she shops? Could it just be "I'm right/she's wrong" mentality that comes up in humans? Knowing why you're so intent on this in one way or another will go a long way towards things. Ask your wife to do the same thing, if you think it will help to let her prepare as well. This gives her a chance to have her side as thought out as you do. Let her know that you want to get to the bottom of this, and have you both at the very least understand where the other is coming from. It might help just knowing that you want to understand why this has her so upset. Don't let her start the discussion there- If she tries to, explain that you want to be able to convey your feelings on the matter as clearly as possible, and want to take the time to really know how to do so before you discuss things. Let her know that you hope she will do the same, so you can have a rational conversation. Addressing the situation When you are both ready, choose a time when you're both calm and the baby won't need your immediate attention for at least half an hour. A nap is likely the only time you'll get for this, from my limited experience with infants. Outline a couple rules: You each get a turn to fully explain yourself, then the other may ask questions to understand your side as needed. From there, the next person can explain uninterrupted and the other side can again ask questions as needed. Ask her to go first, and let her explain her side. Then listen. Listen to what she has to say. Let her say her piece, let her outline how she feels. When she's done, ask questions as you need to so that you can be sure you understand this to the best of your abilities. Once she's explained her side of things and you're pretty sure you understand it, restate it. Make sure your interpretation matches hers. If it doesn't, she can clarify further. From there, you can take your turn. Explain why you feel how you do. Be clear about where your points of view differ. Answer her questions, and ask her to restate how she interpreted what you've said. This should all mirror how you came to understand her side. Now that you've both explained your sides and had a chance to understand each other, you can either both step away to try to come up with ideas for how to resolve this and keep it fair to you both while still keeping you both happy, or you can go ahead and work to sort out a solution. If you do go ahead and work toward a solution, make sure you're both still calm. Otherwise, insist on walking away for a bit until you're both calm (and the baby is napping again.) Aftermath Once you have a solution, stick to what you agree on. Now that you both understand each other and worked for a resolution, it should help keep this problem from boiling up again. If something in the status quo changes down the road and another issue of the kind arises, at least you'll already have a way to hit it up and try to address it. Keep in mind, if you agree to go with an allowance for her, be sure that this goes both ways: You deserve a private "just yours" account as well! You could even make it so you each get the same "personal allowance" each week, to keep things even. This also helps show your wife that you don't feel superior to her just because you're the one bringing home paychecks. This might not even cross her mind, but if it does, then you've addressed it without a problem. (Your own "personal allowance" may not be necessary- If she suggests your paycheck goes to your personal account and you just put what's needed for bills into the account you pay bills/groceries from, then you should be able to do that. Just try to do what seems fairest to both of you.) Keep it fair, keep it reasonable, and keep each other happy. In the end, your love and happiness with each other is more important than figuring out what money belongs to who anyway.
{ "pile_set_name": "StackExchange" }
Q: Difference between Generalized linear modelling and regular logistic regression I am trying to perform logistic regression for my data. I came to know about glm. What is the actual difference between glm and regular logistic regression? What are the pros and cons of it? A: The main benefit of GLM over logistic regression is overfitting avoidance. GLM usually try to extract linearity between input variables and then avoid overfitting of your model. Overfitting means very good performance on training data and poor performance on test data.
{ "pile_set_name": "StackExchange" }
Q: Related Products, Up-Sells, and Cross-Sells modal panel error After moving to Magento ver. 2.2.2 from Magento var. 2.1.9 the Related Products, Up-Sells, and Cross-Sells modal panel from catalog product edit doesn't show anymore. I can see these error in the console Uncaught TypeError: Cannot read property 'apply' of undefined at registry.js:59 at Registry._resolveRequest (registry.js:418) at Registry._addRequest (registry.js:385) at Registry.get (registry.js:229) at async (registry.js:58) at UiClass.applyAction (button.js:78) at Array.forEach (<anonymous>) at UiClass.action (button.js:56) at HTMLButtonElement.<anonymous> (knockout.js:3863) at HTMLButtonElement.dispatch (jquery.js:5226) After many debugging hours I found the KO component applied to product_form.product_form.related.related.modal is Magento_Ui/js/form/form instead of Magento_Ui/js/modal/modal-component Can anyone help or point me in the right direction to fix it? A: I don't have enough info to determine the fix, but it sounds like a file you have overwritten needs updating with something from the core. I would start by removing all customisations you've done to related/upsell/crosssells and see if that resolves the issue, if it does then start removing those files one-by-one. If removing a file fixes it then you know the issue is related to that file. You can then run a diff with your version and the updated core version to hopefully see what you need to include. It may help to go through the release notes for each release and check what changes have been made to related/upsell/crosssells, for example in 2.2.2 these changes were made: A price change to a custom option affects only that option. Previously, changing the price of a custom option also affected the price of related products. GitHub-4588, GitHub-5798, GitHub-6041, GitHub-6097 And Magento now successfully loads re-ordered related products when Edge-Mode is activated. If removing all your changes fails then I wish you extra good luck. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: ms-access 2003 combo box population I have an entry form with a sub. I have three combo boxes that work together. combo 1 sets up with vba and an after event combo 2 and on into three. They work fine independently of the main form, but when I sue the form as a sub the cascade stops working. Forms Main Form Name "1A-Event Entry" SubForm Name "1B-Event sub" ComboBox 1 (After Update) Private Sub Category_AfterUpdate() Me.Type = Null Me.Type.Requery Me.Type = Me.Type.ItemData(0) End Sub ComboBox 2 (SQL) SELECT Type.ID, Type.Type, Type.Category FROM Type WHERE (((Type.Category)=[Forms]![1B-Event sub]![Category])) ORDER BY Type.Type; CombBox2 (After Update) Private Sub Type_AfterUpdate() Me.Detail1 = Null Me.Detail1.Requery Me.Detail1 = Me.Detail1.ItemData(0) End Sub ComboBox3 (SQL) SELECT Detail.ID, Detail.Detail, Detail.Type FROM Detail WHERE (((Detail.Type)=[Forms]![1B-Event sub]![Type])) ORDER BY Detail.Detail; I am sure is has something to do with the Form/ Subform scripting in the SQL, but it escapes me. A: As a subform, you need a different reference: WHERE Type.Category=[Forms]![1A-Event Entry]![Subform Control Name Here].Form![Category] When a form is run as a subform of another form, you must refer to the subform control.
{ "pile_set_name": "StackExchange" }
Q: quick question about plist Can my application download a .plist from a URL and replace the one that I built in xcode and shipped with the application? Thanks Leo A: No, you can't change anything in your application bundle. You must download you plist file to some folder in application sandbox (documents or caches) and read it from there. Your possible workflow for reading that plist can be: Check if plist file is present at download location. If yes - read it from there If it is not present - read plist shipped with your bundle (or copy plist file from bundle to download location and go to step 1 - this way workflow may be a bit more consistent)
{ "pile_set_name": "StackExchange" }
Q: Why does mDNS (Bonjour, Avahi, etc) use UDP? It seems to me that a lot of the problems with DNS, particularly security problems, have the root cause of DNS being implemented over UDP; for example the responder doesn't have to be who he says he is. I don't know the details of mDNS protocol (which I assume is much newer than DNS), maybe it takes care of these problems in its application level. Can anyone shed some light on this for me? A: The 'm' in mDNS stands for "multicast." An mDNS query is pretty much a regular DNS query multicast (aka broadcast) to the local subnet. Every host on the subnet receives all mDNS query packets and responds to the ones for their host name. Since it isn't possible to do a TCP broadcast, you couldn't implement mDNS over TCP. There's a more fundamental point here though, mDNS is already completely insecure. As you point out, anyone can respond to any query so you pretty much have to trust all the hosts on the network. Switching to TCP (if you could) wouldn't fix this problem. A: Zeroconf is not concerned with security; security should be implemented in the layer above. TCP wouldn't change much. These problems have to be solved cryptographically.
{ "pile_set_name": "StackExchange" }
Q: PHP can't move (write) uploaded files to mounted network drive We develop our PHP-based web applications by editing our working files in a shared, local directory on each of our windows machines. The (linux) staging server then mounts our shared drives and serves them each under subdomains. E.g. joe.work.com would serve Joe's working directory. We then access our own staging sites by editing our hosts file to point the subdomain to the staging server...and all of that works great! We're now running into the issue that PHP doesn't seem to have permission to move uploaded files from the tmp directory to a directory inside of the mounted directory (which is actually the shared windows drive...?). The working directory on the windows machines are set to allow everyone rw, and I have tried putting 777 on the mounted directory in the staging machine, but I am still get permission denied. The shared drive, say, \\joes_machine\joes_working_dir mounts on the staging server to /var/mnt/joe. The file upload needs to be moved to /images/common. Albeit slightly dumbed down for this example, I'm not doing anything fancy code-wise: $working_directory = '/var/mnt/joe'; $image_directory = '/images/common/'; $full_filename = $working_directory . $image_directory . $filename; if(move_uploaded_file($_FILES['photo']['tmp_name'], $full_filename)) // do some other stuff My error of course is: Message: move_uploaded_file(/var/mnt/joe/images/common/resulting_filename.jpg): failed to open stream: Permission denied Message: move_uploaded_file(): Unable to move '/tmp/phpjsEfBc' to '/var/mnt/joe/images/common/resulting_filename.jpg' What am I not understanding about file permissions pertaining to a windows shared drive being mounted over the network by linux and PHP needing to write to it? I can't seem to find the hang up! Once we hit production, we won't be using the schema, but if there's a simple solution to be able to continue in our current development environment, then that would be ideal! A: After a few hours of facerolling, I finally found what I was missing. The issue was that the credentials supplied couldn't write to the mounted directory as expected. The way I was able to fix this was by editing the mount command as follows: mount -t cifs //shared/directory /mount/target -o rw,username=connectionuser,password=password,uid=48 so, username and password are to be the windows credentials used to connect to the drive, but uid specifies the unique identifier of the local user on the staging server that apache runs as so that it may write to the mounted directory. previously, i had not specified the uid of the local user, so when apache was trying to write to the mounted directory, it was trying to use the windows credentials (that couldn't write on the 'local' drive) hope this is helpful!
{ "pile_set_name": "StackExchange" }
Q: Simple nested for loop problems I am very new to programming and I am trying to create a short macro on google sheets. I want to copy and paste a list of cells a certain number of times based on variables see here. On the first column you have a list of locations and the second column the number of times they should be pasted into a 3rd column (column F). For example i would like to paste A4 fives times into column F4. Then A5 twice into F8 (F4 + 5 rows) and so one until the end of my list. I came up with the below code but it currently copies each locations of my list 5 times on the same rows (F4-F8) then repeat the same process on the following 5 rows, and so on. I think the issue is with the order of the loops but i can't figure it out really. Another problem i have is that It only copies each location 5 times (B1), but i am not sure how to make my variable numShift an array for (B4-B16) so that each locations is copied the correct number of times Any help would be really appreciated ! function myFunction() { var app = SpreadsheetApp; var ss = app.getActiveSpreadsheet() var activeSheet = ss.getActiveSheet() var numShift = activeSheet.getRange(4,2).getValue() for (var k=0;k<65;k=k+5){ for (var indexNumLocation=0;indexNumLocation<15;indexNumLocation++){ for (var indexNumShift=0;indexNumShift<numShift;indexNumShift++) {var locationRange = activeSheet.getRange(4+indexNumLocation,1).getValue(); activeSheet.getRange(4+k+indexNumShift,6).setValue(locationRange); } } } } A: Try this function myFunction() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastRow = sheet.getLastRow(); var data = []; var i, j; // get times count for each row from B4 to last row var times = sheet.getRange(4, 2, lastRow - 4, 1).getValues(); // get the data that needs to be copied for each row from A4 to last row var values = sheet.getRange(4, 1, lastRow - 4, 1).getValues(); // loop over each row for (i = 4; i <= lastRow; i++) { // run loop number of times for that row for (j = 1; j <= times[i]; j++) { // push the value that needs to be copied in a temporary array data.push([values[i][0]]); } } // finally put that array data in sheet starting from F4 sheet.getRange(4, 6, data.length, 1).setValues(data); }
{ "pile_set_name": "StackExchange" }
Q: Oracle SQL String Manipulation My field contains short codes that I want to access, such as C-COR3. The issue is some records have additional information (F and H with numbers). An example is C-COR3 F1.54H19, I only care about C-COR3. Anything after "F" I want to ignore. Code below works, but only if I hard-code the full F1.54H19. I want to use wildcards to abstract this for other occurrences that have F and H info in the field. (Ex C-R3 F0.18H18 -> C-R3 or C-COR3 F0.23H8.5 -> C-COR3), note varying short code string lengths. /* Translates C-COR3 F1.54H19 to C-COR3. */ select distinct SUBSTR(lud_code_short,1,INSTR(lud_code_short, 'F1.54H19')-2) from rep_dba.mytable I've read that SUBSTR does not allow wildcards, but have had no luck trying my hand at REGEXP_INSTR and REGEX_SUBSTR instead. Any help appreciated. A: Assuming that the "code" is always the first continuous sequence of non-space characters (and that there are no leading spaces - if there are, that's easy to handle), you could do something like this. Note the str || ' ' in the call to instr() - that takes care of the case when the input string has no spaces in it to begin with. Also notice the last input - since there are no spaces anywhere, the output is the same as the input. (Showing that if the "code" is not always separated from the "additional information" by at least one space, the solution would not work.) with test_data (str) as ( select 'C-COR3 F14H2.5' from dual union all select 'C-AB3' from dual union all select null from dual union all select 'C-AB2F14H2.5' from dual ) select str, substr(str, 1, instr(str || ' ', ' ') - 1) as code from test_data ; STR CODE -------------- -------------- C-COR3 F14H2.5 C-COR3 C-AB3 C-AB3 C-AB2F14H2.5 C-AB2F14H2.5
{ "pile_set_name": "StackExchange" }
Q: What is the cataclysm that befalls Earth in Wool? In the Wool series; specifically, Wool 6: First Shift, it is said that the world ends with atomic bombs. The landscape of the world definitely jives with this. However, whenever someone goes out into the world, their protective suit is immediately attacked by something in the air and slowly disintegrates. First Shift makes mention of nano-technology or poison, but I don't recall if that was ever confirmed or not. Does the series reveal what is the villain in the air? A: The nanos wipe out humans in a controlled, timed, DNA-based attack. The bombs served three purposes (and there were only three bombs): They ushered the survivors into the silos; they provided the initial (and fuzzy) legends about the destruction of all things; and they were the trauma that allowed the subsequent regimen of medication to divide the forgotten past from their new future.
{ "pile_set_name": "StackExchange" }
Q: Paypal Adaptive Payments Allowing Third Party to Act on Your Behalf I'm reading the adaptive paypals API ebook and it says on page 21, that : "if you allow a third party to paypal to execute an application on your behalf the third party becomes the API caller because the third party is now calling the Adaptive Payments API. The third party must also have permission from Paypal to use the advanced service. For example if an application supports chained payments both you anf the third party must have permission to use the service" Does this mean if I have an application where a user of the site logs in and sends me $100 (as an approved user of chain payments), say only $50 of the money goes to me and another $25 goes to y, and the other $25 goes back to the ORIGINAL sender... can they ONLY accept this if they have an approved chain payment account?? or does only the primary receiver need to have a chain payment approved account? Thanks A: This section is likely referring to third-party API authentication. E.g. if you're setting a USER, PWD and SIGNATURE but also passing a SUBJECT in order to force the API call to actually be called on behalf of another third party. This wouldn't be strictly something to do with a chained payment scenario, because the SUBJECT can again be different from the primary receiver. For example: METHOD=Pay USER=myapi_api1.test.com PWD=xxxxxx SIGNATURE=xxxxxxxx X-APPLICATION-ID=APP-XXXXXXXXX // The application ID as owned by yourstore@yourdomain.com SUBJECT=yourstore@yourdomain.com // Call the 'Pay' API on behalf of yourstore@yourdomain.com, but use my API credentials (yourstore@yourdomain.com must have granted myapi_api1.test.com access to do this) PRIMARYRECEIVER=blah@anotherdomain.com // This receiver only has to be able to receive money Note: This does not constitute an actual API call you would send. I don't happen to have an Adaptive Payments API call at hand to make a working example at the moment.
{ "pile_set_name": "StackExchange" }
Q: When reviewing, what to do when previous reviewer has already posted a comment? On a recent review of a first post the previous reviewer, a moderator, had already posted a comment that covered the issue. The post was asked on the wrong SE site, but their comment covered this. I decided to flag for moderator intervention because the 'No action necessary' pop-up for this action says "This question seems to be valid", which it isn't on the site it was posted on. But, a moderator was already aware as they commented so is flagging it just making work for others, or is this correct action? I have done some looking around on the Metas but can't find an answer to this I don't think? What are the review queues, and how do they work? How does the new user question review process work? A: If you don't want to flag it, you can always upvote the previous reviewer's comment and then click on "I'm done".
{ "pile_set_name": "StackExchange" }
Q: How do you change a color of an image entirely when hovered in tag element? I have this example code that hovers an image to change the background color. How do you fill the entire image with color when hovered? In my code snippet, it only fills the background color of an a tag element but not the image. Here's an image to further clarify my question. How do achieve this using the hover effect in tag element. a img:hover { background-color: purple; } a:hover { background-color: yellow; } <!DOCTYPE html> <html> <head> </head> <body> <!-- Hovered with image no text --> <a href="https://www.w3schools.com"><img src="cart.png"></a> <!-- Hovered without image just text --> <a href="http://www.wikipedia.org">Change color text</a> </p> </body> </html> A: I have found another method to change the background image. I suppose to have two images so when hovered it will change the image. Thanks for the info @Jaromanda X #my-img:hover { content: url('images/pinkcart.png'); } <!DOCTYPE html> <html> <head> </head> <body> <img id="my-img" src="images/redcarticon.png"/> </p> </body> </html> And thank you also for helping me everyone.
{ "pile_set_name": "StackExchange" }
Q: ARM clock speed on raspberry pi Running bare-metal (no operating system, no Linux) The specs implies the ARM can/does run 700MHz, the sys clock matches the manual and appears to be running at 250MHz. Simple tests on the ARM imply that it is doing the same, for example with the instruction cache on test: subs r0,r0,#1 bne test And vary the number of subs instructions to dominate over the branch, it is in the ball park of 250MHz but a long way away from 700MHz. I there a phy setting that I am not seeing in the datasheet for multiplying the ARM clock? EDIT: Maybe my assumptions are flawed... .globl ARMTEST0 ARMTEST0: subs r0,r0,#1 bne ARMTEST0 bx lr .globl ARMTEST1 ARMTEST1: subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 bne ARMTEST1 bx lr .globl ARMTEST2 ARMTEST2: subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 subs r0,r0,#1 bne ARMTEST2 bx lr .globl ARMTEST3 ARMTEST3: subs r1,r0,#1 subs r2,r1,#1 subs r3,r2,#1 subs r0,r3,#1 subs r1,r0,#1 subs r2,r1,#1 subs r3,r2,#1 subs r0,r3,#1 subs r1,r0,#1 subs r2,r1,#1 subs r3,r2,#1 subs r0,r3,#1 subs r1,r0,#1 subs r2,r1,#1 subs r3,r2,#1 subs r0,r3,#1 bne ARMTEST3 bx lr System timer ticks in hex per function (250Mhz system timer verified against stopwatch, etc). 02DB6DF7 ARMTEST0 02DB6E1C ARMTEST0 00AB6E2A ARMTEST1 00836E46 ARMTEST2 00836E2A ARMTEST3 Which gives: ARMTEST0 0x01000000 subs instructions 0x01000000 bne instructions 0x02000000 instructions 1.43 clocks per instruction. 175Mips. ARMTEST1 0x01000000 sub instructions 0x00200000 bne instructions 0x01200000 instructions 1.68 instructions per clock. 420Mips ARMTEST2 0x01000000 sub instructions 0x00100000 bne instructions 0x01100000 instructions 2.07 instructions per clock. 517Mips ARMTEST3 0x01000000 sub instructions 0x00100000 bne instructions 0x01100000 instructions 2.07 instructions per clock. 517Mips The ARM11 is super-scalar more than one instruction per clock is not unexpected. I would expect more though. Using only register 0 might mess with the pipe as you have to wait for one result of one instruction before executing the next. I was expecting to see a difference between test 2 and 3, perhaps another bad assumption. Maybe its really 500Mhz not 700? There is one line in the linux sources that mentions a 500000000 clock. static struct clk osc_clk = { #ifdef CONFIG_ARCH_BCM2708_CHIPIT .rate = 27000000, #else .rate = 500000000, /* ARM clock is set from the VideoCore booter */ #endif }; /* warning - the USB needs a clock > 34MHz */ #ifdef CONFIG_MMC_BCM2708 static struct clk sdhost_clk = { #ifdef CONFIG_ARCH_BCM2708_CHIPIT .rate = 4000000, /* 4MHz */ #else .rate = 250000000, /* 250MHz */ #endif }; #endif Maybe what I think I have measured as 250Mhz is 270 and the ARM is at 500MHz? EDIT2...DOH That wasnt a great pipeline improvement was it, this is better: .globl ARMTEST3 ARMTEST3: subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop subs r0,r0,#1 nop nop nop nop nop nop nop nop bne ARMTEST3 bx lr ARMTEST3 0x01000000 sub instructions 0x08000000 nop instructions 0x00100000 bne instructions 0x09100000 instructions 037000D7 system clocks 2.64 instructions per clock. 659Mips I failed to get config.txt to work at first, then re-build a linux sd card, booted it to find that the /boot/ directory is in fact the fat partition that contains the gpu boot files and the kernel.img arm boot file. So NOT in a boot/ dir but in that same dir with the .bin's and .elf and .img file create config.txt and put arm_freq=something, the gpu bootloader then makes the modification to the pll multiplier so that when the arm starts it is at that speed. I still expect more than 700 million instructions per second and am not seeing that, will need to keep trying I guess. A: Might be worth looking at the boot loader provided with the Arch Linux reference distribution from the Raspberry Pi organisation's download pages. I have no idea whether it's a working option, but its config.txt includes the line #arm_freq=800 There are also reports of people having overclocked the Pi - so information about initialising the clock is certainly out there, somewhere.
{ "pile_set_name": "StackExchange" }
Q: Adding result values from two different arrays together Please take a look at my sample Fiddle I have a running total for credits selected for Transfer. As you select the number of credits, the running total adds up. It's designed to stop at 6 credits per section. This part works fine. What I'm trying to do is add two different result sets together... Communications + Humanities = Total Credits ...and have it display in the Total Credits: field. This is where I'm getting lost. What I can't figure out is how to add two different fields together... This is what I'm using to get that final result... (the 72 is so that the count will stop at 72 transfer credits maximum) JavaScript... $(function($) { $('#total_Credits select').change(function() { var sum = 0; $('#total_Credits select').each(function(idx, elm) { sum += parseFloat(elm.value, 10); }); $('#total_Credits').html(Math.min(sum,72).toFixed(2)) }); }); HTML... Total Credits: &nbsp;&nbsp;<span id="total_Credits" style="color: red; font-weight:bold; font-size: 2em;"></span> A: You don't need a different function for each group of selects. Instead, you can just use $(function($) { var sum = function($els, prop) { var s = 0; $els.each(function(idx, elm) { s += parseFloat(elm[prop], 10) || 0; }); return s; }; $('.select-wrapper select').change(function() { var $wrap = $(this).closest('.select-wrapper'); $wrap.find('.sum').html(Math.min(sum($wrap.find('select'), 'value'),6).toFixed(2)); $('.total-sum').html(Math.min(sum($('.sum'), 'innerHTML'),72).toFixed(2)); }); }); Demo Note I have modified a bit the html in order to make it work, and I have fixed problems like duplicate ids and nonsense <br>.
{ "pile_set_name": "StackExchange" }
Q: PHP cleanup "&$" I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc. I have tried: html2text command line html_entity_decode + ENT_QUOTES | ENT_HTML401 UTF-8 html_entity_decode(htmlentities($str)) strip_tags trim It did help a lot for cleaning up other things, but those &\#8217; &#8220; don't get fixed. How can I convert them correctly? A: Did you tried "htmlspecialchars_decode" <?php $str = "<p>this -&gt; &quot;</p>\n"; echo htmlspecialchars_decode($str); // note that here the quotes aren't converted echo htmlspecialchars_decode($str, ENT_NOQUOTES); ?> The above example will output: <p>this -> "</p> <p>this -> &quot;</p>
{ "pile_set_name": "StackExchange" }
Q: Bash set +x without it being printed Does anyone know if we can say set +x in bash without it being printed: set -x command set +x traces + command + set +x but it should just print + command Bash is Version 4.1.10(4). This is bugging me for some time now - output is cluttered with useless set +x lines, making the trace facility not as useful as it could be. A: I had the same problem, and I was able to find a solution that doesn't use a subshell: set -x command { set +x; } 2>/dev/null A: You can use a subshell. Upon exiting the subshell, the setting to x will be lost: ( set -x ; command ) A: I hacked up a solution to this just recently when I became annoyed with it: shopt -s expand_aliases _xtrace() { case $1 in on) set -x ;; off) set +x ;; esac } alias xtrace='{ _xtrace $(cat); } 2>/dev/null <<<' This allows you to enable and disable xtrace as in the following, where I'm logging how the arguments are assigned to variables: xtrace on ARG1=$1 ARG2=$2 xtrace off And you get output that looks like: $ ./script.sh one two + ARG1=one + ARG2=two
{ "pile_set_name": "StackExchange" }
Q: Fontsize for text vs. math Disclaimer: I am new to Latex, I apologize for the lack of specific and correct vocabulary to describe my question. I am building an equation sheet and have a question about font sizes. I would like to specify the font size for the text to be smaller than the font size for the equations. I know I can do this by brute force (1st table), but that seems cumbersome and inelegant. When I set the font size for the whole table the size of the equations also change (2nd table). Is there any way to achieve the effects of the 1st table without defining the size of every text string? Thank you! \documentclass[table,9pt]{extarticle} \usepackage[a4paper, landscape]{geometry} \everymath{\displaystyle} \begin{document} \begin{tabular}{lll} $\frac{N(x)}{(ax+b)(cx+d)}$ & \small{Linear Factors} & $\frac{A}{ax+b}+\frac{B}{cx+d}$\\ [3.5ex] $\frac{N(x)}{(ax+b)^2}$ & \small{Repeated} & $\frac{A}{ax+b}+\frac{B}{(ax+b)^2}$\\[10ex] \end{tabular} \small{ \begin{tabular}{lll} $\frac{N(x)}{(ax+b)(cx+d)}$ & Linear Factors & $\frac{A}{ax+b}+\frac{B}{cx+d}$ \\ [3.5ex] $\frac{N(x)}{(ax+b)^2}$ & Repeated & $\frac{A}{ax+b}+\frac{B}{(ax+b)^2}$\\ \end{tabular} } \end{document} A: Just one approach: Make the column use smaller text (\tiny here for the sake of showing a clear difference). And please note: Use font size commands within the group they should resize. \documentclass[table,9pt]{extarticle} \usepackage[a4paper, landscape]{geometry} \everymath{\displaystyle} \usepackage{array} \begin{document} \begin{tabular}{lll} $\frac{N(x)}{(ax+b)(cx+d)}$ & {\small Linear Factors} & $\frac{A}{ax+b}+\frac{B}{cx+d}$\\ [3.5ex] $\frac{N(x)}{(ax+b)^2}$ & {\small Repeated} & $\frac{A}{ax+b}+\frac{B}{(ax+b)^2}$\\[10ex] \end{tabular} \begin{tabular}{l>{\tiny}ll} $\frac{N(x)}{(ax+b)(cx+d)}$ & Linear Factors & $\frac{A}{ax+b}+\frac{B}{cx+d}$ \\ [3.5ex] $\frac{N(x)}{(ax+b)^2}$ & Repeated & $\frac{A}{ax+b}+\frac{B}{(ax+b)^2}$\\ \end{tabular} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Unity Network No sound on other clients I'm trying to play sound on other clients, so they could hear gunfire in the distance, but sound only works for the shooter. Here's my code: void Update() { *** if (Input.GetButton("Fire1")) { CmdFireWeapon(this.gameObject); } *** } [Command] void CmdFireWeapon(GameObject plr) { *** if (!plr.GetComponent<AudioSource>().isPlaying) RpcPlayWeapon(plr); *** } [ClientRpc] void RpcPlayWeapon(GameObject plr) { plr.GetComponent<AudioSource>().Play(); } I'm using 3D Spatial Blend, but there's no sound even with volume == 1 across all distance. Also tried with and without if(isPlaying) - no progress. What am I doing wrong? A: I think I figured it out. Player Prefab on other clients spawned without clip (it is loaded in its script). So I needed to load it first then play it. And I need to keep loading, because clip changes with different weapon. [ClientRpc] void RpcPlayWeapon(GameObject plr) { plr.GetComponent<AudioSource>().clip = plr.GetComponent<PlrController>().curWeapon.shotAudio; plr.GetComponent<AudioSource>().Play(); }
{ "pile_set_name": "StackExchange" }
Q: Bootstrap Tapdrop jQuery in angular.js controller I saw Bootstrap Tapdrop library and it is perfect for dropdown in my responsive tabs. My app works with angular.js, but add the bootstrap-tapdrop.js in my index.html . I want to call: $('.nav-tabs').tabdrop({align:'left'}); into my angularjs app but nothing works. However, when I call this from chrome console works ok. How can I add this sentence jQuery angular.js my driver? is there anyway? or..how can I use this library from angular.js? I have sought similar things in angular but can not find. Thanks A: You have to create a directive in order to use jQuery plugins or whenever you want to attach client side behavior to elements using jQuery or any third party plugins. Try something like this. angular.module('main') .directive('my-tabs-directive', [ function ($timeout, $sce) { return { restrict: 'E', link: function (scope, element, attrs) { //Write any plugin logic here element.tabdrop({align: 'left'}); }, templateUrl: 'passYourTemplateUrl'//You can also use inline template }; } ]); You can understand more about angularJs directive here https://docs.angularjs.org/guide/directive
{ "pile_set_name": "StackExchange" }
Q: Excel Worksheet_SelectionChange event not firing at all? (on both Office 2013 & 2016) I've been having a heck of a time accomplishing what I thought would be an incredibly simple test. All I am trying to achieve is to pop up a MsgBox when a user selects a new cell or changes the contents of a cell. I've been at this for about 6 hours and so far have zero success! I have identical behavior with Office 2016 (Windows 10) and with Office 2013 (Windows 7). Here are my method(s): Create a new macro-enabled workbook. Record a new macro in the workbook. Stop the recording. Open VBA. Open the code for "Module 1" and replace the undesired code with the code below. Save the file. File -> Options -> Trust Center -> Trust Center Settings -> Macro Settings -> "Trust access to the VBA project object model" is selected. Save the file. I also have ensured Application.EnableEvents = True I am expecting to be able to click on various cells, or edit cells, and received a MsgBox whenever the event occurs. Here is my code: Option Explicit Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) MsgBox "changed!" End Private Sub Worksheet_SelectionChange(ByVal Target As Range) MsgBox "selected!" End Sub Public Sub Just_In_Case() Application.EnableEvents = True End Sub What am I missing? Is there a security setting preventing this action event? I have the same behavior online at work as I do offline at home. Thank you in advance for your help! :) PS Here is the screenshot of my VBA environment, if relevant: https://i.stack.imgur.com/yXkMK.png A: That Workbook_SheetChange code needs to be in the ThisWorkbook code module, not in a regular module. EDIT: and the Worksheet_SelectionChange goes in the Worksheet code module http://www.cpearson.com/excel/events.aspx
{ "pile_set_name": "StackExchange" }
Q: How to undo a Time Machine restore? I just attempted to restore a folder from TimeMachine. I was expecting that TM would ask me where to put the restored folder (as it has done in the past, IIRC), but this time it didn't, and instead overwrote the folder1. This is definitely not what I wanted. Is it possible to undo the TM restore? 1Bizarrely enough, TM noticed that one subfolder already existed, and asked whether it should overwrite it, keep the latest version, or keep both. What's bizarre about this is that only one subfolder was selected for such special treatment, out of dozens of subfolders for which it would have been equally applicable. A: Two things might work in your case: Power off the Mac and hope an unerase utility can recover the files before they get overwritten (assuming the restore didn't write over the existing files on disk). Delete the folder and try again from a different Time Machine snapshot.
{ "pile_set_name": "StackExchange" }