qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
50,479,400
I'm trying to show my users notifications through my service that checks my database when an item is at it's set date it should send a notification. My problem is that when the date comes it doesn't send a notification. ``` databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems"); childEventListener = databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue(); if (value != null) { String name = value.get("Name"); String date = value.get("Date"); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US); try { dateFormat = sdf.parse(date); } catch (ParseException e) { Log.wtf("FailedtoChangeDate", "Fail"); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); if (dateFormat.equals(tomorrow)) { GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if (account != null) { String firstname = account.getGivenName(); mContentTitle = "Your " + name + " is about to be expired!"; mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date; } Intent openApp = new Intent(getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT); notification = new NotificationCompat.Builder(getApplicationContext(), "Default") .setSmallIcon(R.drawable.ic_restaurant_black_24dp) .setContentTitle(mContentTitle) .setContentText(mContentText) .setLights(Color.GREEN, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText)) .setContentIntent(contentIntent) .setAutoCancel(true); createNotificationChannel(getApplicationContext()); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext()); notificationManager.notify(uniqueID, notification.build()); } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); ``` I'm sure my notification works because when I remove `if (dateFormat.equals(tomorrow))` it sends a notifciation and works perfectly. This is also a service class and not a normal activity so maybe that has something to do with it.
2018/05/23
[ "https://Stackoverflow.com/questions/50479400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554176/" ]
Implement the `textFieldDidBeginEditing` text field delegate method and set the text field's text if it doesn't already have a value. ``` func textFieldDidBeginEditing(_ textField: UITextField) { if textField.text!.isEmpty { // set the text as needed } } ```
253,161
In the thread [Set theories without "junk" theorems?](https://mathoverflow.net/questions/90820/set-theories-without-junk-theorems/90945#90945), Blass describes the theory T in which mathematicians generally reason as follows: > > Mathematicians generally reason in a theory T which (up to possible minor variations between individual mathematicians) can be described as follows. It is a many-sorted first-order theory. The sorts include numbers (natural, real, complex), sets, ordered pairs and other tuples, functions, manifolds, projective spaces, Hilbert spaces, and whatnot. There are axioms asserting the basic properties of these and the relations between them. For example, there are axioms saying that the real numbers form a complete ordered field, that any formula determines the set of those reals that satisfy it (and similarly with other sorts in place of the reals), that two tuples are equal iff they have the same length and equal components in all positions, etc. > > > There are no axioms that attempt to reduce one sort to another. In particular, nothing says, for example, that natural numbers or real numbers are sets of any kind. (Different mathematicians may disagree as to whether, say, the real numbers are a subset of the complex ones or whether they are a separate sort with a canonical embedding into the complex numbers. Such issues will not affect the general idea that I'm trying to explain.) So mathematicians usually do not say that the reals are Dedekind cuts (or any other kind of sets), unless they're teaching a course in foundations and therefore feel compelled (by outside forces?) to say such things. > > > Question: *If set theorists just want to do set theory and not worry about foundations (and encodings of mathematical objects as sets), do they also work in the theory T?* Or are they always regarding every object as a set? Also, do I understand it correctly that it's hard to actually formalize the syntax of the theory T, because of the many types and connotations of natural language involved? But then, what's "first-order" about T, if T is communicated through natural language?
2016/10/26
[ "https://mathoverflow.net/questions/253161", "https://mathoverflow.net", "https://mathoverflow.net/users/100315/" ]
Caveat number 1: strictly speaking, no one actually works in the theory $T$, just as no one actually works in the theory $\mathsf{ZFC}$. Mathematicians work by means of carefully used natural language and not within a formal system. Formal systems are formulated as approximations that try to model what mathematicians actually do while at work. Now to address the question, with the above caveat in mind, are we always regarding every object as a set? Not necessarily always, just sometimes. The point is that $\mathsf{ZFC}$ and $T$ are bi-interpretable, so you can switch between both viewpoints at will without that changing the stuff that you can prove (and even better: both $T$ and $\mathsf{ZFC}$ are just approximations to what we actually do, so we can just do math as usual, and not worry about these nuances, and whatever it is that we're doing can in theory be translated to the formal system of your choice).
1,737,108
I am stuck with WIN32 ( no .NET or anything managed )
2009/11/15
[ "https://Stackoverflow.com/questions/1737108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11100/" ]
WM\_CTLCOLORSTATIC was the correct way to control the color of the group box title. However, it no longer works: If your application uses a manifest to include the version 6 comctl library, the Groupbox control no longer sends the `WM_CTLCOLORSTATIC` to its parent to get a brush. If your dialog controls look ugly, square and grey - like the windows 95 controls, then you don't have xp styles enabled and you can control the color of group boxes. But thats a terrible sacrifice to make! :P Next, most of the standard controls send `WM_CTLCOLORxxx` messages to their parent (the dialog) to control their painting. The only way to identify the controls is to look up their control IDs - which is why assigning controls a identifier that indicates that that control needs a specific color or font is a good idea. i.e. Don't use `IDC_STATIC` for controls that need red text. Set them to `IDC_DRAWRED` or some made up id. Dont use `GetDlgItem(hwndDlg,IDC_ID) == hwndCtl` to test if the `WM_CTLCOLOR` message is for the correct control: GetDlgItem will simply return the handle of the first control on the dialog with the specific Id, which means only one control will be painted. ``` case WM_CTLCOLORSTATIC: if(GetWindowLong( (HWND)lParam, GWL_ID) == IDC_RED) return MakeControlRed( (HDC)wParam ); ``` You always\* need to return a HBRUSH from a WM\_CTLCOLORxxx message - even if you really just want to 'tamper' with the HDC being passed in. If you don't return a valid brush from your dialog proc then the dialogs window procedure will think you didn't handle the message at all and pass it on to DefWindowProc - which will reset any changes to the HDC you made. Instead of creating brushes, the system has a cache of brushes on standby to draw standard ui elements: [`GetSysColorBrush`](http://msdn.microsoft.com/en-us/library/dd144927(VS.85).aspx) Of course, you DON'T always need to return an HBRUSH. IF you have the xp theme style enabled in your app, you are sometimes allowed to return null :- because xp theme dialogs have differently colored backgrounds (especially on tab controls) returning a syscolor brush would result in ugly grey boxes on a lighter background :- in those specific cases the dialog manager will allow you to return null and NOT reset your changes in the DC.
16,402,483
I have an iPhone 4S (running iOS 5.1) & an iPhone 5 (running iOS 6.1). I noticed that when i try to open the `cocos2D` game, on the iPhone 4S running 5.1, the game is able to open perfectly fine in landscape mode. However, when I try to open the same `cocos2D` game on my iPhone 5 running 6.1, the game is opened in portrait mode. Is there any way that I can rotate the `cocos2D` game into landscape mode in the iPhone 5 running iOS 6.1. Some extra notes: * The game is being pushed from a view controller in my test app. * Since I am pushing the game from an iOS app, I have to support portrait mode in the "Support Interface Orientations" section. (If I was just doing the game, I would just easily set the Support Interface Orientation to landscape left/landscape right) I have also tried different methods such as for iOS 6 such as: ``` -(NSUInteger)supportedInterfaceOrientations -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation -(BOOL)shouldAutorotate ``` But it has given me different results when I tried those methods. Ideally, I would like the app to be locked in the Portrait mode and game to be locked into Landscape mode. So, I'm wondering if it is possible to have an app that remains locked in the portrait mode and the game locked in landscape mode (for both iOS 5 & iOS 6) when opened? Here's a link to a sample project I was working on: <http://www.4shared.com/zip/yEAA1D_N/MyNinjaGame.html>
2013/05/06
[ "https://Stackoverflow.com/questions/16402483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/783188/" ]
I just set the orientation modes in Xcode ("Summary" tab on your target) to landscape left and right. Then for every UIViewController I added this: ``` // Autorotation iOS5 + iOS6 - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation { return UIInterfaceOrientationIsLandscape(toInterfaceOrientation); } ```
44,680,971
I added a redirection link to the reference numbers in a grid that link back to receipts. I followed the instructions given in T200 to perform the task, except I made the page that opens a popup instead of a new tab. It works for the first reference number I click, but after that it doesn't change the record. Instead the popup displays the record for the first reference number I clicked. Here is my code: ``` protected void RefNbrReceipt() { INRegister row = Receipts.Current; INReceiptEntry graph = PXGraph.CreateInstance<INReceiptEntry>(); graph.receipt.Current = graph.receipt.Search<INRegister.refNbr>(row.RefNbr); if (graph.receipt.Current != null) { throw new PXPopupRedirectException(graph, "Receipt Details"); } } ``` I checked and made sure that the row updates to the selected value (I do have SyncPosition = true on the grid) as well as after the Search that graph.receipt.Current.RefNbr = row.RefNbr. All of the objects in the code when debugging and stepping through it are set to the correct values they should be. Even though these values are showing correctly, when the popup appears, it still has the incorrect record (the first record fetched).
2017/06/21
[ "https://Stackoverflow.com/questions/44680971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7085476/" ]
Pass the index label to `loc` and the col of interest: ``` In[198]: df.loc[diff_row.idxmax(), 'City'] Out[198]: 'Dallas' ```
4,236,395
So my question is: if we have a function f(x, y), how do we know if the curve f(x, y)=0 encloses a finite region or not. As an example, the curve $x^2+y^2-1=0$ encloses a finite region, while the curve $x^2-y^2-1=0$ doesn't.
2021/08/30
[ "https://math.stackexchange.com/questions/4236395", "https://math.stackexchange.com", "https://math.stackexchange.com/users/494803/" ]
Consider the following result from geometric analysis due to [Matthew Grayson (1987)](https://en.wikipedia.org/wiki/Mean_curvature_flow#Convergence_theorems): > > Let $g:\mathbb{S}^1\to\mathbb{R}^2$ be a smooth embedding, then the mean curvature flow with initial data $g$ eventually consists exclusively of embeddings with strictly positive curvature. > > > Mean curvature flow is the process of distorting an embedded smooth curve (or more generally embedded smooth manifold) at every point in the direction of its mean curvature vector. What this says is that if $g$ defines a curve defining a bounded region, then that curve will deform into a circle. Moreover this circle will shrink to a single point in finite time. [![enter image description here](https://i.stack.imgur.com/m7vtQ.png)](https://i.stack.imgur.com/m7vtQ.png) Image: [David Eppstein (CC0)](https://en.wikipedia.org/wiki/Curve-shortening_flow#/media/File:Convex_curve_shortening.png) This if you have a function $f:\mathbb{R}^2\to\mathbb{R}^2$ whose level set is a disjoint union of smoothly embedded curves, you can independently perform mean curvature flow on each component of $f(x,y)=0$. If each component bounds a finite region, then in finite time this will produce a set of points. Thus the set of such functions $f$ is recursively enumerable. (*Remark:* in fact it is the case that if two components of $f(x,y)=0$ are nested embeddings of $\mathbb{S}^1$, then performing mean curvature flow on both simultaneously, the two curves will not intersect at any point (until after the inner curve has shrunk to a point). This doesn't completely answer your question, but hopefully it is somewhat useful.
6,393,438
So I hoped to figure out the code that would finish this: ``` public List<List<Integer>> create4(List<Integer> dice) { //unknown code return listOf4s; } ``` So dice would always be a List of 5 Integers, from the 5 Integers I would like to create a List every possible permutation using only 4 numbers. I hope I have made this clear enough. I have searched around but have not quite seen anything I could use. Any help would be great!
2011/06/18
[ "https://Stackoverflow.com/questions/6393438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/679413/" ]
I tend to like shorter code ;) ``` public List<List<Integer>> create4(List<Integer> dice) { List<List<Integer>> listOf4s = new ArrayList<List<Integer>>(); for(Integer num : dice) { List<Integer> dice2 = new ArrayList<Integer>(dice); dices2.remove(num); listOf4s.add(dices2); } return listOf4s; } ```
301,927
So, I'm playing this video game and I came across this sentence that uses "stem from" in an alien way to me. "Their zeal is admirable, but their ideas impractical for a society that must maintain secrecy and organization **to stem** its own genocide **from** coming about." I know that "stem from" means Originate from:(TFD source below) stem from (something) To come, result, or develop from something else. My fear of the water stems from the time my brother nearly drowned me when we were playing in our cousin's pool as kids. But this usage is different. It is as if it means "to prevent". There is one definition on TFD that sort of fits but it would have to be an abbreviated version of it. (TFD def) **stem the tide or stem the flow** COMMON If you stem the tide or stem the flow of something bad which is happening to a large degree, you start to control and stop it. *The authorities seem powerless to stem the rising tide of violence. The cut in interest rates has done nothing to stem the flow of job losses.* is it possible it is that meaning?
2021/11/10
[ "https://ell.stackexchange.com/questions/301927", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/140013/" ]
Both are correct. But how? These sentences both use "unreal" grammar. The reason they're both correct will make more sense if we change them back to real sentences with the same meaning: > > (1) We **have been** able to come here because it isn't raining. > > > (2) We **were** able to come here because it wasn't raining. > > > Sentence (1) refers to the **present** situation of now being at the top of the mountain, and the **present** fact that it's not raining. Sentence (2) refers to the **past** situation of arriving at the top of the mountain with the **past** reason why. So it's two perspectives on the same thing: either (1) *now being* at the top of the mountain, or (2) *having arrived earlier*. I've highlighted the two main verbs. You'll notice they don't have the same tense, even though the original two sentences have the exact same structure\*. This is because when we shift present perfect or simple past into "unreal" grammar, *the result is the same*: *"could have" + past participle*. \*I've also replaced "couldn't" with "be able to" for grammar reasons which are unrelated to this question.
3,533,757
So, that's the problem. I tried factoring the quadratic equation to get something like $2x-y$ but it doesn't work. Dividing by $y^2$ won't work because the right side is $9$, not $0$. The last idea I have is to say that $2x-y=t => y=2x-t$ and replace $y$ in the quadratic equation with $2x-t$ to get a function but then, I get confused.
2020/02/04
[ "https://math.stackexchange.com/questions/3533757", "https://math.stackexchange.com", "https://math.stackexchange.com/users/502482/" ]
$$2x^2-4xy+6y^2=9$$ and let $$k=2x-y\Rightarrow y=2x-k$$ $2x^2-4x(2x-k)+6(2x-k)^2=9$ $2x^2-8x^2+4xk+6(4x^2+k^2-4xk)=9$ $-6x^2+4xk+24x^2+6k^2-24xk-9=0$ $$18x^2-20kx+6k^2-9=0$$ For real roots, Discriminant $\geq 0$ $$400k^2-4\cdot 18(6k^2-9)\geq 0$$ $$100k^2-108k^2+162\geq 0$$ $$-8k^2+162\geq 0\Rightarrow k^2-\frac{81}{4}\leq 0$$ $$-\frac{9}{2}\leq k\leq \frac{9}{2}$$
6,822,131
Because I am not familiar with ADO under the hood, I was wonder which of the two methods of finding a record generally yields quicker results using VB6. 1. Use a 'select' statement using 'where' as a qualifier. If the recordset count yields zero, the record was not found. 2. Select all records iterating through records with a client-side cursor until record is found, or not at all. The recordset is in the range of 10,000 records and will grow. Also, I am open to anything that will yield shorter search times other than what was mentioned.
2011/07/25
[ "https://Stackoverflow.com/questions/6822131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348917/" ]
``` SELECT count(*) FROM foo WHERE some_column='some value' ``` If the result is greater than 0 the record satisfying your condition was found in the database. It is unlikely you would get any faster than this. Proper indexes on the columns you are using in the `WHERE` clause could considerably improve performance.
20,184,852
I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help! ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; for (int i = 1; i<=10; i--) { r = r * i; } FileWriter write = new FileWriter(fac); write.write(""+r); write.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` --- Here's how I solved it thanks to everybody in here, I hope you like this simple method: ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("\n----------------------------------"); System.out.println("The file has been created."); System.out.println("------------------------------------"); int r = 1; FileWriter wr = new FileWriter(fac); for (int i = 1; i<=10; i++) { r = r * i; wr.write(r+System.getProperty( "line.separator" )); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20184852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029988/" ]
the reason any way is that ``` for (int i = 1; i<=10; i--) ``` runs to infinity since 1 cannot be reduced to 10 it should be ``` for (int i = 1; i<=10; i++) ``` and change data type to long as well
16,469,619
I'm new to WCF. I've created a basic service and engineer tested it with the debugger and WCFTestClient. I've never written my own WCF client. Now I need to build unit tests for the service. My classes: ``` IXService CXService CServiceLauncher ``` (Yes, I know the C prefix does not meet current standards, but it is required by my client's standards.) My service functionality can be tested directly against `XService`, but I need to test `CServiceLauncher` as well. All I want to do is connect to a URI and discover if there is a service running there and what methods it offers. Other questions I read: * [AddressAccessDeniedException "Your process does not have access rights to this namespace" when Unit testing WCF service](https://stackoverflow.com/questions/14563557/unit-test-wcf-service) - starts service host in unit test * [WCF Unit Test](https://stackoverflow.com/questions/152338/wcf-unit-test) - recommends hosting the service in unit test, makes a vague reference to connecting to service via HTTP * [WCF MSMQ Unit testing](https://stackoverflow.com/questions/2691066/wcf-msmq-unit-testing) - references MSMQ, which is more detailed than I need * [Unit test WCF method](https://stackoverflow.com/questions/7929882/unit-test-wcf-method) - I never knew I could auto generate tests, but the system isn't smart enough to know what to assert. Test outline: ``` public void StartUiTest() { Uri baseAddress = new Uri("http://localhost:8080/MyService"); string soapAddress = "soap"; IUserInterface target = new CServiceLauncher(baseAddress, soapAddress); try { Assert.AreEqual(true, target.StartUi()); /// @todo Assert.IsTrue(serviceIsRunning); /// @todo Assert.IsTrue(service.ExposedMethods.Count() > 4); Assert.Inconclusive("This tells us nothing about the service"); } finally { target.StopUi(); } } ```
2013/05/09
[ "https://Stackoverflow.com/questions/16469619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091951/" ]
I just needed to build a simple client. Reference: <http://webbeyond.blogspot.com/2012/11/wcf-simple-wcf-client-example.html> 1. Add Service Reference to test project 2. Add to test file: `using System.ServiceModel;` `using MyTests.ServiceReferenceNamespace;` Code inside try is now: ``` Assert.AreEqual(true, target.StartUi()); XServiceClient client = new XServiceClient(); client.GetSessionID(); Assert.AreEqual(CommunicationState.Opened, client.State, "Wrong communication state after first call"); ```
12,409,813
Ideally I want to be able to write something like: ``` function a( b ) { b.defaultVal( 1 ); return b; } ``` The intention of this is that if `b` is any defined value, `b` will remain as that value; but if `b` is undefined, then `b` will be set to the value specified in the parameter of `defaultVal()`, in this case `1`. Is this even possible? Ive been toying about with something like this: ``` String.prototype.defaultVal=function(valOnUndefined){ if(typeof this==='undefined'){ return valOnUndefined; }else{ return this; } }; ``` But I'm not having any success applying this kind of logic to *any* variable, particularly undefined variables. Does anyone have any thoughts on this? Can it be done? Or am I barking up the wrong tree?
2012/09/13
[ "https://Stackoverflow.com/questions/12409813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037617/" ]
Well the most important thing to learn here is if a variable is `undefined` you, by default, do not have any methods available on it. So you need to use a method that can operate on the variable, but is not a member/method *of* that variable. Try something like: ``` function defaultValue(myVar, defaultVal){ if(typeof myVar === "undefined") myVar = defaultVal; return myVar; } ``` What you're trying to do is the equivalent of this: ``` undefined.prototype.defaultValue = function(val) { } ``` ...Which for obvious reasons, doesn't work.
302,472
where i put file of programatically create product ``` <?php use Magento\Framework\App\Bootstrap; include('app/bootstrap.php'); $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $_product = $objectManager->create('Magento\Catalog\Model\Product'); $_product->setName('Test Product'); $_product->setTypeId('simple'); $_product->setAttributeSetId(4); $_product->setSku('test-SKU'); $_product->setWebsiteIds(array(1)); $_product->setVisibility(4); $_product->setPrice(array(1)); $_product->setImage('/testimg/test.jpg'); $_product->setSmallImage('/testimg/test.jpg'); $_product->setThumbnail('/testimg/test.jpg'); $_product->setStockData(array( 'use_config_manage_stock' => 0, //'Use config settings' checkbox 'manage_stock' => 1, //manage stock 'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart 'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart 'is_in_stock' => 1, //Stock Availability 'qty' => 100 //qty ) ); $_product->save(); ?> ```
2020/01/29
[ "https://magento.stackexchange.com/questions/302472", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/85815/" ]
***programmatically create product file put in Magento root directory and run*** example in localhost go to ***var/www/html/magentosmpl233/*** and put your file and run ``` example http://127.0.0.1/magesmpl233/createproduct.php ```
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can install the free 1 month trail version of [Adobe Flash CS4 Professional](https://www.adobe.com/products/flash/), which you can use to edit and create free flash movies. If all you need to do is a one-time editing of the flash (.fla) file, you can get away using just the trial version.
27,737,444
I have a table `#TrackPlayedInformation` upon which I am looping. Sample data of `#TrackPlayedInformation` is as follows: ``` ProfileTrackTimeId JukeBoxTrackId ProfileId EndTime SessionId StartTime 14 52 33 2014-08-16 05:47:19.410 23424234 2014-08-16 05:45:19.410 15 51 33 2014-11-16 05:47:19.410 23424234 2014-08-16 05:45:19.410 ``` I am looping through `#TrackPlayedInformation` and splits the time interval between start time and end time on each minute. New time is inserted on a physical table `TempGraph` Structure of TempGraph is ``` TempGraphId AirTime AirCount 170390 2014-08-16 05:46:19.410 0 170391 2014-08-16 05:47:19.410 0 ``` While inserting to `TempGraph` if not exists is checked, if exists it updates aircount incremented by 1 else inserted as new entry. The query execution takes about 20 minutes to complete id the date interval is about 3 month. Is there any faster way to achieve the result? My workout query is as follows: ``` USE [SocialMob] GO /****** Object: StoredProcedure [dbo].[pDeleteTempGraph] Script Date: 01/02/2015 09:00:32 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[pDeleteTempGraph] AS BEGIN print('start') declare @UserId int declare @ProfileTrackTimeId int set @UserId=1048 drop table #TrackPlayedInformation delete from TempGraph declare @loopCount int declare @StartTime datetime declare @LastDate datetime declare @tempCount int declare @EndTime datetime declare @SaveTime datetime declare @checkDate datetime declare @countCheck int --querying input-- --drop table #TrackPlayedInformation --declare @UserId int --set @UserId=33 SELECT ProfileTrackTimeId,ProfileTrackTime.JukeBoxTrackId,ProfileId,EndTime,SessionId,StartTime into #TrackPlayedInformation FROM ProfileTrackTime LEFT JOIN (SELECT JukeBoxTrackId FROM JukeBoxTrack INNER JOIN Album ON JukeBoxTrack.AlbumId=Album.AlbumId WHERE Album.UserId=@UserId) as AllTrackId ON ProfileTrackTime.JukeBoxTrackId=AllTrackId.JukeBoxTrackId set @loopCount=0 declare @count as int select @count=COUNT(ProfileTrackTimeId) from #TrackPlayedInformation set @LastDate=GETDATE()--storing current datetime print('looping starts') while @loopCount<@count begin select @StartTime=StartTime from #TrackPlayedInformation select @EndTime=EndTime from #TrackPlayedInformation select @ProfileTrackTimeId=ProfileTrackTimeId from #TrackPlayedInformation --select @checkDate=AirTime from TempGraph while @StartTime<=@EndTime begin set @StartTime=DATEADD(minute,1,@StartTime) --checking for duplication --SELECT @countCheck= count(TempGraphId) FROM TempGraph WHERE AirTime=@StartTime --select @countCheck --if (@countCheck<1) if not exists(select top 1 TempGraphId from TempGraph where AirTime=@StartTime) begin --print('inserting') insert TempGraph (AirTime,AirCount) values(@StartTime,0) end else begin --print('updating') update TempGraph set AirCount=AirCount+1 where AirTime=@StartTime end set @LastDate=@StartTime end set @LastDate=DATEADD(MINUTE,1,@LastDate); --deleting row from #TrackPlayedInformation --print('deleting') delete from #TrackPlayedInformation where ProfileTrackTimeId=@ProfileTrackTimeId set @loopCount=@loopCount+1 --incrementing looping condition end begin insert TempGraph (AirTime,AirCount) values(@LastDate,0) end begin declare @nowdate datetime set @nowdate=GETDATE() insert TempGraph (AirTime,AirCount) values(@nowdate,0) end select * from TempGraph; delete from TempGraph; END ``` I am trying to split a time interval by minute for eg- consider date 2014 01 01 5.40 as start time and 2014 01 01 5.50 as end time.i need to entry in TempGraph as 2014 01 01 5.41, 2014 01 01 5.42, 2014 01 01 5.43 .....upto 2014 01 01 5.50
2015/01/02
[ "https://Stackoverflow.com/questions/27737444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3079776/" ]
It is not entirely clear to me what you are trying to accomplish. Nevertheless, loops in SQL should be avoided if possible. You might consider an `UPDATE` statement similar to: ``` UPDATE TempGraph SET AirCount = AirCount + 1 WHERE AirTime BETWEEN @StartTime AND @EndTime ``` followed by something that inserts records for the "missing" times. Without more information on the purpose of this code, it is difficult to provide more help.
59,758,245
I have a dataset in the below format however the data set is a lot bigger: ``` import pandas as pd df1 = pd.DataFrame({'From': ['RU','USA','ME'], 'To': ['JK', 'JK', 'JK'], 'Distance':[ 40000,30000,20000], 'Days': [8,6,4]}) ``` I want to add a date range to each location: ``` date_rng = pd.date_range(start='01/02/2020', freq='MS', periods=3) ``` The end result should look like this: ``` df2 = pd.DataFrame({'Date':['01/02/2020' , '01/03/2020', '01/04/2020','01/02/2020' , '01/03/2020', '01/04/2020','01/02/2020' , '01/03/2020', '01/04/2020'], 'From': ['RU', 'RU', 'RU','USA', 'USA', 'USA','ME', 'ME', 'ME'], 'To': ['JK', 'JK', 'JK','JK', 'JK', 'JK','JK', 'JK', 'JK'], 'Distance':[ 40000, 40000, 40000,30000, 30000, 30000,20000, 20000, 20000], 'Days': [8,8,8,6,6,6,4,4,4]}) ```
2020/01/15
[ "https://Stackoverflow.com/questions/59758245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9749942/" ]
Perhaps this will do what you need: ``` l = [] for d in date_rng: df1['Date'] = d l.append(df1.copy()) pd.concat(l) ```
1,803,165
I need to calculate the volume of solid enclosed by the surface $(x^2+y^2+z^2)^2=x$, using only spherical coordinates. My attempt: by changing coordinates to spherical: $x=r\sin\phi\cos\theta~,~y=r\sin\phi\sin\theta~,~z=r\cos\phi$ we obtain the Jacobian $J=r^2\sin\phi$. When $\phi$ and $\theta$ are fixed, $r$ varies from $0$ to $\sqrt[3]{\sin\phi\cos\theta}$ (because $r^4=r\sin\phi\cos\theta$). Keeping $\theta$ fixed, we let $\phi$ vary from $0$ to $\pi$. Thus the volume equals: $$V=\int\limits\_{0}^{\pi}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\phi\cos\theta}}r^2\sin\phi ~dr ~d\phi ~d\theta=0$$ Which is obviously wrong. What am I doing wrong?
2016/05/28
[ "https://math.stackexchange.com/questions/1803165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342907/" ]
Succinctly, the bounds of integration on $\theta$ should be $-\pi/2\leq\theta\leq\pi/2$, which yields the very believable value of $\pi/3$. The comments seem to indicate some confusion about this, so let's explore it a bit further. A standard exercise related to spherical coordinates is to show that the graph of $\rho^2=x$ is a sphere. Now we've got $\rho^4=x$ so it makes sense to suppose that we have a slightly distorted sphere - perhaps, an oblate spheroid or close. In both cases, we have $$x=\text{a non-negative expression}.$$ Thus, the graph must lie fully in the half-space on one side of the $yz$-plane. Using some snazzy contour plotter, we see that it looks like so: [![enter image description here](https://i.stack.imgur.com/QA99d.png)](https://i.stack.imgur.com/QA99d.png) The contour line wrapped around the equator is the intersection of the object with the $xy$-plane. If we look at this from the above (along the $z$-axis) we can see how a polar arrow might trace out that contour: [![enter image description here](https://i.stack.imgur.com/99yKw.gif)](https://i.stack.imgur.com/99yKw.gif) From this image, it's pretty clear that we need $\theta$ to sweep from the negative $y$-axis to the positive $y$-axis. A natural way to make that happen is let $\theta$ range over $-\pi/2\leq\theta\leq\pi/2$. To polish the problem off, we rewrite the equation $(x^2+y^2+z^2)^2=x$ in spherical coordinates as $$\rho^4 = \rho\sin(\varphi)\cos(\theta),$$ or $$\rho = \sqrt[3]{\sin(\varphi)\cos(\theta)}.$$ This gives us the upper bound of $\rho$ in the spherical integral: $$ \int\limits\_{-\pi/2}^{\pi/2}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\varphi\cos\theta}}r^2\sin\varphi ~dr ~d\varphi ~d\theta=\frac{\pi}{3}. $$
7,414,512
I'm sorry for my mistake grammar and e.t.c in my question ,because English is not my first language!! But my question: I want digital signature sms and send it to another ,this means that digital signature to an sms and send it to another and retrieved it from other device. This is essential. please give me a solution for do this . thanks anybody.
2011/09/14
[ "https://Stackoverflow.com/questions/7414512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/941923/" ]
Consider using this :- <http://www.ibm.com/developerworks/wireless/library/wi-extendj2me/> <http://snippets.dzone.com/posts/show/5115> For Sending/Receiving the sms
499,345
**UPDATE 20th May:** Swapped the analog output regulator for an AZ1117-EH based on Peter Smith's suggestion, removed C1306, so now the 3.3VA output should be ok at least based on the [datasheet](https://www.diodes.com/assets/Datasheets/AZ1117E.pdf). However, no significant improvement. See scope shots and discussion under the section market NEW MAY 20TH. **UPDATE 18th May:** More scope shots below, which do seem to be telling a story. See discussion marked NEW. **UPDATE:** tried adding resistors to the DAC output which had some effect, see below. **EDIT:** tested the dielectric absorption theory: not the culprit (see below). I'm multiplexing a 4 channel 16 -bit DAC to 21 output channels via DG4052 multiplexers (exact part numbers and links to the datasheets below). There's a 10nF hold capacitor after the multiplexer, with the output going to the + -input of a TL074 opamp. The relevant part of the multiplexer schematic: [![MUX schematic](https://i.stack.imgur.com/PDU7a.png)](https://i.stack.imgur.com/PDU7a.png) **updated** and the DAC output schematic (though note below about adding a resistor in series): [![Schematic DAC](https://i.stack.imgur.com/YiwYl.png)](https://i.stack.imgur.com/YiwYl.png) The DACn channels come directly from the DAC outputs (but see below for a test with a resistor in between), and are in the range 0..3.3V. Update rate is 3kHz, and the charge time is about \$\mathrm{40\mu s}\$ **The problem:** The output of a channel, take for example VExpMCU, glitches by about 1.2mV when the enable toggles, and the address of the corresponding channel is selected. In the picture, the yellow trace is VExpMcu, AC coupled, and the blue trace is the MUX enable (which is inverting). The output value is held constant, so the ideal result would be a flat horizontal line: [![Glitch](https://i.stack.imgur.com/lpEff.jpg)](https://i.stack.imgur.com/lpEff.jpg) As a test, I added a 270\$\Omega\$ resistor between the DAC1 output and the MUX input. The result was that the glitch level about halved, but the initial transient is still about the same as before. Note the different time scale, and also the cursors showing that the step is now smaller, at about 660\$\mathrm{\mu V}\$: [![GlitchWith270ohms](https://i.stack.imgur.com/AcTAe.jpg)](https://i.stack.imgur.com/AcTAe.jpg) Interestingly, increasing the resistor to \$1\mathrm{k\Omega}\$ (sorry about the really bad picture here, vertical scale is 1mV/div) about further halved the step, but the initial glitch size remains about the same, with a much longer settling time. This suggests it may nonetheless be something similar to what Andy aka suggested, but there's still a downward step when the enable turns off, which means that somehow the hold cap immediately loses some charge: [![GlitchWith1kOhm](https://i.stack.imgur.com/GyLKk.jpg)](https://i.stack.imgur.com/GyLKk.jpg) **NEW on May 18th:** Setting all the channels to the same output value (so the DAC output would ideally be constant, and it's easy to scope slight glitches there) gives the following scope shot, yellow is enable (active low), blue is directly the DAC output: [![DacOut](https://i.stack.imgur.com/KbR2h.jpg)](https://i.stack.imgur.com/KbR2h.jpg) The big glitch happens while enable is off, so it's irrelevant here. However, there seems to be something on the rising/falling edges. Zooming in on the glitches near the enable signal edges: [![DacOutZoomR](https://i.stack.imgur.com/EUvKB.jpg)](https://i.stack.imgur.com/EUvKB.jpg) [![DacOutZoomL](https://i.stack.imgur.com/rgHi8.jpg)](https://i.stack.imgur.com/rgHi8.jpg) Then a scope shot of the power supply, yellow is still enable, blue is now the 3.3V analog power (AC coupled) measured at C1407: [![SupplyGlitch](https://i.stack.imgur.com/qmewR.jpg)](https://i.stack.imgur.com/qmewR.jpg) which seems to tell us everything: the analog supply sags when the enable toggles, causing the DAC output to glitch, which causes the glitch in the mux output. However, one more scope shot throws a wrench in the works: triggering the scope from the DAC output glitch (the big one that happens while the enable is off) gives the following (Blue is DAC output, yellow is 3.3V analog at C1407): [![Supply and DAC output](https://i.stack.imgur.com/SswUE.jpg)](https://i.stack.imgur.com/SswUE.jpg) Note the absence of the supply glitch. Basically, the scope shots of the 3.3V line are inconsistent, so one of them is wrong. So now I'm thoroughly confused. So how do I check if the problem in the supply is real or a scope artifact? If it's real, how to fix it? There's over 50\$\mathrm{\mu F}\$ of capacitors on the power rail, so just throwing more won't help unless it's *a lot* more. Here's the power section of the board, in case that tells us something (**EDIT: regulator has since been swapped**): [![PSU schematic](https://i.stack.imgur.com/Ci5R5.png)](https://i.stack.imgur.com/Ci5R5.png) **NEW MAY 20TH:** Swapped the analog regulator for an AZ1117-EH, which shouldn't have problems with the 100n caps (removed C1306 which was too close, though). The glitch on the supply still persists, it's now actually a bit bigger though more symmetric: [![GlitchSupplyAZ1117-EH](https://i.stack.imgur.com/aSJKd.jpg)](https://i.stack.imgur.com/aSJKd.jpg) As before, when triggering on the DAC the glitch on the supply line is not present, so that mystery still persists. It's also not on any other power rail when triggering from the DAC. However, it's there on all of them when triggering from the enable signal, for example this time with the yellow trace being +12V at the input to the analog 3.3V regulator: [![Glitch12V](https://i.stack.imgur.com/LpkGQ.jpg)](https://i.stack.imgur.com/LpkGQ.jpg) This is making me think that the glitch on the power rail may be an artifact of my scope grounding, somehow leaking from the neighbouring channel when I'm triggering on the enable (I also tried to use channels 1 and 4 on the scope, just in case, no difference). However, it's always there on the DAC output, so that's probably real. So what now? **EDIT:** Here's the list of potential sources for glitches which I originally considered, most of these appear somewhat irrelevant now in light of the new pictures: 1. mishaps in the timing code, i.e. DAC not having settled, address being selected after the enable, etc etc. However, I believe I've squashed such bugs from the firmware now (there were indeed a few). Also, one would expect those to produce a glitch in the beginning or end of the update cycle, whereas this seems to be a square-like shape for the duration of the enable pulse (although it's hard to be 100% certain since we're at the limits of my modest scope). Anyway, I'm happy to provide scope shots of the address/enable/DAC output signals if you have a hunch it might be something related to that. 2. Charge injection from the mux. However, from the [datasheet](https://www.vishay.com/docs/69685/dg4051e.pdf), the maximum charge injection is... uh... missing from the datasheet in the 12V case, but taking the worst of the cases there is, 0.38pC, which to a 10nF capacitor gives \$0.38\mathrm{pC} / 10 \mathrm{nF} = 38\mathrm{\mu V}\$ change, so about 30 times less. **Update** tried doubling the cap, as suggested by WhatRoughBeast. No change, so it's definitely not charge injection. 3. stray capacitance storing charge somewhere: if there'd be a stray capacitance of about \$1\mathrm{mV} / 3.3V 10 \mathrm{nF} \approx 30 \mathrm{pF}\$, then charge sharing could cause such a glitch (for a full scale voltage difference). However, \$30\mathrm{pF}\$ seems a bit big for stray capacitance here (although admittedly the biggest capacitances mentioned in the datasheet are about 10pF, so not that far off), and besides it's difficult to understand how it would cause the square-like shape, instead of the DAC output buffer correcting it after an initial glitch? **Edit** with the newer picture with the resistor, the squareness of the shape isn't quite that obvious anymore, but then it's difficult to see how increasing the resistance between the DAC and the mux would reduce the error if it's due to stray capacitance. 4. Stray coupling from the address/enable signals: the glitch only happens when that specific channels enable toggles, if it we're parasitic coupling I'd expect to see constant glitches at the enable rate. 5. Capacitor dielectric absorption (DA): I swapped the original X7R cap (specifically a TDK C1608X7R2A103K080AA) for a 10 nF C0G -capacitor (GRM1885C1H103JA01D) in the channel in question, which should have less DA, with no difference in the signal. So I think we can rule out DA. 6. as suggested by Andy aka: the DAC output buffer could be nearly unstable (the datasheet guarantees stability only up to 0.2nF for 0 ohm series resistance, up to 15\$\mathrm{\mu F}\$ for 500 ohms). To test this, I tried decreasing the update rate to 1kHz, which I'd expect to exaggerate the glitch, and potentially see the glitch starting to settle during the longer charge time. However, the glitch size remains exactly the same, and it still appears square-like, without showing signs of settling during the charge time (which has now increased to about 125\$\mathrm{\mu S}\$) **Edit:** however, see the new scope shots above: [![Glitch at 1kHz](https://i.stack.imgur.com/IanJS.jpg)](https://i.stack.imgur.com/IanJS.jpg) **Update:** also tried to add a 10k resistor from DAC output to ground, as suggested by PeterSmith. No change. **Summary this far:** the only change that has had an effect was adding a series resistor after the DAC. Interestingly, doubling the hold cap had no effect either, which means that the step at the end of the charge period is not a fixed amount of *charge* being drawn from the hold cap, but a fixed *voltage* step. However, the glitch seems to be present already at the DAC output, and there's something fishy about the power rails, see discussion above. The promised part numbers and datasheets (don't hesitate to ask for more info, if you need): * DAC: Maxim MAX5134AGTG+, [Datasheet](https://datasheets.maximintegrated.com/en/ds/MAX5134-MAX5137.pdf) * MUX: Vishay DG4052E, [Datasheet](https://www.vishay.com/docs/69685/dg4051e.pdf) * OpAmp: TI TL074, [Datasheet](https://www.ti.com/lit/ds/slos080n/slos080n.pdf?&ts=1589362944238) * hold cap: TDK C1608X7R2A103K080AA, [Datasheet](https://product.tdk.com/info/en/catalog/datasheets/mlcc_commercial_midvoltage_en.pdf) * Analog regulator: replaced an LM1117 with an [AZ1117-EH](https://www.diodes.com/assets/Datasheets/AZ1117E.pdf)
2020/05/13
[ "https://electronics.stackexchange.com/questions/499345", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/54822/" ]
The problem could well be at the 3.3V regulators: [![Power annotated](https://i.stack.imgur.com/SC53A.png)](https://i.stack.imgur.com/SC53A.png) I have circled the output capacitors; the LM1117 [datasheet](https://www.ti.com/lit/ds/symlink/lm1117.pdf?&ts=1589794564554) states: **8.2.2.1.3 Output Capacitor** > > The output capacitor is critical in maintaining regulator stability, > and must meet the required conditions for both minimum amount of > capacitance and equivalent series resistance (ESR). The **minimum** output > capacitance required by the LM1117 is **10 μF**, if a tantalum capacitor > is used. Any increase of the output capacitance will merely improve > the loop stability and transient response. The ESR of the output > capacitor should range between **0.3 Ω to 22 Ω**. In the case of the > adjustable regulator, when the CADJ is used, a larger output > capacitance (22-μF tantalum) is required. > > > A ceramic capacitor will very probably be below this minimum value and the actual minimum value depends on load *and* input voltage which will vary across those conditions. A load step (which does not need to be very much) *can* cause instability at the output which would explain a great deal. In addition to that, the output capacitance of the 3.3V digital rail does not appear to be sufficient (10\$\mu\$F *minimum*). Whether you actually see that instability is going to depend on many things and even attaching a scope probe to the power rail will change those conditions, so it may do one thing without the probe and something different when you *do* probe the power rail. [Update] The usual way of dealing with this sort of issue is to either use a standard tantalum (not the low esr series) which typically have an esr in the required range (although there are [other problems](https://electronics.stackexchange.com/questions/99320/are-tantalum-capacitors-safe-for-use-in-new-designs/99321#99321) with tantalums) or to use a ceramic in series with a low value resistor on the output. Where there are low esr local decouplers, they can sometimes be isolated by using a small inductor or ferrite on the output (we are trying to prevent instability caused by transients). If the devices are far enough away such that track inductance effectively isolates them from the output of the regulator then that may not be required. Sometimes, low esr local decouplers simply cannot be used (I have had this specific problem in the past) and the output capacitance on the regulator has to be relied upon for transient response. The output ESR issue for older LDO devices is well known and many newer parts do not have this problem.
3,814,277
I'm working on a PHP project that has a lot of hard coded paths in it. I'm not the main developer, just working on a small part of the project. I'd like to be able to test my changes locally before committing them, but my directory structure is completely different. For example, there's a lot of this in the code: ``` require_once("/home/clientx/htdocs/include.php") ``` Which doesn't work on my local WAMP server because the path is different. Is there a way to tell either WAMP or XP that "/home/clientx/htdocs/" really means "c:/shared/clients/clientx"?
2010/09/28
[ "https://Stackoverflow.com/questions/3814277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222374/" ]
Always use `$_SERVER['DOCUMENT_ROOT']` instead of hardcoded path. ``` require_once($_SERVER['DOCUMENT_ROOT']."/include.php") ``` as for your wamb environment, you will need a dedicated drive to simulate file structure. You can use NTFS tools or simple `subst` command to map some directory to a drive. Create `/home/clientx/htdocs/` folder on this drive and change your httpd.conf to reflect it. But again, you will do yourself a huge favor by convincing your coworkers to stop using hardcoded paths
63,313,509
For my work, we are trying to spin up a docker swarm cluster with Puppet. We use puppetlabs-docker for this, which has a module `docker::swarm`. This module allows you to instantiate a docker swarm manager on your master node. This works so far. On the docker workers you can join to docker swarm manager with exported resources: ``` node 'manager' { @@docker::swarm {'cluster_worker': join => true, advertise_addr => '192.168.1.2', listen_addr => '192.168.1.2', manager_ip => '192.168.1.1', token => 'your_join_token' tag => 'docker-join' } } ``` However, the `your_join_token` needs to be retrieved from the docker swarm manager with `docker swarm join-token worker -q`. This is possible with `Exec`. My question is: is there a way (without breaking Puppet philosophy on idempotent and convergence) to get the output from the join-token `Exec` and pass this along to the exported resource, so that my workers can join master?
2020/08/08
[ "https://Stackoverflow.com/questions/63313509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3419197/" ]
> > My question is: is there a way (without breaking Puppet philosophy on > idempotent and convergence) to get the output from the join-token Exec > and pass this along to the exported resource, so that my workers can > join master? > > > No, because the properties of resource declarations, exported or otherwise, are determined when the target node's catalog is built (on the master), whereas the command of an `Exec` resource is run only later, when the fully-built catalog is applied to the target node. I'm uncertain about the detailed requirements for token generation, but possibly you could use Puppet's [generate()](https://puppet.com/docs/puppet/6.17/function.html#generate) function to obtain one at need, during catalog building on the master. **Update** Another alternative would be an external (or custom) fact. This is the conventional mechanism for gathering information from a node to be used during catalog building for that node, and as such, it might be more suited to your particular needs. There are some potential issues with this, but I'm unsure how many actually apply: * The fact has to know for which nodes to generate join tokens. This might be easier / more robust or trickier / more brittle depending on factors including + whether join tokens are node-specific (harder if they are) + whether it is important to avoid generating multiple join tokens for the same node (over multiple Puppet runs; harder if this is important) + notwithstanding the preceding, whether there is ever a need to generate a new join token for a node for which one was already generated (harder if this is a requirement) * If implemented as a dynamically-generated external fact -- which seems a reasonable option -- then when a new node is added to the list, the fact implementation will be updated on the manager's next puppet run, but the data will not be available until the following one. This is not necessarily a big deal, however, as it is a one-time delay with respect to each new node, and you can always manually perform a catalog run on the manager node to move things along more quickly. * It has more moving parts, with more complex relationships among them, hence there is a larger cross-section for bugs and unexpected behavior.
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
Your usage of `$(this)` won't work because you haven't made a selection. In JQuery `this` is always bound to the context the previous selector or method, it's a JQuery object containing the results of the selection or filter. Additionally, your selector for finding the child element to insert HTML into is too broad. ``` $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); ``` It will select every single `<div>` with a class of `p-accessible-alt` and insert the same HTML block into all of them. You can replace your entire if block with the following selectors (one for each size). ``` $(".size3").siblings(".p-accessible-alt").html("<p> Blah Blah Size3</p>"); $(".size4").siblings(".p-accessible-alt").html("<p> Blah Blah Size4</p>"); $(".size5").siblings(".p-accessible-alt").html("<p> Blah Blah Size5</p>"); ``` This works by finding the element with the class `.sizeX` and then traverses up to it's parent container, then back down the hierarchy to find it's descendant with the class `.p-accessible-alt` and then apply the html to that.
1,723,227
I have a table of a couple of million records. During production, we find that there is a particular type of query that is taking a few seconds to complete. When I try to reproduce the issue on my machine which has replicated production data, I ran the exact query (as obtained from the slow query log) in the mysql client, it took a few seconds as expected. If I then press up and enter to repeat it, it takes 0.01 seconds subsequently. I have looked up the docs to find out how to turn off caching, so that I can consistently reproduce the issue, and want to test if adding an index will help. Here is what I tried: RESET QUERY CACHE; FLUSH TABLES; However, after the above commands, running the same query again still only takes 0.01 seconds. I must be missing something. Any ideas?
2009/11/12
[ "https://Stackoverflow.com/questions/1723227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209731/" ]
You can tell the server not to place the result in the query cache by including [SQL\_NO\_CACHE](http://dev.mysql.com/doc/refman/5.1/en/query-cache-in-select.html) in the query: ``` SELECT SQL_NO_CACHE id, name FROM customer; ``` Aside from the query cache though, there's a lot more going on inside MySQL to speed things up, it caches other information about tables and indexes to speed up future queries. The first execution of the query will also warm up operating system file caches too. What you really need to do is [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/en/explain.html) the query, and look at the number of rows the database engine needs to analyse. By exploring how it uses your table indexes (or not) you will be better informed as to what indexes might be missing, or alternative ways of structuring the query.
36,196,409
I am getting values in a format like this 00-C6 (Hex). It complains when I try to convert it to double (format execption). What to do? ``` public void check() { double low; double high; percentageCalculator(4095, 5, out low, out high); Dictionary[] A_1 = {Max_1, Min_1}; for (int i = 0; i < A_1.Length; i++) { if ((Convert.ToDouble(A_1[i].CurrentValue) <= low) || ((Convert.ToDouble(A_1[i].CurrentValue) >= high)) { Fault++; } } } ```
2016/03/24
[ "https://Stackoverflow.com/questions/36196409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013907/" ]
Assuming the `Hex` `00-C6` `string` represents `Integer` value (because if it represents `floating-point` value like `float` or `double`, it must consists of `4-byte` or `8-byte`), then one way to process it is to split the `Hex string`: ``` string hexString = "00-C6"; string[] hexes = hexString.Split('-'); ``` Then you process each element in the `hexes` like this: ``` int hex0 = Convert.ToInt32(hexes[0], 16); int hex1 = Convert.ToInt32(hexes[1], 16); ``` If the hex is little endian, then your `double` value would be: ``` double d = hex0 << 8 + hex1; ``` And if it is big endtion, your `double` will be: ``` double d = hex1 << 8 + hex0; ``` The key here is to know that you can convert hex string representation to `Int` by using `Convert.ToInt32` with second argument as `16`. You can combine all the steps above into one liner if you feel like. Here I purposely break them down for the sake of presentation clarity.
60,536,035
I am facing an issue with shopping cart. Unable to increase quantity of existing item in cart or add another item. On button click the addToCart function executes which takes a product. ``` const [cartItems, setCartItems] = useState([]) const addToCart = product => { console.log(product) // here I am getting the entire product const index = cartItems.findIndex(item => item._id === product._id); if (index === -1) { const updateCart = cartItems.concat({ ...product, quantity: 1 }); setCartItems(updateCart); } else { const updateCart = [...cartItems]; updateCart[index].quantity += 1; setCartItems(updateCart); } }; ``` I am getting only 1 quantity of product and if I add another product or increase quantity, it overwrites.
2020/03/04
[ "https://Stackoverflow.com/questions/60536035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13008960/" ]
Your else logic is wrong. You want to update your item quantity from carItems, before you spread it. Change: ``` const updateCart = [...cartItems]; updateCart[index].quantity += 1; setCartItems(updateCart); ``` to ``` cartItems[index].quantity += 1; const updateCart = [...cartItems]; setCartItems(updateCart); ``` Edit: See it in action below: ```js let cartItems = [{ _id: "1", name: "shoe", quantity: 1 }]; const addToCart = product => { console.log(product) // here I am getting the entire product const index = cartItems.findIndex(item => item._id === product._id); if (index === -1) { cartItems.push({ ...product, quantity: 1 }); const updateCart = [...cartItems]; console.log(updateCart); } else { cartItems[index].quantity += 1; const updateCart = [...cartItems]; console.log(updateCart); } }; var product1 = { _id: "1", name: "shoe" }; var product2 = { _id: "2", name: "apple" }; addToCart(product1); addToCart(product2); ```
47,771,494
My Android app `webview` works fine with chrome version 61 or 62, but when I update to version 63. My `webview`does not store the history and `webView.canGoBack()` always returns `false`. But previous versions of chrome work fine. How to solve?
2017/12/12
[ "https://Stackoverflow.com/questions/47771494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5702991/" ]
This issue should be chromium's bug. We find out the same issue in our apps. the reason of this issue is we invoke Webview's loadUrl methond in shouldOverrideUrlLoading method, when we do that , webview can't go back in some version of chromium. The code below is my workaround: ``` public class WebViewBugFixDemo extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // todo : set your content layout final WebView webView = (WebView) findViewById(R.id.webview); final String indexUrl = "http://www.yourhost.com"; final String indexHost = Uri.parse(indexUrl).getHost(); webView.loadUrl(indexUrl); webView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { if (isSameWithIndexHost(url, indexHost)) { return false; } view.loadUrl(url); return true; } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && request != null && request.getUrl() != null) { String url = request.getUrl().toString(); if (isSameWithIndexHost(url, indexHost)) { return false; } view.loadUrl(url); return true; } return super.shouldOverrideUrlLoading(view, request); } }); } /** * if the loadUrl's host is same with your index page's host, DON'T LOAD THE URL YOURSELF ! * @param loadUrl the new url to be loaded * @param indexHost Index page's host * @return */ private boolean isSameWithIndexHost(String loadUrl, String indexHost) { if (TextUtils.isEmpty(loadUrl)) { return false ; } Uri uri = Uri.parse(loadUrl) ; Log.e("", "### uri " + uri) ; return uri != null && !TextUtils.isEmpty(uri.getHost()) ? uri.getHost().equalsIgnoreCase(indexHost) : false ; } } ```
69,725,727
Below comparison is giving false result in PowerShell , Want it to be true. ` operator is causing it to be false whereas for any other special character it is returning true. ``` > 'abc`@01' -like 'abc`@01' False ```
2021/10/26
[ "https://Stackoverflow.com/questions/69725727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17251840/" ]
`-like` is a wildcard comparison operator and ``` is a wildcard escape sequence. ``` PS ~> 'abc`@01' -like 'abc``@01' True ``` Use `-eq` if you want an exact string comparison without having to worry about escaping the reference string: ``` PS ~> 'abc`@01' -eq 'abc`@01' True ```
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
First, look into a UPS (un-interuptable power supply) Second, look into creating persistent transactions, transactions that will save early and often, but not commit until you tell it to. This goes a little beyond the typical transactions in TSQL.
23,510,648
I want to create an Array of JavaFX controllers in order to be easier to work with them e.g. you could loop adding/setting elements in a GridPane. But despite of the compiler/IDE not displaying any error this code below doesn't work: ``` public GridPane drawPane(){ GridPane grid = new GridPane(); Button[] btn = new Button[10]; grid.add(btn[0], 0,0); return grid; } ``` however this one **does work**: ``` public GridPane drawPane(){ GridPane grid = new GridPane(); Button btn = new Button(); grid.add(btn, 0,0); return grid; } ``` Am I instancing the controllers wrong? Why this code doesn't work with arrays ?
2014/05/07
[ "https://Stackoverflow.com/questions/23510648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2188186/" ]
This is hard to acheive when it comes to unicode characters. Even valid unicode characters (there are a ton of it) might not being printable because the current font contains no letter definitions for that character. Meaning a German unicode font might not contain all valid Chinese characters for example. If you just care about ascii, you can use `ctype_print()` to check if a character is printable or not. Example: ``` // test string contains printable and non printable characters $string = "\x12\x12hello\x10world\x03"; $allowed = array("\x10", /* , ... */); // iterate through string for($i=0; $i < strlen($string); $i++) { // check if current char is printable if(ctype_print($string[$i]) || in_array($string[$i], $allowed)) { print $string[$i]; } else { // use printf and ord to print the hex value if // it is a non printable character printf("\\x%02X", ord($string[$i])); } } ``` Output: ``` \x12\x12hello world\x03 ```
42,207,975
this type of question has been asked many times. So apologies; I have searched hard to get an answer - but have not found anything that is close enough to my needs (and I am not sufficiently advanced **(I am a total newbie)** to customize an existing answer). So thanks in advance for any help. Here's my query: * I have 30 or so csv files and each contains between 500 and 15,000 rows. * Within each of them (in the 1st column) - are rows of alphabetical IDs (some contain underscores and some also have numbers). * I don't care about the unique IDs - but I would like to identify the duplicate IDs and the number of times they appear in all the different csv files. * Ideally I'd like the output for each duped ID to appear in a new csv file and be listed in 2 columns **("ID", "times\_seen")** It may be that I need to compile just 1 csv with all the IDs for your code to run properly - so please let me know if I need to do that I am using python 2.7 (a crawling script that I run needs this version, apparently). Thanks again
2017/02/13
[ "https://Stackoverflow.com/questions/42207975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7557229/" ]
It seems the most easy way to achieve want you want would make use of dictionaries. ``` import csv import os # Assuming all your csv are in a single directory we will iterate on the # files in this directory, selecting only those ending with .csv # to list files in the directory we will use the walk function in the # os module. os.walk(path_to_dir) returns a generator (a lazy iterator) # this generator generates tuples of the form root_directory, # list_of_directories, list_of_files. # So: declare the generator file_generator = os.walk("/path/to/csv/dir") # get the first values, as we won't recurse in subdirectories, we # only ned this one root_dir, list_of_dir, list_of_files = file_generator.next() # Now, we only keep the files ending with .csv. Let me break that down csv_list = [] for f in list_of_files: if f.endswith(".csv"): csv_list.append(f) # That's what was contained in the line # csv_list = [f for _, _, f in os.walk("/path/to/csv/dir").next() if f.endswith(".csv")] # The dictionary (key value map) that will contain the id count. ref_count = {} # We loop on all the csv filenames... for csv_file in csv_list: # open the files in read mode with open(csv_file, "r") as _: # build a csv reader around the file csv_reader = csv.reader(_) # loop on all the lines of the file, transformed to lists by the # csv reader for row in csv_reader: # If we haven't encountered this id yet, create # the corresponding entry in the dictionary. if not row[0] in ref_count: ref_count[row[0]] = 0 # increment the number of occurrences associated with # this id ref_count[row[0]]+=1 # now write to csv output with open("youroutput.csv", "w") as _: writer = csv.writer(_) for k, v in ref_count.iteritems(): # as requested we only take duplicates if v > 1: # use the writer to write the list to the file # the delimiters will be added by it. writer.writerow([k, v]) ``` You may need to tweek a little csv reader and writer options to fit your needs but this should do the trick. You'll find the documentation here <https://docs.python.org/2/library/csv.html>. I haven't tested it though. Correcting the little mistakes that may have occurred is left as a practicing exercise :).
43,538,049
Why does block with text shift to the bottom? I know how to fix this issue (need to add "overflow: hidden" to the box), but I don't understand why it shift to the bottom, text inside the box is short, margins in browser-inspector are same as margins of example without text. [Example of the problem](https://codepen.io/AzatKaumov/pen/ZKQpOR/) HTML: ``` <div class="with-text"> <div class="box1"> SIMPLE TEXT </div> <div class="box2"> </div> </div> <div class="without-text"> <div class="box1"> </div> <div class="box2"> </div> </div> ``` CSS: ``` html, body { font-size: 10px; margin: 0; height: 100%; } .box1 { display: inline-block; margin: 5px; width: 50px; height: 50px; background: blue; /* Fix the problem */ /* overflow: hidden; */ color: white; } .box2 { display: inline-block; margin: 5px; width: 50px; height: 50px; background: red; } .with-text:before { display: block; content: "with-text"; text-transform: uppercase; margin: 1rem; } .with-text { box-sizing: border-box; height: 50%; border: 1px solid; } .without-text:before { display: block; content: "without text"; text-transform: uppercase; margin: 1rem; } .without-text { box-sizing: border-box; height: 50%; border: 2px solid black; } ```
2017/04/21
[ "https://Stackoverflow.com/questions/43538049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151870/" ]
The problem is that by default vertical alignment of **inline elements** – **baseline**, The text inside element affects it and pushes div to the bottom. Use `vertical-align: top` to solve issue.
23,334,980
This is my query ``` SELECT CONCAT(`SM_Title`,' ',`SM_Full_Name`) AS NAME, `RG_Date`, `RG_Reg_No`, `RG_Stu_ID`, `SM_Tell_Mobile`, `SM_Tel_Residance`, `RG_Reg_Type`, Default_Batch, `RG_Status`, `RG_Final_Fee`, `RG_Total_Paid`, (`RG_Final_Fee`-`RG_Total_Paid`) AS TOTALDUE, SUM(`SI_Ins_Amount` - `SI_Paid_Amount`) AS AS_AT_APRIAL_END INNER JOIN (SELECT `SI_Ins_Amount`, `SI_Reg_No` FROM `student_installments` GROUP BY MONTHNAME(`SI_Due_Date`)) Z ON Z.`SI_Reg_No` = `registrations`.`RG_Reg_No` FROM `registrations` LEFT JOIN `student_master` ON `student_master`.`SM_ID` = `registrations`.`RG_Stu_ID` LEFT JOIN `student_installments` ON `student_installments`.`SI_Reg_No` = `registrations`.`RG_Reg_No` WHERE (`RG_Reg_Type` LIKE '%HND%' OR `RG_Reg_Type` LIKE '%LMU%' ) AND `SI_Due_Date` <= '2014-04-30' GROUP BY `SI_Reg_No` ``` It gave me an error near `1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Z LIMIT 0, 25' at line 1`
2014/04/28
[ "https://Stackoverflow.com/questions/23334980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1521771/" ]
I may be wrong, but I don't believe you'd want `require ____` in a precompiled JS file > > The reason is the `require` lines are called *directives* which guide > the creation of a `manifest.json` file for your assets. The > [manifest](http://guides.rubyonrails.org/asset_pipeline.html#manifest-files-and-directives) basically tells Rails which files make up your assets, > allowing it to compile them effectively > > > You can see the precompiling documenation from the Rails guide [here](http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets) - basically says that the files you get from precompilation are "standalone" files. They are meant to be loaded as static files, without any preprocessors or directives I would try this: ``` $ rake assets:precompile RAILS_ENV=production ``` This will compile the files as if it were the production environment, and storing them in `/public/assets` as a naked JS / CSS file
6,944
Occasionally, I see a question for which I don't know enough to write a good answer, but I happen to know something that I think would be useful for someone asking that question to know. * **[Example 1](https://rpg.stackexchange.com/questions/94633/how-to-create-a-custom-lycanthrope-in-heroforge-anew#comment218859_94633):** Arthaban wants to know how to do something in HeroForge. I don't know how to do the thing they want to do in HeroForge, so I can't write a good answer. But I *do* know the developer of HeroForge, who probably knows the answer. So I comment with a link to where they could get in touch with her. * **[Example 2](https://rpg.stackexchange.com/questions/98082/how-should-a-substitution-level-be-read#comment230523_98082):** HeyICanChan wants to know what exactly gets replaced when you take a substitution level. I can't find satisfactory rules text that would tell us what *actually* happens - but I have noticed a regularity that might help them out in ruling on these things in a way that makes sense, so I post a comment briefly mentioning it. --- On the one hand, these smell a little bit like [partial-answers-in-comments](https://rpg.meta.stackexchange.com/questions/6533/should-users-refrain-from-answers-or-partial-answers-in-comments/6534#6534). On the other hand, they're not really answers - they're just things that the question makes me think the asker would probably want to know. Are such comments acceptable? If not, is there a different venue by which it would be more appropriate to communicate this kind of information?
2017/04/13
[ "https://rpg.meta.stackexchange.com/questions/6944", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/30299/" ]
No, these aren't acceptable. These are partial answers in comments. A "lead", an "idea", and something that starts with "not an answer but..." are all answers in comments. Your options are: 1. Take the time to find out and write an answer. 2. Hit them up in chat. 3. Let it lie. Usually #3 is the best, because usually the helpful tip isn't really that helpful. Most of them are some variant on "LMGTFY". Your example of "you could go here and contact the developer" - realistically, they know that, or could with a token bit of research. But they're asking here. Everyone knows they could Google or go ask the author/designer on Twitter or go post on some other forum for thing X and ask there. But that's not an answer. Someone with the wherewithal to actually contact the developer and find out - *they* deserve to post an answer. Your second example - so there's a 50% chance the lead is wrong and deceptive as to an approach, because you don't really know the answer. I totally know everyone throwing out "tips" is doing it to be helpful. I am certainly not questioning any motives. But the fact is, these "tips" in comments are often a) wrong, b) pointless, and/or c) lead to comment arguments when people try to rebut them since comments don't have downvotes and their own comments like a proper answer does. In general, don't do it. The likelihood you have the critical piece of information some real answerer doesn't have is slight. And by posting a piece, you disincentivize someone from writing an actual answer around that, since "Well... It's there in a comment and they've already read it... I'll go spend my time somewhere else."
41,493,243
I'm trying to remove a layout with the click of a button. I have this method in my MainActivity.java file: ``` public void goBack(View view) { TableLayout parent = (TableLayout) findViewById(R.id.activity_main); RelativeLayout child = (RelativeLayout) findViewById(R.id.activity_displayMessage); parent.removeView(child); } ``` It is fired when this button is clicked in the view I want to remove: ``` <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_removeView" android:onClick="goBack" /> ``` But it gives me this message: > > java.lang.IllegalStateException: Could not find method goBack(View) in > a parent or ancestor Context for android:onClick > > > But MainActivity is my main file for all my methods, so I'm not sure why it can't find it. Where should I put it so that it can be found? Thanks!
2017/01/05
[ "https://Stackoverflow.com/questions/41493243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880874/" ]
You can do this by rebinding `sys.stdout`: ``` >>> def foo(): ... print('potato') ... >>> import sys, io >>> sys.stdout = io.StringIO() >>> foo() >>> val = sys.stdout.getvalue() >>> sys.stdout = sys.__stdout__ # restores original stdout >>> print(val) potato ``` For a nicer way to do it, consider writing a context manager. If you're on Python 3.4+, it's [already been written for you](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout). ``` >>> from contextlib import redirect_stdout >>> f = io.StringIO() >>> with redirect_stdout(f): ... foo() ... >>> print(f.getvalue()) potato ``` In the case that you are able to modify the function itself, it may be cleaner to allow a dependency injection of the output stream (this is just a fancy way of saying "passing arguments"): ``` def foo(file=sys.stdout): print('potato', file=file) ```
3,910,625
I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria? I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete. Any suggestions/ideas will be grately appreciated.
2010/10/11
[ "https://Stackoverflow.com/questions/3910625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472777/" ]
Java has memory management. C and C++ don't, so it's memory management is a function of the programmer.
134,478
I would like to attach an eyebolt to the ridgeline of my metal roof. I can then attach a rope to that when I need to work on the roof. I am a climber and have the knowledge and gear to secure myself. The rope is mainly to allow me to get up the 10/12 central part of the roof (the ridgeline of which I'll mount the eye-bolt), and not slide off the adjacent 5/12 portions of the roof. It will not be subject to dynamic loading (catching falls); the biggest loads it will sustain are when I haul on it to get up the 10/12 roof (it's impossible otherwise, very slippery). Since the ridge cap is just a fairly flimsy piece of galvalume, the eyebolt must be secured without reliance on it (and RTV silicon caulked to it). My plan is to drill a hole through the ridge cap, the eyebolt will come through that, and then be attached to the rafters with two u-bolts. Since this is the ridge, it's where the rafters meet. So additionally, I will reinforce the rafters with two triangular shaped steel plates (one on each side of the area where the rafters meet); these will be bolted through the rafter with 2-3 bolts, and then the u-bolts will go through them as well. This picture shows the detail. [![enter image description here](https://i.stack.imgur.com/PLNdV.jpg)](https://i.stack.imgur.com/PLNdV.jpg)
2018/03/13
[ "https://diy.stackexchange.com/questions/134478", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/34111/" ]
If I may suggest an alternative since putting a hole in any roof is better avoided. I have a 10/12 pitched roof and I use an extension ladder with a stand-off stabilizer to reach the peak. [![stand-off stabilizer ](https://i.stack.imgur.com/gLCUR.jpg)](https://i.stack.imgur.com/gLCUR.jpg) The ladder is laid flat on the roof with the stabilizer pointing skyward. Extend the section and slide upward towards the peak and then flip the ladder so the stabilizer hooks over the peak. Climb up the rungs which offer both hand and footholds. Once you’re at the peak, tie off your safety line, hoist a plank to lay on the opposite side of the peak and insert through the top rung. Lash it off or use pipe clamps and you’ve reinforced the setup. I have used it to rebuild chimneys, antenna work, placing hundreds of pounds of brick, etc... on it.
17,220,607
I have a stored procedure like this: ``` create proc calcaulateavaerage @studentid int as begin -- some complicated business and query return @result -- single decimal value end ``` and then I want to create proc the whole result ``` select * , ................................ from X where X.value > (calculateaverage X.Id) ``` It always gives an error that reads like "multi-part identifier calculateaverage couldn't be bound." Any idea how to solve that?
2013/06/20
[ "https://Stackoverflow.com/questions/17220607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/712104/" ]
You don't want a stored procedure. You want a function.
11,242,592
I am facing a problem for several days and after many research I couldn't find anything that fit with my case. Here's the thing : I'm working with Visual Studio 2010 on a solution that contains several projects and a Setup Project. I want the setup project to create a MSI file to update the product from version 1.5 to version 1.6. I followed this tutorial <http://www.simple-talk.com/dotnet/visual-studio/updates-to-setup-projects/> and updated also the assembly version and file version numbers of each project of the solution. The settings of my Setup Project are : DetectNewerInstalledVersion : **True** InstallAllUsers : **True** RemovePreviousVersions : **True** Version : **1.6.3** The ProductCode is different from the ProductCode of the previous version and UpgradeCode is the same than the UpgradeCode of the previous version. I read that normally the MSI should remove the files which version is newer than the existing ones and replace with the new ones. And when I run the previous MSI (those which updates the product from 1.4 to 1.5) it works just fine as described. (I'm not sure with which version of visual studio it was compiled but I guess it's with VS2008). Now when I run my MSI, it seems that it first runs the "installation sequence" that replace the old .exe with the new ones, and then it runs the "uninstall sequence" that erase the .exe. And when the install is "finished" there is no more .exe in my application directory. (However in the "Add/Remove Programs" Panel the product apppears as installed in version 1.6). (NB : I can notice when the "install" part or "uninstall" part of the MSI is running because both have Custom Actions that open a Console Application in which I can have a trace). After more research I compared the old MSI with mine whith ORCA and I noticed differences in the table InstallExecuteSequence : With the old MSI, the sequence number of RemoveExistingProducts is **1525** that is between InstallInitialize (1500) and AllocateRegistrySpace (1550). With my MSI, the sequence number of RemoveExistingProducts is **6550** that is between InstallExecute (6500) and InstallFinalize (6600). I can't see any other differencies in the table. I even tried to edit manually with ORCA the MSI and put the sequence number of RemoveExistingProduct to 1525. At the execution the "uninstall part" ran correctly but then I got a 2356 Error (after a few research I guess this is because editing manually the MSI corrupted it). If anyone have an idea that explains the behaviour of my MSI and how to fix it? Thanks
2012/06/28
[ "https://Stackoverflow.com/questions/11242592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1488053/" ]
This appears to be a bug with the plugin "Microsoft Visual Studio 2017 Installer Projects". The msi file gets built with an incorrect sequence number (too high). The uninstall of older products happens *after* the install of new files, so new files get incorrectly deleted. Manual fix: Change the sequence so that uninstall of old products happens before the install of new items. * open the msi with orca.exe (or whatever editor works for you) * go to the InstallExecuteSequence table * change the RemoveExistingProducts sequence number so that it is between InstallValidate and InstallInitialize. For example, I changed it from 6550 to 1450. I ended up creating a simple script to do this fix automatically as a post build step. You can get on github it here... [InstallerStuff](https://github.com/DigitalCoastSoftware/InstallerStuff)
4,529,129
We have the following recursive definition of a set 1. The number 1 belongs to set S 2. if x belongs to set S, then so does x+x 3. Only those elements defined by above rules belong to set S Now, suppose x and y are two elements of set S. Prove that x\*y also belongs to set S. I realize that the set defined by three rules is the set of powers of 2 i.e. {1, 2, 4, 8, 16, 32,.....} and for any two powers of 2, we can use algebra to prove that their product is also a power of 2. But in this case, I need to prove that x\*y belongs to set S only by using the recursive definition of set S.
2022/09/11
[ "https://math.stackexchange.com/questions/4529129", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1093790/" ]
Since only the elements defined in this way are in the set, if $x\in S$ and $x\neq 1$, then $x/2\in S$. Suppose that $x\in S$ is the smallest element such that there exists $y\in S$ with $xy\not \in S$. We can't have $x$ or $y$ equal to $1$, so $x/2 \in S$. Then $(x/2)\*(2y)=xy\not \in S$, contradicting minimality of $x$.
24,207,428
For my current project, I need to drop some pins on a image(NOT a map), and also should be able to click the pin to add some comments to this pin. I wonder if I can use MKAnnotation/MKAnnotationView to do this. I have searched on Internet for a while. I only find tutorials about how to customize MKAnnotation with other images. If I cannot use MKAnnotation, what should I use? Any tutorials about this will be great helpful. Thanks.
2014/06/13
[ "https://Stackoverflow.com/questions/24207428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3727706/" ]
Finally I found that when I want to read attribute user.MYATTR, i have to use name MYATTR. I just wanna mention what interesting behaviour I found, that may lead to mystakes and i wanna warn you :) My file has these two attributes: user.MYATTR1 user.somethingElse.MYATTR2 When I was listing attributes using view.list() method I saw only this one (without user.): MYATTR1 when i wanna read attribute value, i have to use name of attribute without 'user.', so for mentioned attributes it is: MYATTR1 or somethingElse.MYATTR2
5,248,028
jQuery 1.4 added [a shorthand way for constructing new DOM Elements](http://api.jquery.com/jQuery/#jQuery2) and filling in some of their attributes: > > `jQuery( html, props )` > > > `html`: A string defining a single, standalone, HTML element (e.g. or ). > > > `props`: A map of attributes, events, and methods to call on the newly-created element. > > > But, I just noticed this strangeness (with jQuery 1.5.1): ``` >>> $("<img />", { height: 4 })[0].height 0 >>> $("<img />").attr({ height: 4 })[0].height 4 ``` So, they are some differences between the shorthand and the longer way..! Is this a bug or is it intentional? Are there any other ones with similar behaviour which I should watch out for?
2011/03/09
[ "https://Stackoverflow.com/questions/5248028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
From the [docs](http://api.jquery.com/jQuery/#jQuery2): > > As of jQuery 1.4, the second argument > can accept a map consisting of a > superset of the properties that can be > passed to the `.attr()` method. > Furthermore, any event type can be > passed in, and the following jQuery > methods can be called: val, css, html, > text, data, width, height, or offset. > > > So basically the snippet is not equivalent to `$("<img />").attr({ height: 4 })` but to `$("<img />").height(4)` and the html it evaluates to is `<img style="height: 4px" />` - hence the returned `0`.
753,813
I'm trying to lay out some images in code using addSubview, and they are not showing up. I created a class (myUIView) that subclasses UIView, and then changed the class of the nib file in IB to be myUIView. Then I put in the following code, but am still getting a blank grey screen. ``` - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // Initialization code [self setupSubviews]; } return self; } - (void)setupSubviews { self.backgroundColor = [UIColor blackColor]; UIImageView *black = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"black.png"]]; black.center = self.center; black.opaque = YES; [self addSubview:black]; [black release]; } ```
2009/04/15
[ "https://Stackoverflow.com/questions/753813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82780/" ]
yes, just implement initWithCoder. initWithFrame is called when a UIView is created dynamically, from code. a view that is loaded from a .nib file is always instantiated using initWithCoder, the coder takes care of reading the settings from the .nib file i took the habit to do the initialization in a separate method, implementing both initWithCode and initWithFrame (and my own initialization methods when required)
1,738,022
Assume M has only a countable or finite number of points and M is connected. Prove that every continuous function f:M->R is a constant function on all of M. Here is what I have so far: If f: M->R is continuous and M is connected then f(M) is connected in R. Hence f(M) is an interval because it is a connected subset of R. Since M has only a finite number of points, the only interval it can be mapped to is a single point, hence f is a constant function. I am confused how to go from f(M) being an interval to that actually meaning it is only a single point to prove that it is a constant function.
2016/04/11
[ "https://math.stackexchange.com/questions/1738022", "https://math.stackexchange.com", "https://math.stackexchange.com/users/317811/" ]
The cardinality of $f(M)$ is at most the cardinality of $M$, thus countable or finite. The only nonempty intervals of $\mathbb R$ that are countable or finite are singletons.
32,179,545
I have 2 input boxes for first name and last name of passengers travelling. There could be maximum 9 number of passengers. It is not allowed to have two passengers with same name(first and last combined) How can I check if none of the passenger have same names(first and last name combined) ``` <input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;"> ``` Thanks. **Edit:** I am not using a database to store the passenger names and the passengers are all entered on the same page.
2015/08/24
[ "https://Stackoverflow.com/questions/32179545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4895885/" ]
``` var name=[]; var sameName=false; for(var i=1;i<=<%=detailsModel.getNumberOfAdult()%>;i++) { var fullName = document.getElementById("adultFirstName"+i).value+" "+document.getElementById("adultLastName"+i).value name.push(fullName); } for(var i=1;i<=<%=detailsModel.getNumberOfChild()%>;i++) { var fullName = document.getElementById("childFirstName"+i).value+" "+document.getElementById("childLastName"+i).value name.push(fullName); } for(var i=1;i<=<%=detailsModel.getNumberOfInfant()%>;i++) { var fullName = document.getElementById("infantFirstName"+i).value+" "+document.getElementById("infantLastName"+i).value name.push(fullName); } for(var i=0;i<name.length;i++) { for(var j=i+1;j<name.length;j++) { if(name[i]==name[j]) { var sameName=true valid= false; } } } if(sameName==true) { $('#sameNameError').html('2 Passengers Cannot Have Same Name'); } else { $('#sameNameError').html(''); } ```
13,080,956
I have seen that it is possible but not easy to configure cross-compiling with Free Pascal, as there have to be libraries of the target OS on the system. But I only need a quick syntax-check to verify that the project can be compiled, linking an executable is not required. So: are there compiler options which I can use to do a **cross-platform test compile** (only) with Free Pascal? In my case, before checking in the project in source control, I would like to verify on a Windows workstation if the compiler can compile for a Linux or OSX target.
2012/10/26
[ "https://Stackoverflow.com/questions/13080956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80901/" ]
Do you ever call init for any instance of that class ? somewhere in your code you should have : ``` untitled *myObj = [[untitled alloc] init]; ``` If not, then this is the reason why it is not called.
41,922,466
I would like to automatically route to a login page if the user is not logged in. app.module.ts ============= ``` import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { DashBoardComponent} from './dashboard/dashboard.component'; import { NotFoundComponent } from './not-found/not-found.component'; const APPROUTES: Routes = [ {path: 'home', component: AppComponent}, {path: 'login', component: LoginComponent}, {path: 'dashboard', component: DashboardComponent}, {path: '**', component: NotFoundComponent} ]; @NgModule({ declarations: [ AppComponent, LoginComponent, DashboardComponent NotFoundComponent ], imports: [ BrowserModule, FormsModule, HttpModule, MaterialModule.forRoot(), RouterModule.forRoot(APPROUTES) ], providers: [], bootstrap: [AppComponent] }) ``` If the user isn't logged in, the `LoginComponent` should load, otherwise the `DashboardComponent`.
2017/01/29
[ "https://Stackoverflow.com/questions/41922466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6865232/" ]
Here are 3 ways to do what you asked, from least preferred to favorite: **Option 1. Imperatively redirect the user in `AppComponent`** ```ts @Component({ selector: 'app-root', template: `...` }) export class AppComponent { constructor(authService: AuthService, router: Router) { if (authService.isLoggedIn()) { router.navigate(['dashboard']); } } } ``` Not very good. It's better to keep the "login required" information in the route declaration where it belongs. **Option 2. Use a `CanActivate` guard** Add a `CanActivate` guard to all the routes that require the user to be logged in: ```ts const APPROUTES: Routes = [ {path: 'home', component: AppComponent, canActivate:[LoginActivate]}, {path: 'dashboard', component: DashBoardComponent, canActivate:[LoginActivate]}, {path: 'login', component: LoginComponent}, {path: '**', component: NotFoundComponent} ]; ``` My guard is called `LoginActivate`. For it to work I must add the guard to my module's `providers`. And then I need to implement it. In this example I'll use the guard to redirect the user if they're not logged in: ```ts @Injectable() export class LoginActivate implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean>|Promise<boolean>|boolean { if (!this.authService.isLoggedIn()) { this.router.navigate(['login']); } return true; } } ``` Check out the doc about route guards if this doesn't make sense: <https://angular.io/docs/ts/latest/guide/router.html#guards> This option is better but not super flexible. What if we need to check for other conditions than "logged in" such as the user permissions? What if we need to pass some parameter to the guard, like the name of a role "admin", "editor"...? **Option 3. Use the route `data` property** The best solution IMHO is to **add some metadata in the routes declaration** to indicate "this route requires that the user be logged in". We can use the route `data` property for that. It can hold arbitrary data and in this case I chose to include a `requiresLogin` flag that's either `true` or `false` (`false` will be the default if the flag is not defined): ```ts const APPROUTES: Routes = [ {path: 'home', component: AppComponent, data:{requiresLogin: true}}, {path: 'dashboard', component: DashBoardComponent, data:{requiresLogin: true}} ]; ``` Now the `data` property in itself doesn't do anything. But I can use it to enforce my "login required" logic. For that I need a `CanActivate` guard again. Too bad, you say. Now I need to add 2 things to each protected route: the metadata AND the guard... BUT: * You can attach the `CanActivate` guard to a top-level route and *it will be executed for all of its children routes* [TO BE CONFIRMED]. That way you only need to use the guard once. Of course, it only works if the routes to protect are all children of a parent route (that's not the case in Rafael Moura's example). * The `data` property allows us pass all kinds of parameters to the guard, e.g. the name of a specific role or permission to check, a number of points or credits that the user needs to possess to access the page, etc. Taking these remarks into account, it's best to rename the guard to something more generic like `AccessGuard`. I'll only show the piece of code where the guard retrieves the `data` attached to the route, as what you do inside the guard really depends on your situation: ```ts @Injectable() export class AccessGuard implements CanActivate { canActivate(route: ActivatedRouteSnapshot): Observable<boolean>|Promise<boolean>|boolean { const requiresLogin = route.data.requiresLogin || false; if (requiresLogin) { // Check that the user is logged in... } } } ``` For the above code to be executed, you need to have a route similar to: ```ts { path: 'home', component: AppComponent, data: { requiresLogin: true }, canActivate: [ AccessGuard ] } ``` NB. Don't forget to add `AccessGuard` to your module's `providers`.
28,470,591
I am trying to upload images to DB using below code, MyJsp.jsp ``` <form action="ImageUploadToDB" method="post" enctype="multipart/form-data"> <div> <img alt="Image1" id="Image11" src="" width="130px" height="90px" class="imgtotxt"><br><br> <input type="file" id="files11" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image"> <img alt="Image2" id="Image12" src="" width="130px" height="90px" class="imgtotxt"><br><br> <input type="file" id="files12" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image"> <img alt="Image3" id="Image13" src="" width="130px" height="90px" class="imgtotxt"><br><br> <input type="file" id="files13" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image"> <img alt="Image4" id="Image14" src="" width="130px" height="90px" class="imgtotxt"><br><br> <input type="file" id="files14" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image"> <img alt="Image5" id="Image15" src="" width="130px" height="90px" class="imgtotxt"><br><br> <input type="file" id="files15" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image"> </div> </form> ``` I am inserting all uploaded images from above form by using servlet like below, ``` final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload fileUpload = new ServletFileUpload(factory); List items = null; LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>(); if (ServletFileUpload.isMultipartContent(request)) { try { items = fileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } System.out.println("selected images :"+items); if (items != null) { final Iterator iter = items.iterator(); while (iter.hasNext()) { final FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { fileMap.put(item.getName(), item.getInputStream()); //System.out.println("uploaded images here:"+item.getName()); } } } } try { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root",""); Set<String> keySet = fileMap.keySet(); for (String fileName : keySet) { String sql ="INSERT INTO contacts2 (images) values (?)" ; PreparedStatement statement; statement = con.prepareStatement(sql); statement.setBlob(1, fileMap.get(fileName)); int row = statement.executeUpdate(); System.out.println("inserted successfully:"); } } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("errror is:"+e); } finally{ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ``` If i uploading such as images1.jpg, images2.jpg, images3.jpg, images4.jpg, images5.jpg then my output is : ``` inserted successfully: inserted successfully: inserted successfully: inserted successfully: inserted successfully: ``` But if i uploading such as images1.jpg, images2.jpg, images1.jpg, images4.jpg, images2.jpg then my output is : ``` inserted successfully: inserted successfully: inserted successfully: ``` when i check my DB there is image1.jpg, image2.jpg, image4.jpg only.I have no idea why that same name of images not inserting to DB. Someone tell me where i am wrong? Updated : This is for Mr.Keval's answer ``` fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream()); int count2 =5; for (int k=0;k<5;k++) { System.out.println("for successfully:"); String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ; PreparedStatement statement; statement = con.prepareStatement(sql); statement.setString(1, clas); statement.setString(2, subject); statement.setString(3, uid); System.out.println("Qimg name is:"+listGet.get(k)); statement.setString(4, listGet.get(k)); System.out.println("Qimg is:"+fileMap.values().toArray()[k]); Object bb = fileMap.values().toArray()[k]; // System.out.println("Qimg is:"+listGet2.get(listgetcount)); // System.out.println("finallyyyy:"+fileMap.get("files1")); statement.setBinaryStream(5, (InputStream) bb); // System.out.println("Aimg name is:"+listGet.get(count2)); statement.setString(6, listGet.get(count2)); //System.out.println("Aimg is:"+fileMap.values().toArray()[count2]); Object bb2 = fileMap.values().toArray()[count2]; //System.out.println("Qimg is:"+fileMap.get("files2")); //String getval2 = listGet2.get(count2); statement.setBinaryStream(7, (InputStream) bb2); int row = statement.executeUpdate(); System.out.println("inserted successfully:"); count2=count2+1; } ``` If i upload same images then shows like ``` for successfully: Qimg name is:image1.jpg Qimg is:java.io.FileInputStream@f747c0 inserted successfully: for successfully: Qimg name is:image4.jpg Qimg is:java.io.FileInputStream@fd4f30 inserted successfully: for successfully: Qimg name is:image5.jpg Qimg is:java.io.FileInputStream@1b654b9 inserted successfully: for successfully: Qimg name is:image7.jpg Qimg is:java.io.FileInputStream@1303c07 inserted successfully: for successfully: Qimg name is:image9.jpg Qimg is:java.io.FileInputStream@110b3f6 java.lang.ArrayIndexOutOfBoundsException: 9 ```
2015/02/12
[ "https://Stackoverflow.com/questions/28470591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3766129/" ]
Since you are using `LinkedHashMap` with the names of files as keys, when you add two files of the same name (two entries with the same key), the latter will replace the former. This is causing the entries with duplicate names to be replaced. Consider using an ArrayList of a class (that you create) containing the file name and the `InputStream` to store this data. Edit: my suggestion in code (untested) ``` final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload fileUpload = new ServletFileUpload(factory); List items = null; ArrayList<FileWithStream> fileMap = new ArrayList<FileWithStream>(); if (ServletFileUpload.isMultipartContent(request)) { try { items = fileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } System.out.println("selected images :"+items); if (items != null) { final Iterator iter = items.iterator(); while (iter.hasNext()) { final FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { fileMap.add(new FileWithStream(item.getName(), item.getInputStream())); //System.out.println("uploaded images here:"+item.getName()); } } } } try { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root",""); for (FileWithStream file : fileMap) { String sql ="INSERT INTO contacts2 (images) values (?)" ; PreparedStatement statement; statement = con.prepareStatement(sql); statement.setBlob(1, file.getStream()); int row = statement.executeUpdate(); System.out.println("inserted successfully:"); } } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("errror is:"+e); } finally{ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ``` with a class like: ``` public class FileWithStream { private String name; private InputStream stream; public FileWithStream(String name, InputStream stream) { this.name = name; this.stream = stream; } public String getName() { return name; } public InputStream getStream() { return stream; } } ```
29,533
I need to have a special class for example for body element which will be showing me on which site from multisite installation I am in. Here is a [solution](https://drupal.stackexchange.com/questions/17009/load-domain-specific-css-file-on-a-multisite) loading different css files but is there a way to have a simple class?
2012/04/27
[ "https://drupal.stackexchange.com/questions/29533", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/5551/" ]
Well i decided to use different .css files with this code: ``` // Allow a site-specific user defined CSS file (useful for multisite installations): // If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"), // it will be loaded after "local.css". SITE is the site's host name, without leading "www". // For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css" global $base_url; $site = preg_replace("/^[^\/]+[\/]+/", '', $base_url); $site = preg_replace("/[\/].+/", '', $site); $site = preg_replace("/^www[^.]*[.]/", '', $site); drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all'); ```
26,463,915
I have e.g. following `Lists`: ``` List<tst> listx; // tst object has properties: year, A, B, C, D year A B C D ------------ 2013 5 0 0 0 // list1 2014 3 0 0 0 2013 0 8 0 0 // list2 2014 0 1 0 0 2013 0 0 2 0 // list3 2014 0 0 3 0 2013 0 0 0 1 // list4 2014 0 0 0 5 ``` if I use `addAll` method, the `listTotal` will be: ``` year A B C D ------------ 2013 5 0 0 0 // listTotal 2014 3 0 0 0 2013 0 8 0 0 2014 0 1 0 0 2013 0 0 2 0 2014 0 0 3 0 2013 0 0 0 1 2014 0 0 0 5 ``` How to merge them to the `listRequired` which would be like this? ``` year A B C D ------------ 2013 5 8 2 1 // listRequired 2014 3 1 3 5 ```
2014/10/20
[ "https://Stackoverflow.com/questions/26463915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/731696/" ]
Use a `Map<Integer, Tst>` containing, for each year (the key of the map) the `Tst` you want for this year as a result. Iterate through your `listTotal` and, for each Tst: * if the year of the `Tst` isn't in the map yet, then store the `Tst` for this year * else, get the Tst from the map and merge it with the current Tst In the end, the `values()` of the map is what you want in your `listRequired`. Code: ``` Map<Integer, Tst> resultPerYear = new HashMap<>(); for (Tst tst : listTotal) { Tst resultForYear = resultPerYear.get(tst.getYear()); if (resultForYear == null) { resultPerYear.put(tst.getYear(), tst); } else { resultForYear.merge(tst); } } Set<Tst> result = resultPerYear.values(); ```
34,847,380
I'm using `AWS VPC` with `ELB` in-front. As far as i understand, only the `Network Access Control List (ACL)` can do the Inbound **Blocking**, by IPs. But again the problem there is: * The limitation of the number of Rules inside ACL. Which is only 40 max total. Again the Security Groups can not do "blocking". So what i do now is, to block the certain IPs by the Apache Virtual Hosts (handle the `x-forwarded-for` ips), which is not the clean approach. Then what is the proper approach to this please?
2016/01/18
[ "https://Stackoverflow.com/questions/34847380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/775856/" ]
Your success function is overwriting the whole `$scope` variable instead of placing values in it. You need to do the latter in order for anything to actually be accessible to your view: ``` success: function(results) { $scope.price = results.price; $scope.priceDescription = results.priceDescription; console.log($scope.price); console.log($scope.priceDescription); }, ```
25,887,511
Volley gives us better efficiency, however it uses the "url" ``` JsonObjectRequest j = new JsonObjectRequest((int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener); ``` But if I have to use HttpPost or HttpGet object as I have to set Header and Entity etc. How can I do it while still using Volley. ``` HttpGet httpGet = new HttpGet(url); httpGet.setHeader("String", "something" ); httpGet.setHeader("Content-Type","application/json"); ... httpPost.setEntity(new StringEntity("whatever")); ``` basically after these lines of code I get HttpPost / HttpGet object; is there a way to use this object in volley instead of using HttpClient to execute the request. Or is there a some different way to set header etc and then use it with Volley.
2014/09/17
[ "https://Stackoverflow.com/questions/25887511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174460/" ]
Create an ErrorController - this allows you to tailor your end-user error pages and status codes. Each action result accepts an exception which you can add to your route data in your application\_error method in your global.asax. It doesn't have to be the exception object, it can be anything you like - just add it to the routedata in your application\_error. ``` [AllowAnonymous] public class ErrorController : Controller { public ActionResult PageNotFound(Exception ex) { Response.StatusCode = 404; return View("Error", ex); } public ActionResult ServerError(Exception ex) { Response.StatusCode = 500; return View("Error", ex); } public ActionResult UnauthorisedRequest(Exception ex) { Response.StatusCode = 403; return View("Error", ex); } //Any other errors you want to specifically handle here. public ActionResult CatchAllUrls() { //throwing an exception here pushes the error through the Application_Error method for centralised handling/logging throw new HttpException(404, "The requested url " + Request.Url.ToString() + " was not found"); } } ``` Your Error View: ``` @model Exception @{ ViewBag.Title = "Error"; } <h2>Error</h2> @Model.Message ``` Add a route to catch all urls to the end of your route config - this captures all 404's that are not already caught by matching existing routes: ``` routes.MapRoute("CatchAllUrls", "{*url}", new { controller = "Error", action = "CatchAllUrls" }); ``` In your global.asax: ``` protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); //Error logging omitted HttpException httpException = exception as HttpException; RouteData routeData = new RouteData(); IController errorController = new Controllers.ErrorController(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("area", ""); routeData.Values.Add("ex", exception); if (httpException != null) { //this is a basic example of how you can choose to handle your errors based on http status codes. switch (httpException.GetHttpCode()) { case 404: Response.Clear(); // page not found routeData.Values.Add("action", "PageNotFound"); Server.ClearError(); // Call the controller with the route errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); break; case 500: // server error routeData.Values.Add("action", "ServerError"); Server.ClearError(); // Call the controller with the route errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); break; case 403: // server error routeData.Values.Add("action", "UnauthorisedRequest"); Server.ClearError(); // Call the controller with the route errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); break; //add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default. default: // server error routeData.Values.Add("action", "ServerError"); Server.ClearError(); // Call the controller with the route errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); break; } } //All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code else { routeData.Values.Add("action", "ServerError"); Server.ClearError(); // Call the controller with the route errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } } ``` Then when you throw ``` throw new HttpException(404, "Invoice 5 does not exist"); ``` your message will be carried through and displayed to the user. You can specify at this point which status code you want to use, and extend the switch statement in the application\_error.
27,026,866
I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python? ``` import Image import numpy as np im = Image.open("farm.jpg") col,row = im.size data = np.zeros((row*col, 5)) pixels = im.load() for i in range(row): for j in range(col): r,g,b = pixels[i,j] data[i*col + j,:] = r,g,b,i,j ```
2014/11/19
[ "https://Stackoverflow.com/questions/27026866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344013/" ]
I had to write this recently and ended up with ``` indices = np.dstack(np.indices(im.shape[:2])) data = np.concatenate((im, indices), axis=-1) ``` Where `im` is a numpy array. You are probably better off reading the images straight into numpy arrays with ``` from scipy.misc import imread im = imread("farm.jpg") ``` Or, better still if you have Scikit Image installed ``` from skimage.io import imread im = imread("farm.jpg") ```
15,072,038
Good morning everyone, I have a macro that I want to sort data. A button in my workbook calls a small userform with 10 checkboxes. The user should pick those categories that he wants to review and click sort. The result I want is for only the categories he chose to be displayed but I am getting an all or nothing result out of the attached macro. Below is that macro that supports the form/button to sort the categories. I have searched through Google and several other forums and can't find an answer relevant to my problem! Any help you could offer would be greatly appreciated. Thanks! ``` Private Sub cmdSort_Click() LastRow = Range("A" & Rows.Count).End(xlUp).Row If chkFE = True Then For Each cell In Range("BC4:BC" & LastRow) If UCase(cell.Value) <> "Fire Extinguishers" Then cell.EntireRow.Hidden = True End If Next End If If chkChem = True Then For Each cell In Range("BD4:BD" & LastRow) If UCase(cell.Value) <> "Chem" Then cell.EntireRow.Hidden = True End If Next End If If chkFL = True Then For Each cell In Range("BE4:BE" & LastRow) If UCase(cell.Value) <> "FL" Then cell.EntireRow.Hidden = True End If Next End If If chkElec = True Then For Each cell In Range("BF4:BF" & LastRow) If UCase(cell.Value) <> "Elec" Then cell.EntireRow.Hidden = True End If Next End If If chkFP = True Then For Each cell In Range("BG4:BG" & LastRow) If UCase(cell.Value) <> "FP" Then cell.EntireRow.Hidden = True End If Next End If If chkLift = True Then For Each cell In Range("BH4:BH" & LastRow) If UCase(cell.Value) <> "Lift" Then cell.EntireRow.Hidden = True End If Next End If If chkPPE = True Then For Each cell In Range("BI4:BI" & LastRow) If UCase(cell.Value) <> "PPE" Then cell.EntireRow.Hidden = True End If Next End If If chkPS = True Then For Each cell In Range("BJ4:BJ" & LastRow) If UCase(cell.Value) <> "PS" Then cell.EntireRow.Hidden = True End If Next End If If chkSTF = True Then For Each cell In Range("BK4:BK" & LastRow) If UCase(cell.Value) <> "STF" Then cell.EntireRow.Hidden = True End If Next End If If chkErgonomics = True Then For Each cell In Range("BL4:BL" & LastRow) If UCase(cell.Value) <> "Ergonomics" Then cell.EntireRow.Hidden = True End If Next End If Unload frmSort End Sub ```
2013/02/25
[ "https://Stackoverflow.com/questions/15072038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2030282/" ]
You are actually filtering, not sorting. Which raises the question, why not just let the user the Excel's `Filter` button and dialog? To answer your question, your code will only ever work if one `Checkbox` is checked. For every Checkbox that's checked your code is hiding the rows for all other categories. So only the category for the last Checkbox will have rows showing You could try reversing your logic. Start with all rows hidden, and set `Hidden = False` for any rows whose category is clicked.
45,294,027
I'm trying to select a specific sheet (by name or index) with my excel Add-In with no avail. My addin file `ThisAddIn.cs` has: ``` public Excel.Workbook GetActiveWorkbook() { return (Excel.Workbook)Application.ActiveWorkbook; } ``` And my `Ribbon1.cs` has: ``` namespace Test3 { public partial class Ribbon1 { private void Ribbon1_Load(object sender, RibbonUIEventArgs e) { Debug.WriteLine("Hello"); Workbook currentwb = Globals.ThisAddIn.GetActiveWorkbook(); Worksheet scratch = currentwb.Worksheets.Item[1] as Worksheet; // Error blocks here if (scratch == null) return; // Worksheet scratch = currentwb.Worksheets["Sheets1"]; scratch.Range["A1"].Value = "Hello"; } } } ``` But I get a `System.NullReferenceException: 'Object reference not set to an instance of an object.'` I'm new to c# (come from Python) and am very confused why this doesn't work. Any help would be greatly appreciated.
2017/07/25
[ "https://Stackoverflow.com/questions/45294027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3478500/" ]
It all has to do with what is in the accumulator (`high`). If you don't provide the second argument to `reduce`, the accumulator starts off as the first object, and the current element is the second element. In your first iteration, you treat the accumulator as the object, fetching the grade using `high.grade`; but then you return a number (`94`), and not an object, to be your next accumulator. In the next iteration of the loop, `high` is not an object any more but `94`, and `(94).grade` makes no sense. When you remove the third element, there is no second iteration, and there is no time for the bug to occur, and you get the value of the current accumulator (`94`). If there were only one element, you'd get the initial accumulator (`{name: 'Leah', grade: 94}`). This is, obviously, not ideal, as you can't reliably predict the shape of the result of your calculation (object, number or error). You need to decide whether you want the number or the object, one or the other. ``` let highest = students.reduce( (high, current) => Math.max(high, current.grade), Number.NEGATIVE_INFINITY ) ``` This variant keeps the accumulator as a number, and will return `94`. We can't rely on the default starting accumulator, as it needs to be a number, so we set it artificially at `-INF`. ``` let highest = students.reduce( (high, current) => high.grade > current.grade ? high : current, ) ``` This is the object version, where `highest` ends up with `{name: 'Leah', grade: 94}`.
10,422,174
I used ctrl-6 to jump between two files and compare these two files page by page, But each time when I switch back, the page content is changed. That is, a new page with previous cursor line in the middle of screen now is shown instead. Is there a way to keep the page position in the screen unchanged when I switched back. Thanks a lot!
2012/05/02
[ "https://Stackoverflow.com/questions/10422174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/724472/" ]
May I suggest using tabs (`C-PgUp` and `C-PgDn` to switch)? You can always start by doing `C-w``s``C-^``C-w``T` Otherwise see this odler answer of mine for hints on restoring cursor positions: * [After a :windo, how do I get the cursor back where it was?](https://stackoverflow.com/questions/9984032/after-a-windo-how-do-i-get-the-cursor-back-where-it-was/9989348#9989348) * [Vim buffer position change on window split (annoyance)](https://stackoverflow.com/questions/9625028/vim-buffer-position-change-on-window-split-annoyance/9626591#9626591)
54,840,020
I'm trying to display the info of the user when I get the id using `$routeParams.id`, I already displayed the user's info using texts only but how can I display the user's image using `img src`? **In my controller I did this to get the selected user.** ``` .controller('editbloodrequestCtrl', function($scope,$routeParams, Bloodrequest) { var app = this; Bloodrequest.getBloodrequest($routeParams.id).then(function(data) { if (data.data.success) { $scope.newLastname = data.data.bloodrequest.lastname; $scope.newFirstname = data.data.bloodrequest.firstname; $scope.newImg = data.data.bloodrequest.img; app.currentUser = data.data.bloodrequest._id; } else { app.errorMsg = data.data.message; } }); }); ``` **Now that I get the users info, I displayed this in my frontend** ``` <label>Lastname:</label> <input class="form-control" type="text" name="lastname" ng-model="newLastname"> <label>Firstname:</label> <input class="form-control" type="text" name="firstname" ng-model="newFirstname"> <label>Image:</label> <img src ="" name="img" ng-model="newImg"> //how can I display the image here? ``` **Sample Documents:** ``` {firstname:"James",lastname:"Reid",img:"random.jpg"} ``` **My output:** [![enter image description here](https://i.stack.imgur.com/EuXt2.png)](https://i.stack.imgur.com/EuXt2.png)
2019/02/23
[ "https://Stackoverflow.com/questions/54840020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7294541/" ]
No need to bind ng-model to your image, just use the src with the absolute path of the image ``` <img src ="{{newImg}}" name="img"> ```
16,480,300
at the moment I have script which prints out numeric values into bits so for example ``` print((short) 1); ``` I get a value of `00000001`, but how can I get for this a value like `00000001 00000000` and in case if I print `print((int) 1);` I get a value of `00000001 00000000 00000000 00000000`. Here is my code: ``` void printbyte(unsigned char x) { for (int i = 0; i < 8; i++) { if (x & 0x80) cout << 1; else cout << 0; x = x << 1; } cout << endl; } template <typename T> void print (T A) { unsigned char *p = (unsigned char *) &A; printbyte(*p); } int main() { print((short) 1); system("pause"); return 0; } ```
2013/05/10
[ "https://Stackoverflow.com/questions/16480300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2363241/" ]
You can just use `sizeof(T)` within `print` to determine how many bytes to process and then call `printbyte` for each byte, e.g. ``` #include <iostream> #include <climits> using namespace std; void printbyte(unsigned char x) { for (int i = 0; i < CHAR_BIT; i++) { cout << ((x & 0x80) != 0); x <<= 1; } } template <typename T> void print (T A) { for (size_t i = 0; i < sizeof(T); ++i) { unsigned char b = A >> ((sizeof(T) - i - 1) * CHAR_BIT); //unsigned char b = A >> (i * CHAR_BIT); // use this for little endian output printbyte(b); cout << " "; } cout << endl; } int main() { print((short) 1); print((long long) 42); return 0; } ```
12,511,202
I have Python 2.7.3 installed on RHEL 6, and when I tried to install pysvn-1.7.6, I got an error. What should I do? ``` /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/CXX/Python2/Objects.hxx:2912: warning: deprecated conversion from string constant to 'char*' Compile: pysvn_svnenv.cpp into pysvn_svnenv.o Compile: pysvn_profile.cpp into pysvn_profile.o Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/cxxsupport.cxx into cxxsupport.o Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/cxx_extensions.cxx into cxx_extensions.o Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/cxxextensions.c into cxxextensions.o Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/IndirectPythonInterface.cxx into IndirectPythonInterface.o Link pysvn/_pysvn_2_7.so make: *** No rule to make target `egg'. Stop. error: Not a URL, existing file, or requirement spec: 'dist/pysvn-1.7.6-py2.7-linux-x86_64.egg' ```
2012/09/20
[ "https://Stackoverflow.com/questions/12511202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1685704/" ]
I solved this problem, the reason is that i have made a mistake. i just executed the following command, it is not in the instruction. ``` python setup.py install ``` the installation steps are (**the Source is the dir name in pysvn directory**): ``` cd Source python setup.py configure make cd ../Tests make cd Source mkdir [YOUR PYTHON LIBDIR]/site-packages/pysvn cp pysvn/__init__.py [YOUR PYTHON LIBDIR]/site-packages/pysvn cp pysvn/_pysvn*.so [YOUR PYTHON LIBDIR]/site-packages/pysvn ```
4,244,321
in my application i am using array of button and i need to get the specified button which was pressed in the array. how to get. Note: not in table view
2010/11/22
[ "https://Stackoverflow.com/questions/4244321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489687/" ]
All UIViews have a integer `tag` property you can use to identify them. So in your button click handler (assuming it is the same function for all your buttons) you can get that tag and use it to differentiate between your buttons, e.g.: ``` -(void) myButtonClicked:(UIButton*)sender{ switch(sender.tag){ //Perform an action depending on button's tag ... } } ```
111,749
How might I implement a local HTTP server using either Java, C#, C or purely Mathematica? It should be able to respond with Mathematica input to GET and POST requests ideally on W7. This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server)
2016/04/03
[ "https://mathematica.stackexchange.com/questions/111749", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5615/" ]
The following guide shows how to conduct communication between [nanohttpd](https://github.com/NanoHttpd/nanohttpd), an http server for Java, and *Mathematica*. The result is a server that, if you go to its address in a web browser, displays the result of `SessionTime[]`, i.e. the time since the *Mathematica* kernel associated to the server started. I'm going to write as if the reader was using OS X with Maven installed because that is the operating system I am using, but this solution works on all operating systems with the proper, obvious, modifications. Directories and so on. On OS X Maven can be installed with [Brew](http://brew.sh/) using ``` brew -install maven ``` Getting up and running with nanohttpd: 1. Download the latest version of nanohttpd from [Github](https://github.com/NanoHttpd/nanohttpd/releases). 2. Follow the steps listed under "quickstart" on [nanohttpd.org](http://www.nanohttpd.org/) Add this to the top of the sample app among the other imports: ``` import com.wolfram.jlink.*; ``` Locate JLink.jar on your harddrive. On OS X it is located at ``` /Applications/Mathematica.app/SystemFiles/Links/JLink ``` Navigate to the app's directory and run the following command to include JLink.jar in the Maven project (with the appropriate modifications): ``` mvn install:install-file -Dfile=/Applications/Mathematica.app/Contents/SystemFiles/Links/JLink/JLink.jar -DgroupId=com.wolfram.jlink -DartifactId=JLink -Dversion=1.0 -Dpackaging=jar ``` And modify the app's pom.xml by adding the file as a dependency: ``` <dependency> <groupId>com.wolfram.jlink</groupId> <artifactId>JLink</artifactId> <version>1.0</version> </dependency> ``` Check that you can still compile the application and that it still works. Now if that's true, replace the code in App.java with this (see the sample program [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html)): ``` import java.io.IOException; import java.util.Map; import com.wolfram.jlink.*; import fi.iki.elonen.NanoHTTPD; public class App extends NanoHTTPD { KernelLink ml; public App() throws IOException { super(8888); start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); try { String jLinkDir = "/Applications/Mathematica.app/SystemFiles/Links/JLink"; System.setProperty("com.wolfram.jlink.libdir", jLinkDir); // http://forums.wolfram.com/mathgroup/archive/2008/Aug/msg00664.html ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname '\"/Applications/Mathematica.app/Contents/MacOS/MathKernel\" -mathlink'"); // Get rid of the initial InputNamePacket the kernel will send // when it is launched. ml.discardAnswer(); } catch (MathLinkException e) { throw new IOException("Fatal error opening link: " + e.getMessage()); } System.out.println("\nRunning! Point your browers to http://localhost:8888/ \n"); } public static void main(String[] args) { try { new App(); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); } } @Override public Response serve(IHTTPSession session) { String msg = "<html><body><p>"; try { ml.evaluate("SessionTime[]"); ml.waitForAnswer(); double result = ml.getDouble(); msg = msg + Double.toString(result); } catch (MathLinkException e) { msg = msg + "MathLinkException occurred: " + e.getMessage(); } msg = msg + "</p></body></html>"; return newFixedLengthResponse(msg); } } ``` Look up the line with `String jLinkDir =` and confirm that the directory is right. If you are using another operating system than OS X you also have to configure the line with `MathLinkFactory` in it. Information about that is available [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html). Compile the code and run it by (as you did before to run the sample app), navigating to the project's directory and executing the following commands: ``` mvcompile mvn exec:java -Dexec.mainClass="com.stackexchange.mathematica.App" ``` where you have edited mainClass appropriately. You now have an HTTP server on the address <http://localhost:8888/> that calls on a *Mathematica* kernel and uses its response to answer requests.
5,509,793
`Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window. ![Eclipse Environment Screenshot](https://i.stack.imgur.com/d5Yjj.png) I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session: ``` public static long longTryParse(String text, long fallbackValue) { try { return Long.parseLong(text); } catch (Exception e) { return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative. } } ``` So ... 1. Are these valid statements? 2. If so, why am I getting an exception? 3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session? Thanks!
2011/04/01
[ "https://Stackoverflow.com/questions/5509793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23566/" ]
> > Are these valid statements? > > > Yes ... taken as Java expressions in the context of a normal Java program. In the context of an Eclipse debugger's expression evaluator, I'm not sure. > > If so, why am I getting an exception? > > > I don't know for sure, but I suspect that it is something to do with the debugger itself. * One possibility is that you are using the expression evaluation functionality incorrectly. * Another possibility is that this is a bug in the Eclipse debugger, or a mismatch between the Eclipse debugger and the debug agent in the JVM. The one thing that I do know is that the `parseInt` and `parseLong` methods themselves don't throw `UnsupportedOperationException`. (In theory, they could because it is an unchecked exception. But I checked the source code for those 2 methods, and there's no way that the code could do that ... if executed in the normal way.) --- The Google query - "site:eclipse.org +UnsupportedOperationException JDI" - shows a lot of hits in the Eclipse issues database and newsgroups / mailing lists. In some cases, it looks like the problem is that the JDI / JNDI implementation for the target platform is incomplete. Could this be your problem? You mention you are doing Android development ...
123,318
I have a list 'choiceOpt' which contains a choice field 'choiceOptions' having Yes ad No as options. I want to retrieve this Yes and No programmatically (javascript) . Kindly help.
2014/12/05
[ "https://sharepoint.stackexchange.com/questions/123318", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/35506/" ]
After the first query that creates `Folder` object you could perform the `second` REST request: ``` http://<sitecollection>/<site>/_api/web/folders/getbyurl(folderrelativeurl)/listItemAllFields ``` to retrieve the associated `List Item` with a `Folder`. The following JavaScript example demonstrates that approach: ``` function executeJson(url,method,additionalHeaders,payload) { var headers = {}; headers["Accept"] = "application/json;odata=verbose"; if(method == "POST") { headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val(); } if (typeof additionalHeaders != 'undefined') { for(var key in additionalHeaders){ headers[key] = additionalHeaders[key]; } } var ajaxOptions = { url: url, type: method, contentType: "application/json;odata=verbose", headers: headers }; if(method == "POST") { ajaxOptions.data = JSON.stringify(payload); } return $.ajax(ajaxOptions); } function createFolder(webUrl,folderUrl) { var url = webUrl + "/_api/web/folders"; var folderPayload = { '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': folderUrl}; return executeJson(url,'POST',null,folderPayload).then(function(data){ var url = webUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/ListItemAllFields"; return executeJson(url,'GET'); }); } ``` Usage ``` createFolder(_spPageContextInfo.webAbsoluteUrl,'/Shared Documents/Archive') .done(function(data) { var folderItem = data.d; console.log(folderItem.Id); //print ListItem.Id property }) .fail( function(error){ console.log(JSON.stringify(error)); }); ```
1,647,927
For the sake of education, and programming practice, I'd like to write a simple library that can handle raw keyboard input, and output to the terminal in 'real time'. I'd like to stick with ansi C as much as possible, I just have no idea where to start something like this. I've done several google searches, and 99% of the results use libraries, or are for C++. I'd really like to get it working in windows, then port it to OSX when I have the time.
2009/10/30
[ "https://Stackoverflow.com/questions/1647927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/101946/" ]
Sticking with Standard C as much as possible is a good idea, but you are not going to get very far with your adopted task using just Standard C. The mechanisms to obtain characters from the terminal one at a time are inherently platform specific. For POSIX systems (MacOS X), look at the [`<termios.h>`](http://www.opengroup.org/onlinepubs/9699919799/basedefs/termios.h.html#tag_13_74) header. Older systems use a vast variety of headers and system calls to achieve similar effects. You'll have to decide whether you are going to do any special character handling, remembering that things like 'line kill' can appear at the end of the line and zap all the characters entered so far. For Windows, you'll need to delve into the WIN32 API - there is going to be essentially no commonality in the code between Unix and Windows, at least where you put the 'terminal' into character-by-character mode. Once you've got a mechanism to read single characters, you can manage common code - probably. Also, you'll need to worry about the differences between characters and the keys pressed. For example, to enter 'ï' on MacOS X, you type `option-u` and `i`. That's three key presses.
43,314
Is there a difference when the adverbs '*always, continually,forever,etc..*' are used with past simple and past progressive? For example : 1. He **always/ continually** worked there. 2. He was **always/ continually** working there. (What is the difference between the above two sentences?)
2014/12/17
[ "https://ell.stackexchange.com/questions/43314", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/10435/" ]
Let's say that a colleague mistakenly believes that Joe is a new hire. We might say: *Joe has always worked here.* to mean nothing more than the fact that Joe is not a new employee. He has been here for some while. If we want to say that Joe never slacked off when he was working at Acme Widgets, but always took his job seriously and gave it his best effort: *Joe was always working when he was at Acme Widgets.*
5,764,693
Only info I found was this: <http://forrst.com/posts/Node_js_Jade_Import_Jade_File-CZW> I replicated the suggested folder structure (views/partials) But it didn't work, as soon as I put ``` !=partial('header', {}) !=partial('menu', {}) ``` into index.jade, I get a blank screen, the error message I receive from jade is: > > ReferenceError: ./views/index.jade:3 > 1. 'p index' > > 2. '' > > 3. '!=partial(\'header', {})' > > > partial is not defined > > > I'd be very grateful for any help ! (I strongly prefer not to use express.js)
2011/04/23
[ "https://Stackoverflow.com/questions/5764693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335355/" ]
Jade has a command called include. Just use ``` include _form ``` given that the filename of the partial is \*\_form.jade\*, and is in the same directory
141,298
So hypothetically, if one was to buy krypton and wanted to make it glow, would a little tesla coil be enough to make it glow? If not, what would be enough? And would one be able to make it glow multiple times or just once, like will making it glow wear down the electrons in the noble gas or somethin’?
2020/10/09
[ "https://chemistry.stackexchange.com/questions/141298", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/99739/" ]
Great question! I don't believe it'll wear out in the short term. Light is produced when the electron is excited to a higher orbital and drops back down; this is completely reversible. Neon tubes work on the same principle and last for years! *Eventually* (probably after many years) a whole bunch of effects will probably kick in; if there's some impurities in the krypton, they might react with the plasma; the walls of the container will degrade and become opaque, etc. Whether a certain voltage will cause the krypton to glow seems to be a pretty complicated problem! I believe that would depend on the frequency of the tesla coil (V = dB/dT), how it's coupled to the gas (is there a wire in the tube?), and how large the volume of gas that you want to light.
49,288,411
I have a map with a lot of sprites. I could add a material to the sprite with diffuse shading and than add lots of lights. But that won't give me the result I want. And is performance heavy. --- Examples -------- In the first image you can see that light is generated by torches. It's expanding its light at its best through 'open spaces' and it is stopped by blocks fairly quickly. [![enter image description here](https://i.stack.imgur.com/8Sm4g.jpg)](https://i.stack.imgur.com/8Sm4g.jpg) --- Here is a great example of the top layer. We can see some kind of 2D directional light? Please note that the lighting inside the house is generated by torches again. The cave on the right side shows a better example of how light is handled. Also, note the hole in the background, this is generating some extra light into the cave. As if the light is really shining through the background there. [![enter image description here](https://i.stack.imgur.com/ibtqE.jpg)](https://i.stack.imgur.com/ibtqE.jpg) --- What I have ----------- You can clearly see the issue here. Lights increase their intensity. And light creates a squared edge around some of the tiles for some reason. Also, lots of lights will cause performance issues very quickly. [![enter image description here](https://i.stack.imgur.com/OZWtH.jpg)](https://i.stack.imgur.com/OZWtH.jpg) --- Raycasting? ----------- I read that you can somehow use raycasting? To target 'open space' or something? I have no experience with shaders or with lighting in games at all. I'd love a well-explained answer with how to achieve this Terraria/Starbound lighting effect. This does not mean I'm saying that raycasting is the solution. --- Minecraft --------- In Minecraft, light can travel for a certain amount of air blocks. It gradually fades to completely dark. In the Graphic settings you can enable `Smooth Lightning`, which will (obviously) smooth the lightning on the blocks. I guess this is done with shaders, but I'm not sure. My guess is that this is performance heavy. But I'm thinking about air blocks (which are gameobjects) and maybe I have the wrong logic. --- **Note:** I love a helpful answer, but please provide a link with a detailed explanation. Or provide an explanation with source code or links to the Unity docs in your answer. I wouldn't like to see theories worked out or something. I'd love to get an answer on how to implement this kind of lighting in Unity. I'd also like to know if it's possible to *NOT* use a package from the Unity Marketplace. --- Similar, but no good -------------------- Take a look at similar posts with links to articles that cover the basics of raycasting. But no explanation on how to implement this in Unity and not the Terraria/Starbound effect I'd like to achieve: [Make pixel lighting like terraria and starbound](https://stackoverflow.com/questions/41443130/make-pixel-lighting-like-terraria-and-starbound) [How to achieve Terraria/Starbound 2d lighting?](https://stackoverflow.com/questions/31736654/how-to-achieve-terraria-starbound-2d-lighting) --- Video impression ---------------- For example, take a look at this video for a really good impression on how 2d light works in Starbound: <https://www.youtube.com/watch?v=F5d-USf69SU> I know this is a bit more advanced, but also the point light generated by the player's flash light is stopped by blocks and let through by the open spaces. --- Other help forums ----------------- Also posted by me. **Gamedev Exchange:** <https://gamedev.stackexchange.com/questions/155440/unity-2d-shader-lighting-like-terraria-or-starbound> **Unity Forum:** <https://answers.unity.com/questions/1480518/2d-shader-lighting-like-terraria-or-starbound.html> ---
2018/03/14
[ "https://Stackoverflow.com/questions/49288411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6086226/" ]
I can mention 2 main elements about 2d Dynamic Lighting for unity. 1. One of the main asset used for 2d lighting in unity essentials is [DDL light](https://assetstore.unity.com/packages/tools/particles-effects/2ddl-pro-2d-dynamic-lights-and-shadows-25933), with an official tutorial [here](https://learn.unity.com/tutorial/recorded-video-session-2d-essentials-pack). 2. Most importantly Unity itself is working on a Dynamic lighting system, currently in beta (for 2019.2). Unity introduced the package Lightweight RP for 2d lights [here](https://forum.unity.com/threads/experimental-2d-lights-and-shader-graph-support-in-lwrp.683623/) and there's a tutorial [here](https://www.youtube.com/watch?v=nkgGyO9VG54).
18,059,797
Hi I am currently working with a report in Visual Studio 2008. I use the query below to create a data set. This works correctly in SQL / SMSS and in the dataset when I test the query. ``` SELECT CASE WHEN Make LIKE 'FO%' THEN 'Ford' WHEN Make LIKE 'HON%' THEN 'Honda' END Make, CASE WHEN model LIKE 'CIV%' THEN 'Civic' WHEN model LIKE '%AC%' THEN 'Accord' ELSE model END model, year, AVG(Fuel.MPG) as AVGMPG From cars, Fuel Where Fuel.ID=cars.ID AND year > 2003 AND Make is not NULL AND model is not NULL AND year is not NULL Group by Make, model, year ``` When I have a report reference the dataset it generates the following error; > > An error has occurred during report processing. Exception has been > thrown by the target of an invocation. Failed to enable constraints. > One or more rows contain values violating non-null, unique, or > foreign-key constraints. > > > Since the actual SQL statement is larger and involves several CASE statements, all of which work, I have narrowed it down to the else portion of the statement. For background, I am trying to pull all the data from model but group certain values that are similar, but still pull the rest of the data as well.
2013/08/05
[ "https://Stackoverflow.com/questions/18059797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1902937/" ]
The WHATWG (the organization who specifies browser behavior, alongside the W3C) has a [list of known script MIME types](http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#scriptingLanguages) and some blacklisted MIME types that must not be treated as scripting languages: > > The following lists the MIME type strings that user agents must recognize, and the languages to which they refer: > > > * `"application/ecmascript"` > * `"application/javascript"` > * `"application/x-ecmascript"` > * ... > > > The following MIME types (with or without parameters) must not be interpreted as scripting languages: > > > * `"text/plain"` > * `"text/xml"` > * `"application/octet-stream"` > * `"application/xml"` > > > Note: These types are explicitly listed here because they are poorly-defined types that are nonetheless likely to be used as formats for data blocks, and it would be problematic if they were suddenly to be interpreted as script by a user agent. > > > What the WHATWG spec calls "data blocks" here are **non-scripts** enclosed in `<script>` tags: > > In this example, two script elements are used. One embeds an external script, and the other includes some data. > > > ``` <script src="game-engine.js"></script> <script type="text/x-game-map">` ........U.........e o............A....e .....A.....AAA....e .A..AAA...AAAAA...e </script> ``` The components of the WHATWG spec that specify `load` events for `<script>` tags explicitly state that they fire for *scripts* referred to by `<script>` tags, not to non-script data blocks. A `<script>` element is a data block if its `type` is not recognized as a MIME type corresponding to a scripting language supported by the browser. This means that blacklisted types like `text/plain` will never be recognized as scripts, whereas type values in neither the must-support nor must-not-support list, like `application/dart` (for Google's Dart language) might be supported by some browsers. Furthermore, including a non-script `type` alongside a `src` is not spec-compliant. Data blocks are legal only when specified inline: > > When used to include data blocks (as opposed to scripts), the **data must be embedded inline**, the format of the data must be given using the `type` attribute, the **`src` attribute must not be specified**, and the contents of the script element must conform to the requirements defined for the format used. > > >
49,953,590
Quick Context: I have a basic excel Spreadsheet with three fields: Client\_URL, Client\_Name and AHREFs\_Rank. When a URL is entered into Client\_URL I want to: 1. Login to AHREFs; 2. Paste and enter the client URL into a web form field using the value of cell Client\_URL; 3. Pull the AHREF's Rank number for the inner text of a link. **I'm having trouble with step 3.** Here's the **full** code for Step 3 used so far, I'm experiencing "Compile Error: Object Required" issues. ``` Private Sub Worksheet_Change(ByVal Target As Range) If Target.Row = Range("Client_URL").Row And _ Target.Column = Range("Client_URL").Column Then Dim HTMLDoc As HTMLDocument Dim MyBrowser As InternetExplorer Dim MyHTML_Element As IHTMLElement Dim MyURL As String MyURL = "https://ahrefs.com/user/login" Set MyBrowser = New InternetExplorer MyBrowser.navigate MyURL MyBrowser.Visible = True Do Loop Until MyBrowser.readyState = READYSTATE_COMPLETE Set HTMLDoc = MyBrowser.document HTMLDoc.all.Email.Value = "[email protected]" HTMLDoc.all.Password.Value = "password123" For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input") If MyHTML_Element.Type = "submit" Then MyHTML_Element.Click: Exit For Next MyURL = "https://ahrefs.com/dashboard/metrics" MyBrowser.navigate MyURL Do Loop Until MyBrowser.readyState = READYSTATE_COMPLETE Set HTMLDoc = MyBrowser.document HTMLDoc.activeElement.Value = Range("Client_URL").Value HTMLDoc.getElementById("dashboard_start_analysing").Click Do DoEvents Loop Until MyBrowser.readyState = READYSTATE_COMPLETE Set HTMLDoc = MyBrowser.document Dim rankInnertext As Object rankInnertext = HTMLDoc.getElementById("topAhrefsRank").innerText MsgBox rankInnertext End If End Sub ``` If I remove the "Set" from "rankInnertext =" i then get a Runtime Error 91 "Object Variable Not Set". To break it down, in Step 3 I've: Submitted a field on a previous page and am waiting for the current page to finish loading. I'm then attempting to pull the inner text of a link with the ID "topAhrefsRank" and set the value of the cell "AHREFs\_Rank" to equal the value of the inner text as a string. > > Very new to visual basic so any help is appreciated. > > > Update: Changed code as per suggestions. Have changed rankInnertext from String to Object. Now receiving "Run Time Error 91: Object Variable or With block variable not set" > > >
2018/04/21
[ "https://Stackoverflow.com/questions/49953590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2613371/" ]
This helped me: ``` .fa { -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } ```
33,010,655
I just wanted to append `td` in the `tr` **Table** ``` <table class="u-full-width" id="result"> <thead> <tr> <th>Project Name</th> <th>Id</th> <th>Event</th> </tr> </thead> <tbody> <tr> <td>Dave Gamache</td> <td>26</td> <td>Male</td> </tr> </tbody> </table> ``` **Script** ``` // Receive Message socket.on('message', function(data){ console.log(data); var Project = data.project; var Id = data.id; var Event = data.event; var tr = document.createElement("tr"); var td1 = tr.appendChild(document.createElement('td')); var td2 = tr.appendChild(document.createElement('td')); var td3 = tr.appendChild(document.createElement('td')); td1.innerHTML = Project; td2.innerHTML = Id; td3.innerHTML = Event; document.getElementById("result").appendChild(td1, td2, td3); }); ``` I come up with this above code but this is not working means see the image... [![enter image description here](https://i.stack.imgur.com/1yOoJ.png)](https://i.stack.imgur.com/1yOoJ.png)
2015/10/08
[ "https://Stackoverflow.com/questions/33010655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The last line is wrong. You should append the `tr` to the table, not all the `td`s. ``` document.getElementById("result").appendChild(tr); ```
32,801,983
The backstory. In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them. To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with. In C++ i have made a similar function that returns the point in question. ``` struct point3D { double x,y,z; } point3D findIntersect(const vec3& vector1, const vec3& vector2) { // Do stuff... return point; } ``` The problem: I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point. Possible solutions I have looked at are: Write a separate function for the distance. A lot of extra work for when I want both of them. * Create a custom struct for this one function. *Seems a bit overkill.* * Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.* * Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.* * Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.* I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`. Does anyone have a more elegant solution to returning multiple values from a function?
2015/09/26
[ "https://Stackoverflow.com/questions/32801983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5380126/" ]
Since you don't want to define a custom struct or class, I assume that you want the return value to be only point. So, I suggest you to use an optional pointer argument, it's default value is NULL, and if it is not NULL you store the distance in the variable pointed by it. ``` point3D findIntersect(const vec3 &v1, const vec3 &v2, double *dist = NULL) { // ... if (dist) { // find the distance and store in *dist } return ... ; } ```
4,354,341
Could someone please help with the following jQuery ***I need all jQuery UI buttons that are not children of two tables #id1 and #id2 and not of classid=x*** What I have come up with so far is ``` $(":button(.ui-button .ui-widget):not(#table1 #table2):not(.MyCustomClass)") ``` but this doesnt seem to work... What am I missing?
2010/12/04
[ "https://Stackoverflow.com/questions/4354341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314661/" ]
I think you want: ``` $(':button.ui-button, :button.ui-widget').not('#table1 *, #table2 *').not('.MyCustomClass') ``` It's usually faster to break the qualifiers out of the selector.
4,253,815
i try to deserialize a json string with the help of gson. While gson.fromJson I get the following error: > > No-args constructor for class xyz; does not exist. Register an InstanceCreator with Gson for this type to fix this problem > > > I tried to work with an InstanceCreate but I didn't get this running. I hope you can help me. JSON String ``` [ { "prog": "Name1", "name": "Name2", "computername": "Name3", "date": "2010-11-20 19:39:55" }, { "prog": "Name1", "name": "Name2", "computername": "Name3", "date": "2010-11-20 12:38:12" } ``` ] according to gson I have to cut the first and last chars ("[" and "]") according to <http://www.jsonlint.com/> the string is with the chars correct... :?: the code looks like that: ``` public class License { public String prog; public String name; public String computername; public String date; public License() { this.computername = ""; this.date = ""; this.name = ""; this.prog = ""; // no-args constructor } } ``` --- ``` String JSONSerializedResources = "json_string_from_above" try { GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); JSONObject j; License[] lic = null; j = new JSONObject(JSONSerializedResources); lic = gson.fromJson(j.toString(), License[].class); for (License license : lic) { Toast.makeText(getApplicationContext(), license.name + " - " + license.date, Toast.LENGTH_SHORT).show(); } } catch(Exception e) { Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } ``` regards Chris
2010/11/23
[ "https://Stackoverflow.com/questions/4253815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/517123/" ]
Try making your constructor public, so that gson can actually access it. ``` public License() { this.computername = ""; this.date = ""; this.name = ""; this.prog = ""; // no-args constructor } ``` but since Java creates a default constructor, you could just use: ``` public class License { public String prog = ""; public String name = ""; public String computername = ""; public String date = ""; } ``` **Update:** It's really quite trivial: `JSONObject` expects a Json object "{..}". You should use `JSONArray` which expects "[...]". I tried it and it works. You should still change `License` class as noted above.
52,324,863
For example, turn this: ``` const enums = { ip: 'ip', er: 'er' }; const obj = { somethingNotNeeded: {...}, er: [ { a: 1}, { b: 2} ], somethingElseNotNeeded: {...}, ip: [ { a: 1}, { b: 2} ] } ``` Into this: ``` [ { a: 1}, { b: 2}, { a: 1}, { b: 2} ] ``` I'm already doing this in a roundabout way by declaring an enum object of the types i want (er, ip) then doing a forEach (lodash) loop on obj checking if the keys aren't in the enum and delete them off the original obj. Then having just the objects I want, I do two nested forEach loops concatenating the results to a new object using object rest spread... I'm almost entirely sure there's a better way of doing this but I didn't think of it today.
2018/09/14
[ "https://Stackoverflow.com/questions/52324863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391600/" ]
Get the `enums` properties with [`Object.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values) (or [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) if they are always identical). Use [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to iterate the array of property names, and extract their values from `obj`. Flatten the array of arrays by [spreading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) it into [`Array.concat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat): ```js const enums = { ip: 'ip', er: 'er' }; const obj = { somethingNotNeeded: {}, er: [ { a: 1}, { b: 2} ], somethingElseNotNeeded: {}, ip: [ { a: 1}, { b: 2} ] }; const result = [].concat(...Object.values(enums).map(p => obj[p])); console.log(result); ```
55,094,997
I want to export outlook **NON-HTML Email Body** into excel with a click of a button inside excel. Below are my codes. Appreciate if anyone could assist me on this. This is the code that I use to print the **plain text email body** but I get a lot of unwanted text > > sText = **StrConv(OutlookMail.RTFBody, vbUnicode)** > > > Range("D3").Offset(i, 0).Value = **sText** > > > [![Output Example](https://i.stack.imgur.com/lkGQX.png)](https://i.stack.imgur.com/lkGQX.png) I did tried this but it prompts **run-time error '1004' Application-defined or object-defined error** It works on body with HTML tags though. > > Range("D3").Offset(i, 0).Value = **OutlookMail.Body** > > > This is the structure of my email folders [![My email folders](https://i.stack.imgur.com/ANckj.png)](https://i.stack.imgur.com/ANckj.png) Below are my complete vba codes ``` Sub extract_email() Dim OutlookApp As New Outlook.Application Dim Folder As Outlook.MAPIFolder Dim OutlookMail As MailItem Dim sText As String Dim i As Integer Set myAccount = OutlookApp.GetNamespace("MAPI") Set Folder = myAccount.GetDefaultFolder(olFolderInbox).Parent Set Folder = Folder.Folders("Test_Main").Folders("Test_Sub") i = 1 Range("A4:D20").Clear For Each OutlookMail In Folder.Items If OutlookMail.ReceivedTime >= Range("B1").Value And OutlookMail.SenderName = "Test_Admin" Then Range("A3").Offset(i, 0).Value = OutlookMail.Subject Range("A3").Offset(i, 0).Columns.AutoFit Range("A3").Offset(i, 0).VerticalAlignment = xlTop Range("B3").Offset(i, 0).Value = OutlookMail.ReceivedTime Range("B3").Offset(i, 0).Columns.AutoFit Range("B3").Offset(i, 0).VerticalAlignment = xlTop Range("C3").Offset(i, 0).Value = OutlookMail.SenderName Range("C3").Offset(i, 0).Columns.AutoFit sText = StrConv(OutlookMail.RTFBody, vbUnicode) Range("D3").Offset(i, 0).Value = sText Range("D3").Offset(i, 0).Columns.AutoFit Range("D3").Offset(i, 0).VerticalAlignment = xlTop i = i + 1 End If Next OutlookMail Set Folder = Nothing End Sub ```
2019/03/11
[ "https://Stackoverflow.com/questions/55094997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10954825/" ]
An email can have several bodies or none. Outlook recognises text, Html and RTF bodies. No email I have examined in recent years contained a RTF body. Once it was the only option if you wanted to format your message. Today, Html and CSS offer far more functionality than RTF and I doubt if any smartphone accepts RTF. I am surprised you are receiving an email with a RTF body; my guess it is from a legacy system. Ignoring RTF, if an email has an Html body, that is what is displayed to the user. Only if there is no Html body, will the user see the text body. Of the emails I have examined, all have both a text and an Html body. Almost all of those text bodies are the Html body with every tag replaced by a carriage return and a linefeed. Since CRLF as newline is a Windows convention, I suspect if an email has no text body, Outlook is creating one from the Html body for the benefit of macros that want to process a text body. If my theory is correct, Outlook is not doing the same for an email that only contains a RTF email. Hence, you have a text body if there is an Html body but not if there is a RTF body. The specification for Microsoft’s RTF is available online so you could research the format if you wish. If you search for “Can I process RTF from VBA?”, you will find lots of suggestions which you might find interesting. Alternatively, the example RTF body you show looks simple: ``` {string of RTF commands{string of RTF commands}} {string of RTF commands ending in “1033 ”text\par text\par text\par } ``` If you deleted everything up to “1033 ” and the trailing “}” then replaced “\par” by “”, you might get what you want. I have issues with your VBA. For example: Not all items in Inbox are MailItems. You should have: ``` For Each OutlookMail In Folder.Items If OutlookMail.Class = olMail Then If OutlookMail.ReceivedTime ... Then : : : End If End If ``` You do not need to format cells individually. The following at the bottom would handle the AutoFit and vertical alignment: ``` Cells.Columns.Autofit Cells.VerticalAlignment = xlTop ``` Your code operates on the active worksheet. This relies on the user having the correct worksheet active when the macro is started. You should name the target worksheet to avoid errors.
8,832,464
I can target all browsers using this code: ``` <link rel="stylesheet" media="screen and (min-device-width: 1024px)" href="large.css"/> <link rel='stylesheet' media='screen and (min-width: 1023px) and (max-width: 1025px)' href='medium.css' /> <link rel='stylesheet' media="screen and (min-width: 419px) and (max-width: 1023px)" href='small.css' /> ``` But media query design does not work on old versions of IE, so I have a problem with that browser as usual.
2012/01/12
[ "https://Stackoverflow.com/questions/8832464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/771291/" ]
Use this jQuery snipet to set a class on the BODY tag: ``` $(document).ready(function(){ var width = $(window).width(); var class = 'small'; if(width > 1024) { class = 'large'; } else if(width > 1023 && width < 1025) { class = 'medium'; } $('body').addClass(class); }); ``` With appropriate class (large/medium/small) on your BODY you are able to write CSS like this: ``` body.large p {font-size: 25px}; body.medium p {font-size: 20px}; body.small p {font-size: 15px}; ``` etc.
1,125,931
The spherical Bessel equation is: $$x^2y'' + 2xy' + (x^2 - \frac{5}{16})y = 0$$ If I seek a Frobenius series solution, I will have: \begin{align\*} &\quad y = \sum\_{n = 0}^{\infty} a\_nx^{n + r} \\ &\implies y' = \sum\_{n = 0}^{\infty} (n + r)a\_nx^{n + r - 1} \\ &\implies y'' = \sum\_{n = 0}^{\infty} (n + r)(n + r - 1)a\_nx^{n + r - 2} \end{align\*} Substituting into the ODE of interest: \begin{align\*} &\quad x^2y'' + 2xy' + (x^2 - \frac{5}{16})y = 0 \\ &\equiv \sum\_{n = 0}^{\infty} (n + r)(n + r - 1)a\_nx^{n + r} + \sum\_{n = 0}^{\infty} 2(n + r)a\_nx^{n + r} + \sum\_{n = 0}^{\infty} a\_nx^{n + r + 2} + \sum\_{n = 0}^{\infty} \frac{-5}{16}a\_nx^{n + r} = 0 \\ &\equiv \sum\_{n = 0}^{\infty} [(n + r)(n + r - 1) + 2(n + r) - \frac{5}{16}]a\_nx^{n + r} + \sum\_{n = 2}^{\infty} a\_{n - 2}x^{n + r} = 0 \\ &\equiv [r(r-1) + 2r - (5/16)]a\_0 + [(r+1)(r) + 2(r+1) - (5/16)]a\_1 + \\ &\quad \sum\_{n = 2}^{\infty} ([(n + r)(n + r - 1) + 2(n + r) - \frac{5}{16}]a\_n + a\_{n-2})x^{n + r} = 0 \\ &\implies [r(r-1) + 2r - (5/16)] = 0 \wedge \\ &\quad [(r+1)(r) + 2(r+1) - (5/16)] = 0 \wedge \\ &\quad [(n + r)(n + r - 1) + 2(n + r) - \frac{5}{16}]a\_n + a\_{n-2} = 0 \end{align\*} The first conjunct is the standard indicial equation specifying $r$. The second conjunct is yet another quadratic that $r$ has to satisfy. Is there a mistake? Or should $a\_1 = 0$?
2015/01/30
[ "https://math.stackexchange.com/questions/1125931", "https://math.stackexchange.com", "https://math.stackexchange.com/users/115703/" ]
The main indicial is the the first equation. You get two roots from the first equation so you should set $a\_1=0$. If there is a common root between the first and second equations, then you can consider that root and set both $a\_1$ and $a\_0$ nonzero.
19,846,817
It seems like `require` calls are executed asynchronously, allowing program flow to continue around them. This is problematic when I'm trying to use a value set within a `require` call as a return value. For instance: main.js: ``` $(document).ready(function() { requirejs.config({ baseUrl: 'js' }); requirejs(['other1'], function(other1) { console.log(other1.test()); //logs out 'firstValue', where I would expect 'secondValue' } }); ``` other1.js ``` function test() { var returnValue = 'firstValue'; //this is what is actually returned, despite the reassignment below... requirejs(['other2'], function(other2) { other2.doSomething(); returnValue = 'secondValue'; //this is what I really want returned }) return returnValue; } if(typeof module != 'undefined') { module.exports.test = test; } if(typeof define != 'undefined') { define({ 'test':test }); } ``` How can I set a return value for a function from inside a `require` block?
2013/11/07
[ "https://Stackoverflow.com/questions/19846817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1040915/" ]
Yes, require calls are executed `asynchronously`. So your example won't work, because ``` function test() { var returnValue = 'firstValue'; requirejs(['other2'], function(other2) { // <-- ASYNC CALL other2.doSomething(); returnValue = 'secondValue'; }) return returnValue; // <-- RETURNS FIRST! ('firstValue') } ``` The only thing you need to do in your example is: **main.js** ``` requirejs.config({ baseUrl: 'js' }); requirejs(['other1'], function(other1) { console.log(other1.test()) }); ``` **js/other2.js** ``` // No dependencies define(function() { return { doSomething: function() { return 'secondValue'; } }; }); ``` **js/other1.js** ``` // Dependency to other2.js define(['other2'], function(other2) { return { test: function() { return other2.doSomething(); } }; }); ``` See complete example here: <http://plnkr.co/edit/hRjX4k?p=preview>
57,215,753
I have a link that is placed in `li` and when you hover on it, a block should appear with links that I will indicate in it ``` <li id="dropdown" class="li"> <a href="/news/">Lessons</a> </li> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> ```
2019/07/26
[ "https://Stackoverflow.com/questions/57215753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11714641/" ]
In this case, you don't have to declare `global`. Simply indent your `submitBtn` function inside `entry_Fn`: ``` def entry_Fn(): level_1 = Toplevel(root) Label( level_1, text = "level one").pack() entry_1 = Entry(level_1) entry_1.pack() entry_2 = Entry(level_1) entry_2.pack() def submitBtn(): val_1= entry_1.get() val_2= entry_2.get() sum_var.set(int(val_1)+ int(val_2)) level_1.destroy() Button(level_1, text= "submit", command=submitBtn).pack() ``` But generally it is easier to make a class so you can avoid this kind of scope problems, like below: ``` from tkinter import * class GUI(Tk): def __init__(self): super().__init__() self.geometry('600x400') self.sum_var= StringVar() Label(self, text="Main window").pack() Button(self, text="To enter Data", command=self.entry_Fn).pack() sum = Label(self, textvariable=self.sum_var) sum.pack() def entry_Fn(self): self.level_1 = Toplevel(self) Label(self.level_1, text = "level one").pack() self.entry_1 = Entry(self.level_1) self.entry_1.pack() self.entry_2 = Entry(self.level_1) self.entry_2.pack() Button(self.level_1, text="submit", command=self.submitBtn).pack() def submitBtn(self): val_1 = self.entry_1.get() val_2 = self.entry_2.get() self.sum_var.set(int(val_1)+ int(val_2)) self.level_1.destroy() root = GUI() root.mainloop() ```
53,874
I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly? Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song. I know there is no exact answer but I would like to know what you think so I can silence my conscience :)
2017/02/28
[ "https://music.stackexchange.com/questions/53874", "https://music.stackexchange.com", "https://music.stackexchange.com/users/37313/" ]
I would expect that the musicians in top bands play extremely consistently, due to sheer repetition and the fact that it's their career. However, your question touches on a trickier idea: What exactly is a "mistake"? If the exact notes and rhythms are prescribed, then any deviation from that clearly constitutes a mistake. But how precise does the timing/tempo need to be for the rhythm to be considered correct? What if it's technically correct, but a bit off stylistically or emotionally? What if something is "supposed" to ring out, but the fretting was a bit off and a note got partially dampened? And what if the music is improvised? From the listener's perspective: would you rather listen to a solo that was beautiful but had a wrong note, or one that was technically perfect but soulless? Anecdotally, my favorite rendition of a Debussy piano piece has a blatant key signature mistake in it\*, but it's still my favorite due to every other aspect of the performance. My old piano teacher tells a story of performing a section of a Bartok piece in the wrong *clef*, and people still enjoyed it. The whole idea of perfection and mistakes is not very well defined, and in performance art it must be that way. Ultimately, the question is not whether or not a performance was "perfect", but whether or not it was enjoyable and conveyed whatever it was supposed to. --- \* For the curious: [Van Cliburn's recording of Jardins sous la pluie](https://www.youtube.com/watch?v=m8rXQCewQjA). The section in C# in the middle, he misses B# in the melody each time.
60,145,379
I have this issue when trying to read my data which is json encoded from the php page to the swift page. this is the code I am using ``` import Foundation protocol HomeModelProtocol: class { func itemsDownloaded(items: NSArray) } class HomeModel: NSObject, URLSessionDataDelegate { //properties weak var delegate: HomeModelProtocol! var data = Data() let urlPath: String = "http://localhost/service.php" //this will be changed to the path where service.php lives func downloadItems() { let url: URL = URL(string: urlPath)! let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default) let task = defaultSession.dataTask(with: url) { (data, response, error) in if error != nil { print("Failed to download data") }else { print("Data downloaded") // this work fine self.parseJSON(data!) } } task.resume() } func parseJSON(_ data:Data) { var jsonResult = NSArray() print(jsonResult) // this print empty parentheses print(String(data: data, encoding: .utf8)) // this prints out the array //the code below throughs an arror do{ jsonResult = try JSONSerialization.jsonObject(with:data, options:JSONSerialization.ReadingOptions.allowFragments) as! [NSArray] as NSArray print(jsonResult) } catch let error as NSError { print(error) } var jsonElement = NSDictionary() let locations = NSMutableArray() for i in 0 ..< jsonResult.count { jsonElement = jsonResult[i] as! NSDictionary let location = LocationModel() //the following insures none of the JsonElement values are nil through optional binding if let name = jsonElement["Name"] as? String, let address = jsonElement["Address"] as? String, let latitude = jsonElement["Latitude"] as? String, let longitude = jsonElement["Longitude"] as? String { location.name = name location.address = address location.latitude = latitude location.longitude = longitude } locations.add(location) } DispatchQueue.main.async(execute: { () -> Void in self.delegate.itemsDownloaded(items: locations) }) } } ``` this is the output which I am receiving: ``` Data downloaded ( ) Optional(" \nconnectedinside[{\"name\":\"One\",\"add\":\"One\",\"lat\":\"1\",\"long\":\"1\"},{\"name\":\"Two\",\"add\":\"Two\",\"lat\":\"2\",\"long\":\"2\"},{\"name\":\"One\",\"add\":\"One\",\"lat\":\"1\",\"long\":\"1\"},{\"name\":\"Two\",\"add\":\"Two\",\"lat\":\"2\",\"long\":\"2\"}]") ``` > > Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around > character 2." UserInfo={NSDebugDescription=Invalid value around > character 2.} > > >
2020/02/10
[ "https://Stackoverflow.com/questions/60145379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6024981/" ]
You get this error, because the json response you receive is not an array but a dictionary. EDIT: as pointed out in a comment, you first need to fix your json response in your php code. There is ":" missing after "connectedinside". It should look like this: `{\"connectedinside\":[{\"name\":\"One\",\"add\":"One",...},...]}` My suggestion to fix this: You should have two models: ``` struct HomeModelResponse: Codable { let connectedinside: [LocationModel] } // your LocationModel should look like this: struct LocationModel: Codable { let name: String let add: String let lat: String let long: String } ``` And change your JSONDecoding code to: ``` do { jsonResult = try? JSONDecoder().decode(HomeModelResponse.self, from: data) print() } catch let exception { print("received exception while decoding: \(exception)" } ``` Then you can access your LocationModels by jsonResult.connectedinside
25,879,652
Is there a way in Eclipse to easily find all appearances of a variable in a file without having to manually search (CTRL + F) for it?
2014/09/16
[ "https://Stackoverflow.com/questions/25879652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3284878/" ]
with the cursor on the variable, press ctrl-shift-g. Works for variables, classes, methods, works across the entire project. If you just click on the variable, eclipse will highlight all uses of the variable in the current file, and mark the scrollbar with the places that are highlighted.
30,877,355
I want to change the 'csproj' file of my unity project in order to be able to access a specific library as [this](https://stackoverflow.com/questions/5694/the-imported-project-c-microsoft-csharp-targets-was-not-found) answer sugests. I am manually editing the file but every time i reload the project, the 'csproj' file returns to it's initial state. Is this a common issue? Is there a way to avoid this and change the file permanently? --- EDIT: My goal is to use **CSharpCodeProvider** so if there is another way of doing it without changing the 'csproj' file, i will gladly adopt the approach
2015/06/16
[ "https://Stackoverflow.com/questions/30877355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1754152/" ]
As far as I know, you cannot prevent Unity from overwriting your csproj files upon recompilation of your scripts. When working with larger code bases and Unity3D I tend to put most of my code into separate .Net assemblies (DLLs). This helps me when I'm sharing code between multiple projects and game servers, and Unity doesn't need to compile all scripts when it detects changes. To do that fire up your .Net IDE of choice and create a new *class library* project (which will output a .dll). Make sure it is targeting the **.Net Framework 3.5** or lower. Then, you copy the output .dll into you Unity project's *Assets* folder in a post-build step. I like to use a post-build step to prevent me from forgetting to copy the assembly after a change. DLLs in the project's *Assets* folder are automatically referenced by Unity when it creates its C# projects. This means all of the containing code can be used from within your scripts. Note, though, that the other way around will not work as easily: you cannot use code from Unity scripts in your separate project. Depending on what exactly you want to do with [CSharpCodeProvider](https://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider(v=vs.110).aspx) you can put your generation logic (and the necessary `Import` directive) into such a separate project. Edit: For more information how we set up our project structure you can watch [this talk](https://www.youtube.com/watch?v=ndt1crp9i7M) by the lead programmer on Jagged Alliance Online from Unite11.
3,784,607
**Purpose of the app:** A simple app that draws a circle for every touch recognised on the screen and follows the touch events. On a 'high pressure reading' `getPressure (int pointerIndex)` the colour of the circle will change and the radius will increase. Additionally the touch ID with `getPointerId (int pointerIndex)`, x- and y-coordinates and pressure are shown next to the finger touch. Following a code snipplet of the important part (please forgive me it is not the nicest code ;) I know) ``` protected void onDraw(Canvas canvas){ //draw circle only when finger(s) is on screen and moves if(iTouchAction == (MotionEvent.ACTION_MOVE)){ int x,y; float pressure; //Draw circle for every touch for (int i = 0; i < touchEvent.getPointerCount(); i++){ x = (int)touchEvent.getX(i); y = (int)touchEvent.getY(i); pressure = touchEvent.getPressure(i); //High pressure if (pressure > 0.25){ canvas.drawCircle(x, y, z+30, pressureColor); canvas.drawText(""+touchEvent.getPointerId(i)+" | "+x+"/"+y, x+90, y-80, touchColor); canvas.drawText(""+pressure, x+90, y-55, pressureColor); }else{ //normal touch event canvas.drawCircle(x, y, z, touchColor); canvas.drawText(""+touchEvent.getPointerId(i)+" | "+x+"/"+y, x+60, y-50, touchColor); canvas.drawText(""+pressure, x+60, y-25, pressureColor); } } } } ``` **The problem:** A HTC Desire running Android 2.1 is the test platform. The app works fine and tracks two finger without a problem. But it seems that the two touch points interfere with each other when they get t0o close -- it looks like they circles 'snap'to a shared x and y axle. Sometimes they even swap the input coordinates of the other touch event. Another problem is that even though `getPressure (int pointerIndex)` refers to an PointerID both touch event have the same pressure reading. As this is all a bit abstract, find a video here: <http://www.youtube.com/watch?v=bFxjFexrclU> **My question:** 1. Is my code just simply wrong? 2. Does Android 2.1 not handle the touch events well enough get things mixed up? 3. Is this a hardware problem and has nothing to do with 1) and 2)? Thank you for answers and/or relinks to other thread (sorry could find one that address this problem). Chris
2010/09/24
[ "https://Stackoverflow.com/questions/3784607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400022/" ]
I hate to tell you this, but it's your hardware. The touch panel used in the Nexus One (which I believe is the same hardware used in the HTC Desire) is known for this particular artifact. We did some work to alleviate the "jumps to other finger's axis" problem around the ACTION\_POINTER\_UP/DOWN events for Android 2.2 by dropping some detectable bad events, but the problem still persists when the pointers get close along one axis. This panel is also known for randomly reversing X and Y coordinate data; two points (x0, y0) and (x1, y1) become (x0, y1) and (x1, y0). Sadly there's only so much you can do when the "real" data is gone by the time Android itself gets hold of it. This isn't the only panel in the wild that has dodgy multitouch capabilities. To tell at runtime if you have a screen capable of precise multitouch data reporting without issues like this, use PackageManager to check for [`FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT`](http://d.android.com/reference/android/content/pm/PackageManager.html#FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT). If you don't have this feature available you can still do simple things like scale gestures reliably.
69,903
How do you cite a background map layer that is used in ArcMap that is retrieved from ArcGIS Online? For example the background layer is suppose to be credited from the U.S. Geological Survey and in the description it was digitized from the U.S. Geological Survey Professional Paper 1183.
2013/08/27
[ "https://gis.stackexchange.com/questions/69903", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/21471/" ]
According to the help topic ["Defining parameter data types in a Python toolbox"](http://resources.arcgis.com/en/help/main/10.1/index.html#/Defining_parameter_data_types_in_a_Python_toolbox/001500000035000000/), you should use `"DEFeatureClass"`.
321,417
In the following passage, I know here the word "authority" should not be the meaning: "political or administrative power and control", it's not suitable in this context. May be, I think the meaning of it will be "tradition or rite and ritual". I'm not sure. how should I understand this phrase "Blind faith in authority" or the word "authority"? The contexts: > > Inasmuch as the Buddha teaches that all genuine progress on the path of virtue is necessarily dependent upon one’s own understanding and insight, all dogmatism is excluded from the Buddha’s teaching. Blind faith in **authority** is rejected by the Buddha, and is entirely opposed to the spirit of his teaching. > > > "Fundamentals of Buddhism" by Nyanatiloka Mahåthera, Page. 5
2022/08/22
[ "https://ell.stackexchange.com/questions/321417", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/150477/" ]
It doesn't mean quite either of those things. It means "somebody or something outside you telling you the answers or what to do". It's sense 4 at [Wiktionary](https://en.wiktionary.org/wiki/authority#Noun): > > Status as a trustworthy source of information, reputation for mastery or expertise; or claim to such status or reputation. > > >
42,233,888
I'm dealing with the behemoth that is the AWS IAM permissions system. There are so many options that it can be extremely difficult to pinpoint which permissions are missing/too restrictive. The documentation in <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policy-structure.html#check-required-permissions> describes a seemingly-useful flag that can be added to cli commands. Unfortunately, it doesn't appear to work. Am I missing something? ``` aws --version aws-cli/1.11.47 Python/2.7.12 Linux/3.4.0+ botocore/1.5.10 ```
2017/02/14
[ "https://Stackoverflow.com/questions/42233888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477438/" ]
That's from the old ec2 command line tool. I don't think the new unified AWS CLI tool has an auth-dry-run option.
102,059
Because of certain reasons, I'm sometimes tied to an extremely slow internet connection. What I realized with this, is that certain sites (for example, any subdomain of blog.hu) works in a way that needs a certain part of the site be loaded before comments are loaded too. I assume it's because of an AJAX operation, as the comments themselves are not visible within the HTML file. In contrast, forum engines, such as vBulletin are often free from AJAX, meaning that when a thread's HTML is loaded, every comment in it are "hardcoded", meaning that even if the "fancy parts" (CSS, images and so on) are not loaded, I can already read the comments. My needs are very special though, so I'm interested - is there any general UX advantage of any of these?
2016/12/01
[ "https://ux.stackexchange.com/questions/102059", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/76708/" ]
There are physical limits as to how long a line of text can be before it gets difficult to process. Much like breathing while speaking, the mind needs periodic breaks to process the string of letters and numbers it has just taken in. Line breaks provide an opportunity for this to occur. A general rule that I have heard is to aim for roughly 80 characters per line. However, this is not the whole story. It seems like we could simply base our font size off of the vw unit to ensure that we always hit this magical 80 character ideal, but no one really does this. Why not? The short answer is peripheral vision. Keep in mind that our eyes and brain also need to keep track of what line we're on, so when we jump after the line break, we know where to continue from. If the text block takes up too much of our field of view, the start of the line will be too far into our peripheral vision by the time we get to the end, and we lose sight of our place. That's no good either. The best way to solve the demands of both character limit and field of view limit is to just enforce a maximum width that (hopefully) ensures we're fitting 80ish characters to a line while those characters remain large enough to read easily and the entire block remains small enough to stay within readable focus. A couple of points about outlook and gmail specifically. Outlook uses some of the excess horizontal space to display both navigation and the list of messages in left aligned panes. The remainder of the window *appears* to be used for the message body, but extreme widths (using multiple monitors) reveal that it quietly enforces a max-width for the body contents. Gmail surprisingly does allow body text to grow effectively infinitely. I pulled up a couple of wordy emails to check, and to be honest long paragraphs don't read especially well. Note that the *compose* dialog is width limited, so it's somewhat surprising that they aren't limiting the width for reading. Perhaps they've found in their testing that emails are typically fairly short or (in the case of promotional) have already been laid out by a designer. Or perhaps Google needs to update their desktop layout...
59,386,815
I use VS 2019 and Xamarin I try to run the example (new project), but I need level API 19 (Android 4.4.2) I was set target, minimun sdk. But get error while build **"Severity Code Description Project File Line Suppression State Error The $(TargetFrameworkVersion) for App4.Android (v4.4) is less than the minimum required $(TargetFrameworkVersion) for Xamarin.Forms (8.1). You need to increase the $(TargetFrameworkVersion) for App4.Android. App4.Android"** I have already tried select different Android version (5,6,7), but apart from 8 only. I don’t. Search on sites they write, simple changed and use. But in reality, this is not so. In general, is it really possible to write below Android 8? [![enter image description here](https://i.stack.imgur.com/LdChI.png)](https://i.stack.imgur.com/LdChI.png) [![enter image description here](https://i.stack.imgur.com/QDaAy.png)](https://i.stack.imgur.com/QDaAy.png) [![enter image description here](https://i.stack.imgur.com/7Txap.png)](https://i.stack.imgur.com/7Txap.png)
2019/12/18
[ "https://Stackoverflow.com/questions/59386815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3219750/" ]
As described here [Expanding target API level requirements in 2019](https://android-developers.googleblog.com/2019/02/expanding-target-api-level-requirements.html), In order to provide users with the best Android experience possible, the Google Play Console will continue to require that apps target a recent API level: * August 2019: New apps are required to target API level 28 (Android 9) or higher. * November 2019: Updates to existing apps are required to target API level 28 or higher. and in future as well the target API level requirement will advance annually. So you need to set target api version as required, however your app will work on all the phones with minimum sdk support. Minimum sdk version you can set based on the features supported by your app.
6,803,762
Is it possible to get list of translations (from virtual pages into physical pages) from TLB (Translation lookaside buffer, this is a special cache in the CPU). I mean modern x86 or x86\_64; and I want to do it in programmatic way, not by using JTAG and shifting all TLB entries out.
2011/07/23
[ "https://Stackoverflow.com/questions/6803762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196561/" ]
The linux kernel has no such dumper, there is page from linux kernel about cache and tlb: <https://www.kernel.org/doc/Documentation/cachetlb.txt> "Cache and TLB Flushing Under Linux." David S. Miller There was an such TLB dump in 80386DX (and 80486, and possibly in "Embedded Pentium" 100-166 MHz / "[Embedded Pentium MMX](http://www.intel.com/content/www/us/en/intelligent-systems/previous-generation/embedded-pentium-mmx.html) 200-233 MHz" in 1998): * [1](http://books.google.com/books?id=XZzUyvghwnsC&pg=PA579&dq="to+the+80386dx") - Book "MICROPROCESSORS: THE 8086/8088, 80186/80286, 80386/80486 AND THE PENTIUM FAMILY", ISBN 9788120339422, 2010, page 579 This was done via Test Registers TR6 TR7: * [2](http://books.google.com/books?id=yXriyj4eZ-gC&pg=SA3-PA19&lpg=SA3-PA19&dq="check+translation") - Book "Microprocessors & Microcontrollers" by Godse&Godse, 2008 ISBN 9788184312973 page SA3-PA19: "3.2.7.3 Test Registers" "only two test registers (TR6-TR7) are currently defined. ... These registers are used to check translation lookaside buffer (TLB) of the paging unit." * [3](http://www.tecchannel.de/server/prozessoren/402224/x86_programmierung_und_betriebsarten_teil_5/index10.html) "x86-Programmierung und -Betriebsarten (Teil 5). Die Testregister TR6 und TR7", deutsche article about registers: "Zur Prüfung des Translation-Lookaside-Buffers sind die zwei Testregister TR6 und TR7 vorhanden. Sie werden als Test-Command-Register (TR6) und Testdatenregister (TR7) bezeichnet. " * [4](http://datasheets.chipdb.org/Intel/x86/Pentium/Embedded%20Pentium%AE%20Processor/MDELREGS.PDF) Intel's "Embedded Pentium® Processor Family Developer’s Manual", part "26 Model Specific Registers and Functions" page 8 "26.2.1.2 TLB Test Registers" TR6 is command register, the linear address is written to it. It can be used to write to TLB or to read line from TLB. TR7 is data to be written to TLB or read from TLB. Wikipedia says in <https://en.wikipedia.org/wiki/Test_register> that reading TR6/TR7 "generate invalid opcode exception on any CPU newer than 80486." The encoding of mov tr6/tr7 was available only to privilege level 0: <http://www.fermimn.gov.it/linux/quarta/x86/movrs.htm> ``` 0F 24 /r movl tr6/tr7,r32 12 Move (test register) to (register) movl %tr6,%ebx movl %tr7,%ebx 0F 26 /r movl r32,tr6/tr7 12 Move (register) to (test register) movl %ebx,%tr6 movl %ebx,%tr7 ```
17,200,445
I am new to coding and I ran in trouble while trying to make my own fastq masker. The first module is supposed to trim the line with the + away, modify the sequence header (begins with >) to the line number, while keeping the sequence and quality lines (A,G,C,T line and Unicode score, respectively). ``` class Import_file(object): def trim_fastq (self, fastq_file): f = open('path_to_file_a', 'a' ) sanger = [] sequence = [] identifier = [] plus = [] f2 = open('path_to_file_b') for line in f2.readlines(): line = line.strip() if line[0]=='@': identifier.append(line) identifier.replace('@%s','>[i]' %(line)) elif line[0]==('A' or 'G'or 'T' or 'U' or 'C'): seq = ','.join(line) sequence.append(seq) elif line[0]=='+'and line[1]=='' : plus.append(line) remove_line = file.writelines() elif line[0]!='@' or line[0]!=('A' or 'G'or 'T' or 'U' or 'C') or line[0]!='+' and line[1]!='': sanger.append(line) else: print("Danger Will Robinson, Danger!") f.write("'%s'\n '%s'\n '%s'" %(identifier, sequence, sanger)) f.close() return (sanger,sequence,identifier,plus) ``` Now for my question. I have ran this and no error appears, however the target file is empty. I am wondering what I am doing wrong... Is it my way to handle the lists or the lack of .join? I am sorry if this is a duplicate. It is simply that I do not know what is the mistake here. Also, important note... This is not some homework, I just need a masker for work... Any help is greatly appreciated and all mentions of improvement to the code are welcomed. Thanks. Note (fastq format): ``` @SRR566546.970 HWUSI-EAS1673_11067_FC7070M:4:1:2299:1109 length=50 TTGCCTGCCTATCATTTTAGTGCCTGTGAGGTGGAGATGTGAGGATCAGT + hhhhhhhhhhghhghhhhhfhhhhhfffffe`ee[`X]b[d[ed`[Y[^Y ``` Edit: Still unable to get anything, but working at it.
2013/06/19
[ "https://Stackoverflow.com/questions/17200445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2501764/" ]
used `class="ball"` as id should be unique, *but you get the point, how to create 100 div* ``` $(document).ready(function () { var $newdiv; for (var i = 0; i < 100; i++) { $newdiv = $('<div class="ball" />').text(i); $('body').append($newdiv); } }); ``` Demo `--->` <http://jsfiddle.net/Uq2ap/>
34,119
I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available. Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium. What could be the reason that UI Framework developers do not prefer Selenium?
2018/06/07
[ "https://sqa.stackexchange.com/questions/34119", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/28240/" ]
**TL;DR**: Selenium is just to slow, compared to for example [Karma](https://karma-runner.github.io/2.0/index.html). --- I guess most UI Frameworks manipulate the DOM. So verifying that the manipulation was correct is also done in the DOM. Most UI Frameworks seem to use Karma for cross-browser testing the DOM. By running plain JavaScript in the browser and using the plain JavaScript API to get back the results. Checking all the functionality with Selenium would be slow, hard to maintain and unnecessary as you can test it faster with for example Karma and plain JavaScript. Jasmine and qUnit are more alternative test runners than tools to verify the DOM. You can also build Selenium or Karma tests with them. For building UI Frameworks I would expect you need something to run-tests against an actual DOM and check it does what you expect, preferable cross all supported browsers and bloody fast. UI Frameworks are building blocks for building web-based workflows. Testing the building blocks is relatively easy with the browser JavaScript API. Where testing full workflows is not, here Selenium would be better suited.
11,736,349
I`m trying to create a loading windows with faded ( Blured ) background , that lock all the other windows any issue for fade the background to lock other windows ?!
2012/07/31
[ "https://Stackoverflow.com/questions/11736349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565157/" ]
Following are the methods from BaseAGIScript class which can be used to play sound files. * `controlStreamFile` - Plays the sound file, user can interrupt by pressing any key. * `getOption` - Plays the given sound file and waits for user option. * `getData` - Plays the given sound file and waits for user enter data.
151,700
Almost on every tutorial video, I watched about `Thermal Expansion` tesseracts, receiving one can output items to build craft transport pipes (gold or stone). The thing is I use `Thermal Expansion 3.0.0.2` mod which has only one type of tesseracts (Not energy, fluid and item like was earlier. Now it's three in one.). And the problem is that receiving tesseract does not output items to transport pipes. It can easily interact with any kind of chests attached directly to it (even with `Applied Energistics chests`), but not with the pipes. What am I doing wrong or how to fix this? The following configuration does not work: **Sending tesseract:** ![enter image description here](https://i.stack.imgur.com/mp8os.png) **Receiving tesseract:** ![enter image description here](https://i.stack.imgur.com/D2AI8.png) But if I put chest directly to the receiving tesseract items are transported properly. The next configuration works fine: ![enter image description here](https://i.stack.imgur.com/QDg0j.png) ![enter image description here](https://i.stack.imgur.com/U9J1s.png) I use **Minecraft 1.6.4**, **Thermal Expansion 3.0.0.2** and **Build Craft 4.2.2**. Client and server are combined by myself and all mods are installed on vanilla minecraft. No additional modpacks were used. Here is **[full list](https://docs.google.com/spreadsheet/ccc?key=0AsJGELm4ir_edGd4RE9GcEZvdEhSVFBLYTVQemEwWXc&usp=sharing#gid=1)** of mods I installed. **EDIT:** I started new client only with 3 mods from **[this list](https://docs.google.com/spreadsheet/ccc?key=0AsJGELm4ir_edGd4RE9GcEZvdEhSVFBLYTVQemEwWXc&usp=sharing#gid=1)**: **BuildCraft**, **Thermal Expansion** and **NEI** and nothing changed. Receiving tesseract still doesn't pump out item to the pipes.
2014/01/21
[ "https://gaming.stackexchange.com/questions/151700", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/52979/" ]
I think that they are not compatible with buildcrafts pipes yet, you need to use a fluiduct(you're free to use a pipe after that i think).
71,467,087
I'm following this tutorial: <https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-sign-user-overview?tabs=aspnetcore> According to other docs, I can use the 'state' parameter to pass in custom data and this will be returned back to the app once the user is logged in However, OIDC also uses this state param to add its own encoded data to prevent xsite hacking - I cant seem to find the correct place in the middleware to hook into this and add my custom data There's a similar discussion on this thread: [Custom parameter with Microsoft.Owin.Security.OpenIdConnect and AzureAD v 2.0 endpoint](https://stackoverflow.com/questions/37489964/custom-parameter-with-microsoft-owin-security-openidconnect-and-azuread-v-2-0-en/37520329#37520329) but I'm using AddMicrosoftIdentityWebApp whereas they're using UseOpenIdConnectAuthentication and I don't know how to hook into the right place in the middleware to add my custom data then retrieve it when on the return. I'd like to be able to do something like in the code below - when I set break points state is null outgoing and incoming, however the querystring that redirects the user to Azure has a state param that is filled in by the middleware, but if i do it like this, then I get an infinite redirect loop ``` public static class ServicesExtensions { public static void AddMicrosoftIdentityPlatformAuthentication(this IServiceCollection services, IConfigurationSection azureAdConfig) { services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(options => { options.ClientId = azureAdConfig["ClientId"]; options.Domain = azureAdConfig["Domain"]; options.Instance = azureAdConfig["Instance"]; options.CallbackPath = azureAdConfig["CallbackPath"]; options.SignUpSignInPolicyId = azureAdConfig["SignUpSignInPolicyId"]; options.Events.OnRedirectToIdentityProvider = context => { //todo- ideally we want to be able to add a returnurl to the state parameter and read it back //however the state param is maintained auto and used to prevent xsite attacks so we can just add our info //as we get an infinite loop back to az b2 - see https://blogs.aaddevsup.xyz/2019/11/state-parameter-in-mvc-application/ //save the url of the page that prompted the login request //var queryString = context.HttpContext.Request.QueryString.HasValue // ? context.HttpContext.Request.QueryString.Value // : string.Empty; //if (queryString == null) return Task.CompletedTask; //var queryStringParameters = HttpUtility.ParseQueryString(queryString); //context.ProtocolMessage.State = queryStringParameters["returnUrl"]?.Replace("~", ""); return Task.CompletedTask; }; options.Events.OnMessageReceived = context => { //todo read returnurl from state //redirect to the stored url returned //var returnUrl = context.ProtocolMessage.State; //context.HandleResponse(); //context.Response.Redirect(returnUrl); return Task.CompletedTask; }; options.Events.OnSignedOutCallbackRedirect = context => { context.HttpContext.Response.Redirect(context.Options.SignedOutRedirectUri); context.HandleResponse(); return Task.CompletedTask; }; }); } } ```
2022/03/14
[ "https://Stackoverflow.com/questions/71467087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5003392/" ]
``` # The following code should work: df.NACE_code = df.NACE_code.astype(str) df.NACE_code = df.NACE_code.str.replace('.', '') ```
59,309,998
I have a script that runs every 15 seconds and it creates a new thread every time. Now and then this thread gets stuck and blockes the synchronisation process of my program. Now i want to kill the process with a specific name if the thread is stuck for 20 loops. Here is my code: ``` public void actionPerformed(ActionEvent e) { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss"); System.out.println(ft.format(dNow)); ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int noThreads = currentGroup.activeCount(); Thread[] lstThreads = new Thread[noThreads]; currentGroup.enumerate(lstThreads); boolean loopthreadfound = false; for (int i = 0; i < noThreads; i++){ try{ if (lstThreads[i].getName() == "loopthread"){loopthreadfound = true;} }catch(Exception e1){System.out.println(e1);} } if (loopthreadfound == false){ loopthreadcounter = 0; //Starten in nieuwe thread Thread loopthread = new Thread() { public void run() { try { checkonoffline(); checkDBupdates(); } catch (JSONException | SQLException | IOException e1) { System.out.println(e1); } } }; loopthread.setName("loopthread"); loopthread.start(); }else{ loopthreadcounter++; System.out.println("Loopthread already running... counter: " + loopthreadcounter); if (loopthreadcounter > 20){ // HERE I WANT TO KILL THE THREAD "loopthread " } } } ```
2019/12/12
[ "https://Stackoverflow.com/questions/59309998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12526527/" ]
Ok, after a bit of work I believe I have a solution. As part of my CI (Continuous Integration) job I run: ``` cdk synth ``` I then save the contents of the cdk.out folder to a repository (I'm using Octopus Deployment). As part of my CD (Continuous Deployment) job I have the following (Powershell): ``` $Env:AWS_ACCESS_KEY_ID={your key} $Env:AWS_SECRET_ACCESS_KEY={your secret} $Env:AWS_DEFAULT_REGION={your region} $cdk=[Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) + "\npm\cdk.cmd" & $cdk --app . deploy {your stack name} --require-approval never ``` So the "cdk synth" will generate the template and assets required for deployment. The "cdk --app . depoy {your stack name} --require-approval never" is telling aws-cdk to us the existing templates and assets. This avoids a situation where the CD process may produce a different setup than the CI process. The "." indicates that the templates & assets are in the current folder. You will need to install node & aws-cdk on the CD server (in my case an Octopus Deploy tentacle); Node install is easy, just log in and install. To add aws-cdk perform the following (using an administrator powershell): ``` npm prefix -g // Make note of the path npm config set prefix C:\Windows\System32\config\systemprofile\AppData\Roaming\npm npm install -g aws-cdk npm config set prefix {original path} ``` Note that the npm path maybe different for your usage - will depend on the user account used for the CD process and Windows version.
29,079
What is correct format for using XPath? Does XPath vary with the browser? ``` drchrome.findElement(By.xpath("//a[contains(.,'Google')]")).click(); ```
2017/08/16
[ "https://sqa.stackexchange.com/questions/29079", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/27487/" ]
As far as i know xpath doesn't depends on any browser. Make sure you have created correct xpath it will work. Second : It's depend on your tag which attribute it has and how efficient you are in xpath. For example this is the simple hyperlink: ``` <a href="https://stackexchange.com/questions?tab=hot" name="hotnetwork" class="js-gps-track">Hot Network Questions</a> ``` So here i can create the xpath to locate the same in different ways like : ``` //a[@name='hotnetwork'] ``` OR ``` //a[@class='js-gps-track'] ``` OR combine both attribute for uniqueness like : ``` //a[@name='hotnetwork'][@class='js-gps-track'] ``` OR if you want to access the link using its text then you can use `contains()` method ``` //a[contains(text(),'Hot Network')] ``` Note : It will locate the element based on match found with your given string (Hot Network) If you require to locate an element if self or its child tag contains some text then using dot `.` in contains method as you are using : ``` //a[contains(.,'Hot Network')] ``` OR you can use `text()` method like : ``` //a[text()=' Hot Network Questions'] ``` While using `text()` method you have to pass the full link text including spaces else it won't work.
6,089,673
i'm new in the iphone and json world . i have this json structure . You can see it clearly by putting it here <http://jsonviewer.stack.hu/> . ``` {"@uri":"http://localhost:8080/RESTful/resources/prom/","promotion":[{"@uri":"http://localhost:8080/RESTful/resources/prom/1/","descrip":"description here","keyid":"1","name":"The first name bla bla ","url":"http://localhost/10.png"},{"@uri":"http://localhost:8080/RESTful/resources/promo/2/","descrip":"description here","keyid":"2","name":"hello","url":"http://localhost/11.png"}]} ``` i want to parse it with json-framework . I tried this ``` NSDictionary *json = [myJSON JSONValue]; NSDictionary *promotionDic = [json objectForKey:@"promotion"]; NSLog(@" res %@ : ",[promotionDic objectAtIndex:0]); ``` But then how to do to get for exemple , the name of the object at index 0 ? I think i should put object in an NSArray ? but i dont find how :/ and i dont the number of object is variable . Help please .
2011/05/22
[ "https://Stackoverflow.com/questions/6089673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/761812/" ]
First off, You need this line after you load the JSON ``` NSLog(@" json %@ : ",[json description]); ``` That will tell you what you have. Secondly, you can't call objectAtIndex: on a dictionary. If it works, its because promotionDict is really an NSArray. (The NSLog will tell you). In Objective - C you can assign to any kind of pointer, which is confusing to new developers, but is part of the language, and really is a feature. With an NSArray you can ask for the number of things in it, [myArray count], etc. You need to command double click in XCode to open up the docs for NSDictionary, etc.
63,063,279
I have this code, which is slightly different than the some of the other code with the same question on this site: ``` public void printAllRootToLeafPaths(Node node,ArrayList path) { if(node==null){ return; } path.add(node.data); if(node.left==null && node.right==null) { System.out.println(path); return; } else { printAllRootToLeafPaths(node.left, new ArrayList(path)); printAllRootToLeafPaths(node.right,new ArrayList(path)); } } ``` Can someone explain WHY best case is O(nlogn)? Worst case, the tree breaks down to a linked list and the array is copied 1+2+3+...+n-1+n times which is equivalent to n^2 so the time complexity is O(n^2). Best case array is being copied along every node in the path. So copying it looks like 1+2+3+...+logn. N/2 times. So why isn't the summation (logn)^2 if 1+2+3+...+n-1+n is n^2? Making the best case O(n(logn)^2)?
2020/07/23
[ "https://Stackoverflow.com/questions/63063279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13985180/" ]
Yes, all that copying needs to be accounted for. Those copies are not necessary; it's easy to write functions which either: * use a (singly) linked list instead of ArrayList, or * use a single ArrayList, overwriting previous paths when they're not needed any more. With non-copying algorithms, the cost of the algorithm is the cost of printing the paths, which is the sum of the lengths of all paths from the root to a leaf. Copy the array on every call, makes the cost become the sum of the paths from the root to every *node*, rather than every leaf. (The fact that the array is copied twice is really not relevant to complexity analysis; it just means multiplying by a constant factor, which can be ignored.) With the non-copying algorithm, the best case is a linear tree, with only one child per node. Then there is just one leaf with a path length of *N*, so the total cost is O(*N*). But that's a worst-case input if you're copying at every node; the node path lengths are successive integers, and the sum of node path lengths is quadratic. For your algorithm, the best case is a perfectly-balanced fully-occupied tree. In a fully-occupied tree, there is one more leaf than non-leaf nodes; in other words, approximately half the nodes are leaves. In a perfectly-balanced tree, every node can be reached from the root in a maximum of log *N* steps. So the sum of path lengths to every node is O(*N* log *N*). (Some nodes are closer, but for computing big O we can ignore that fact. Even if we were to take it into account, though, we'd find that it doesn't change the asymptotic behaviour because the number of nodes at each depth level doubles for each successive level.) Because half the nodes are leaves, the cost of this input is O(*N* log *N*) with the non-copying algorithm as well. Both algorithms exhibit worst-case quadratic complexity. We've already seen the worst-case input for the copying algorithm: a linear tree with just one leaf. For the non-copying algorithm, we use something very similar: a tree consisting of a left-linked backbone, where every right link is a leaf: ``` root /\ / \ /\ 7 / \ /\ 6 / \ /\ 5 / \ /\ 4 / \ /\ 3 / \ 1 2 ``` Since that tree is fully-occupied, half its nodes are leaves, and they are at successively increasing distances, so that is again quadratic (although the constant multiplier is smaller.)