text
stringlengths
70
452k
dataset
stringclasses
2 values
Will Jvm make compiled byte code into executable file I read the following articles: http://searchcio-midmarket.techtarget.com/definition/just-in-time-compiler http://javarevisited.blogspot.in/2011/12/jre-jvm-jdk-jit-in-java-programming.html I am now really interested in knowing what will happen when I run a class. JIT compiles the byte code again and then ??? Will this compiled code be converted into an .exe by the JVM? Like the others said: JIT does not mean the code is compiled to a binary executable (.exe). However, an interesting application that you may consider is Excelsior JET. I haven't read too much about it and haven't used it, so I don't know exactly how it works... yet. But according to its webpage, it's an AOT (Ahead-Of-Time) compiler. This means that it will compile your .class files to a system-dependent binary file. You should give it a try, see how it performs. According to the website, you get a free license if your project is non-comercial in nature. Java Compiler compiles plain-text Java code into JVM bytecode. http://en.wikipedia.org/wiki/Java_bytecode JVM has a HotSpot optimizer that evaluates the code for "Hot Spots" (basically, code that will be used the most) and pays special attention to those spots when using CPU cache. It may also flag those spots for the JVM to recompile to a native language (like Assembly) and this is called JIT. JVM is essentially a virtual machine that runs a JVM bytecode interpreter. There is never a direct .exe. It is a Windows/C/C++ thing, mostly. No, the code is NOT "compiled" into an "exe" the program is stored in memory as byte code, but the code segment currently running is preparatively compiled to physical machine code in order to run faster. I'll go out on limb and say that JIT is a type of interpreter, designed to improve the speed of commonly used branches of code (at least that was my interpretation 10 years ago) JIT compilers represent a hybrid approach, with translation occurring continuously, as with interpreters, but with caching of translated code to minimize performance degradation. It also offers other advantages over statically compiled code at development time, such as handling of late-bound data types and the ability to enforce security guarantees. 'No, the code is "compiled" into an "exe"' - Seems you forgot the word "not" in your Answer. care about your words, they can give you -1, first line Thanks guys for the peer review, appreciate...brain is obvious working faster then the fingers :P The JIT is a compiler because its output is code, albeit that the code only gets "output" to code segments in JVM memory. An interpreter doesn't output code, it executes code.
common-pile/stackexchange_filtered
Network manager always fails to autoconnect to wireless networks after boot. Manually connecting works fine On both of my latpops running arch linux and KDE plasma Networkmanager fails to autoconnect to a saved wireless network after login with the message No secret provided which is quite annoying. Connecting manually after it fails or disconnecting while it attempts to autoconnect and then manually connecting works fine. dmesg | grep wlp3s0 yields the following on both machines: [ 2.932334] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 2.946381] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 3.214407] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 3.274321] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 12.008032] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 42.004698] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 42.012632] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready [ 49.783058] IPv6: ADDRCONF(NETDEV_UP): wlp3s0: link is not ready Any idea how this can be solved?
common-pile/stackexchange_filtered
Form for has_many based on records count in associated table class User < ActiveRecord::Base has_many :user_services end class UserService < ActiveRecord::Base attr_accessible :service_id, :user_id, :value belongs_to :user belongs_to :service end For example I have 5 services: Google, Facebook, Youtube and etc. When I am editing a user, I should see form for each service created in services table. Google 'Enter your account name' Facebook 'example_account_name' Youtube 'Enter your account name' If user already enter name I can edit it and if name is blank I can create it. If I add another service I must see another text_field for edit it value. What is the best solution? All magic in find_or_initialize <%= form_for @user do |f| %> ... <% @services.each do |service| %> ... <%= f.fields_for :user_services<EMAIL_ADDRESS>do |user_service| %> <%= user_service.label :value, "Set your id" %> <%= user_service.text_field :value %> <%= user_service.hidden_field :user_id, :value => @user.id %> <% end %> <% end %> <p><%= f.submit "Submit" %></p> <% end %> I think Ryan Bates has the answer for you. Checkout http://railscasts.com/episodes/196-nested-model-form-part-1 and http://railscasts.com/episodes/197-nested-model-form-part-2 Thanks, but I know about nested forms and question is different The second link shows you how to dynamically add forms via javascript
common-pile/stackexchange_filtered
How can OpenCV element pointer exist in Obj-C Class? I am a new settle in Obj-C. I want to wrap a OpenCV class in Obj-C. I have a C++ class now, it is like: class cxx { private: IplImage* image; public: cxx (); void modify (); }; Now I am rewriting in Obj-C, I get confused in the memory type of the pointers. I put it in a class: class obj_c:NSObjec { IplImage* image; } - (id) init; - (void) modify; But I don't how to deal with the right property of the pointer IplImage*. If I don't set any property, I can't even access the pointer in the function. Since you are just getting started, you should consider using OpenCV's new C++ interface instead of the old C interface. There are tutorials here. @interface objc_c : NSObject { IplImage * image; } - (id)init; - (void)modify; @end That's how you make a class in objective-c. And in the body of the functions, init and modify, yes, you will be able to access the pointer. You don't have to declare properties unless you want to access an ivar from outside of the class (typically).
common-pile/stackexchange_filtered
Importing PyQ from within Spyder causes kernel to die Have installed kdb+ 64-bit to a Windows 10 machine. Running within Anaconda/Spyder, when I import PyQ, I get an error message that the kernel died. No issues running q stand alone from the command line. Both of these import pyq from pyq import q Give this error, along with a kernel restart. Kernel died, restarting version info: Spyder 3.3.1 Python 3.6 kdb+/q 3.6 (64-bit) Any ideas how to resolve this? What version of pyq-kernel do you use? If you think you've encountered a bug in pyq, it is best to report it at https://github.com/KxSystems/pyq/issues. running version 4.1.4 of pyq, 5.9.2 PyQt5. don't know that this is necessarily a pyq bug, you have reason to believe it is? You cannot import pyq into a regular python session, but you should be able to connect Spyder to a pyq kernel. First, install pyq-kernel: pip install pyq-kernel pyq -m pyq.kernel install Second, start a pyq kernel session on the console and find the kernel id: $ jupyter console --kernel=pyq_3 In [2]: %connect_info { "shell_port": 60484, "iopub_port": 60485, "stdin_port": 60486, "control_port": 60487, "hb_port": 60488, "ip": "<IP_ADDRESS>", "key": "ca3c4bc5-a55c552fdb14da48fda44b9d", "transport": "tcp", "signature_scheme": "hmac-sha256", "kernel_name": "" } Paste the above JSON into a file, and connect with: $> jupyter <app> --existing <file> or, if you are local, you can connect with just: $> jupyter <app> --existing kernel-25218.json or even just: $> jupyter <app> --existing if this is the most recent Jupyter kernel you have started. Kernel id is the number in the `kernel-###.json file. Finally, go the menu under the gear icon in the Spyder's IPython console window, select "Connect to an existing kernel" and enter the kernel id that you have found in the second step in the "Kernel ID/Connection file" box. thanks, saw your response on github as well...haven't tried this yet, but will respond once I do
common-pile/stackexchange_filtered
Handling a lossless jpeg Image in DICOM I have a DICOM Image which has the image stored as the following JPEG Lossless, Nonhierarchical, First- Order Prediction (Processes 14 [Selection Value 1]): Default Transfer Syntax for Lossless JPEG Image Compression I can open the original DICOM file in Irfanview, and that works fine, but when I take the Bit stream from the DICOM file and save it as a file, and try to open it in Irfanview, I get an error "Unsupported JPEG process/compression: SOF type 0xc3" I've checked that the byte stream matches that of the DICOM file, and checked that it starts with, FF D8 FF E0 00 10 4A 46 49 46 which seems to be a standard JPEG header. There are 4 bytes at the end of the DICOM file beyond what is specified by the length of the tag, are these some sort of DICOM footer? Any ideas what it would take to get this to open? I've included the JPEG_LS plugin in Irfanview. This is a continuation of Length of PixelStream in EvilDicom library My imaging library supports JPEG_LS in a JPEG file or read from a DICOM. Can you share the image? I'll see if there is something wrong with the way it's written. That data is not JPEG-LS, it is JPEG Lossless (1.2.840.10<IP_ADDRESS>.70), a completely unrelated compression format. Very few image readers support that type of JPEG data. I've only known it to be used in the context of DICOM. I believe also that it may not necessarily be one contiguous block of JPEG data, but rather be broken into segments (encapsulated DICOM) with DICOM tag wrappers. Perhaps Irfanview knows how to read it when in the context of a DICOM, but fails to read it as normal JPEG data, since it is such a rare JPEG format. Or perhaps the data stream is not contiguous JPEG data, but contains DICOM elements as well.
common-pile/stackexchange_filtered
How to check status of hdfs job from java program? I want to check the status of a job. Once it is completed I want to perform another action. The problem is I also want to check whether job is killed or aborted as many jobs can be there in hdfs and report accordingly. https://www.programcreek.com/java-api-examples/index.php?api=org.apache.hadoop.mapred.JobStatus Gone through the link! Aslo please saw the source code on this link. private void printJobAnalysis() { if (!job.getJobStatus().equals (JobStatus.getJobRunState(JobStatus.SUCCEEDED))) { System.out.println("No Analysis available as job did not finish"); return; } AnalyzedJob avg = new AnalyzedJob(job); System.out.println("\nAnalysis"); System.out.println("========="); printAnalysis(avg.getMapTasks(), cMap, "map", avg.getAvgMapTime(), 10); printLast(avg.getMapTasks(), "map", cFinishMapRed); if (avg.getReduceTasks().length > 0) { printAnalysis(avg.getReduceTasks(), cShuffle, "shuffle", avg.getAvgShuffleTime(), 10); printLast(avg.getReduceTasks(), "shuffle", cFinishShuffle); printAnalysis(avg.getReduceTasks(), cReduce, "reduce", avg.getAvgReduceTime(), 10); printLast(avg.getReduceTasks(), "reduce", cFinishMapRed); } System.out.println("========="); }
common-pile/stackexchange_filtered
How to press a button with java-script event inside a web-page by code for iOS (iPhone)? I am writing an application for iOS (iPhone). How to press a button with java-script event inside a web-page? I need to write a code to press this button. Then the event will be executed. And I'll take result of it's work. Thanks a lot for help! You can use: document.getElementById('id-of-button').click(); This will perform a click event on the button. EDIT: to run JavaScript in a UIWebView use the stringByEvaluatingJavaScript: method. Eg: [webView stringByEvaluatingJavaScript:@"document.getElementById('id-of-button').click();"]; Update: [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('id-of-button').click();"];
common-pile/stackexchange_filtered
Non-voting-based reputation from edits This question gave us this beautiful page where low quality posts are shown. Usually those "low quality posts" are: Answers that really are comments (score 46 example, score 46 example), but those are getting handled separately. Poor questions (score 43 example, score 49 example), but those can get closed. Hastily written answers (score 29 example answer, score 52 example answer) that can be turned into useful posts by some expansions or some linking to documentation. The edits to the third kind of posts can be rewarded easily without having to vote on edits. You would, for example, gain 1 token reputation by improving an answer's score by 10 points* (and lose as much by making it worse, so that you can't do rollback wars with yourself.) This reputation would count towards the rep cap. Closed and CW posts wouldn't count. This doesn't need to only apply to bad posts. This would encourage tasks such as editing an incomplete answer, instead of adding a competing one (as much as it is encouraged, I think one good answer is better than two possibly incomplete ones) -- from what I see, just making a post longer improves its score. Flipside The Stack Overflow only problem with this example is that, on average, adding code reduces a post's score. This could result in a reputation penalization for adding code sample to an answer! Similar problems may also apply to LaTeX sites if the score calculation counts equations. We're talking about 1 rep however... Also, this may make reputation recalculation more expensive -- especially now that you can make them on-demand. *Average edit score gain in the few tests I've made. Ready... Steady... DOWNVOTE! Is this an SO only optimization? Would it readily apply to, for instance, Cooking.SE? @drach No -- as I explain in the flipside, it'd apply best to sites that do not discuss code and do not use LaTeX, as those topics skew the scoring. Cooking would be ideal. But that's rather my point @radp ~ If you can't make it work for all, it seems a micro-op sort of thing. @drachenstern I'm not saying it wouldn't work on SO -- it would, but with a few gotchas.
common-pile/stackexchange_filtered
Add elements to Arraylist and it replaces all previous elements in Java I am adding elements to a ArrayList and it adds the first one correctly but then when I add any subsequent elements it wipes replaces the other elements with the value from the most recently added and adds a new element to the ArrayList. I ran test using arraylist and ints and even another created class and it worked perfectly but something about the custom class I am using here causes problems. The code for the array list is public static void main(String args[]){ List<BasicEvent> list = new ArrayList<BasicEvent>(); list.add(new BasicEvent("Basic", "Door", 9, 4444, new Date(12,04,2010), new Time(12,04,21), 1, 0.98, 0)); list.add(new BasicEvent("Composite", "Door", 125, 4444, new Date(12,04,2010), new Time(12,04,20), 1, 0.98, 1)); list.add(new BasicEvent("Basic", "Door", 105, 88, new Date(12,04,2010), new Time(12,05,23), 1, 0.98, 0)); list.add(new BasicEvent("Basic", "Door", 125, 12, new Date(12,04,2010), new Time(12,05,28), 1, 0.98, 1)); list.add(new BasicEvent("Basic", "Door", 129, 25, new Date(12,04,2010), new Time(12,05,30), 1, 0.98, 0)); list.add(new BasicEvent("Basic", "Door", 125, 63, new Date(12,04,2010), new Time(12,04,20), 1, 0.98, 1)); list.add(new BasicEvent("Basic", "Detect", 127, 9, new Date(12,04,2010), new Time(12,05,29), 1, 0.98, -1)); for(int i=0;i<list.size();i++) {System.out.println("list a poition " + i + " is " + BasicEvent.basicToString(list.get(i)));} And the code for the custom class basicEvent is public class BasicEvent { public static String Level; public static String EType; public static double xPos; public static double yPos; public static Date date; public static Time time; public static double Rlb; public static double Sig; public static int Reserved; public BasicEvent(String L, String E, double X, double Y, Date D, Time T, double R, double S, int Res){ Level = L; EType = E; xPos = X; yPos = Y; date = D; time = T; Rlb = R; Sig = S; Reserved = Res; }; public static String basicToString(BasicEvent bse){ String out = bse.getLevel() + ";" + bse.getEtype() + ";" + bse.getxPos() + ";" + bse.getyPos() + ";" + bse.getDate().dateAsString() + ";" + bse.getTime().timeAsString() + ";" + bse.getRlb() + ";" + bse.getSig() + ";" + bse.getReserved(); return out; } Try to reformat the code of BasicEvent so that it looks as actual code in the question, thanks. What do you get as output, and what do you expect ? Why are your class members static? new Date(12,04,2010) has at least 2 errors in it, probably 3. 2010 does not indicate the year you think it does in that case, 04 is a octal binary, as soon as you reach 08 you'll notice the problem, 04 (as well as 4) probably doesn't indicate the month you think it does, check the Javadoc of that constructor. All the members of your class BasicEvent are static, i.e. they are shared between all instances of the class. Thus when you create a new instance, the properties of the old instance are overridden with the new values. You should change your class definition to public class BasicEvent { public String Level; public String EType; public double xPos; public double yPos; public Date date; public Time time; public double Rlb; public double Sig; public int Reserved; ... } As a side note, in general it is not good practice to use public fields - better make them private and provide public accessors / setters only as needed. Of course, in experimental code it does not matter much, but in production quality code it does. Darn, too late :P +1 that's indeed the cause. Why are all your class members static? Static means there will be only one value in the whole VM, so it's logical the values are being overwritten on each instance creation (this is not a problem with ArrayList). Make your member variables non-static, and consider making them private and exposing them with getters. Well, all your fields in BasicEvent are static, so they belong to the class, not to objects. That means they are the same for all objects. Every time you create an object, you write on these fields. Please look at your Java documention on the signification of static fields and how to use them.
common-pile/stackexchange_filtered
backbone.js routing when query passed to route contains / My app basically takes some form input and returns a set of results. I have two routes routes: { '': 'search', 'search': 'search', 'results/:query': 'results' }, results: function(query) { var search = new ResultsSearchView(); var grid = new GridView({ query: query }); } If the query contains any characters / specifically (can totally happen in this case), they are added to the URL and my route breaks. I have tried using encodeURI() and encodeURIComponent() bit I'm not having any luck. How are you folks handling such things? You can use encodeURIComponent when building the URL to convert the / to %2F and then decodeURIComponent inside the route handler to convert them back; the HTML would end looking like this: <a href="#results/pancakes">no slash</a> <a href="#results/where%2Fis%2Fpancakes%2Fhouse">with slashes</a> and then in the router: routes: { 'results/:query': 'results' }, results: function(query) { query = decodeURIComponent(query); // Do useful things here... } Demo: http://jsfiddle.net/ambiguous/sbpfD/ Alternatively, you could use a splat route: Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components. So your HTML would be like this: <a href="#results/pancakes">no slash</a> <a href="#results/where/is/pancakes/house">with slashes</a> and your router: routes: { 'results/*query': 'results' }, results: function(query) { // Do useful things here... } Demo: http://jsfiddle.net/ambiguous/awJxG/ Using a splat route and it's working great. Thank you for the help.
common-pile/stackexchange_filtered
Keep activity alive when using register activity for result even if Dont keep activity is enabled Is there a way to stop ActivityA from being terminated when it launches ActivityB using registerForActivityResult in Android, even when the "Don't keep activities" option is turned on? Are there any tricks or methods to keep ActivityA alive when switching to ActivityB in this scenario? I know we can use onSavedInstanceState and onRestoreInstanceState to recover data, but I'm curious if there's a way to ensure ActivityA stays running. The whole reason that registerForActivityResult is written that way is because process death and recreation is unavoidable.
common-pile/stackexchange_filtered
Is passing Context as a parameter to a method in a Singleton class causes memory leak I'm declaring a Singleton class where I need to pass context parameter for one of the methods in this class public class MySingleton() { Private Context mContext; Private static MySingleton mInstance; public static MySingleton mInstance() { if (mInstance == null) { mInstance = new MySingleton(); } return mInstance; } public void myMethod(Context context) { this.mContext = context; // write your code here.... } } will this cause a memory leak. It could, as you do not know what sort of Context you will be referencing. It would be safer to write: this.mContext = context.getApplicationContext(); This way, you are certain that mContext is referencing the Application singleton. What if I deleted mContext and kept context as a local variable? @HmH: That may be safe, though it would depend a bit on what you do with that variable. This method is called to create an AlarmManager and the context is used to initiate an intent and PendingIntent. But the method is called 3 times from 3 different places. @HmH: What you are describing should be safe, particularly if you are not holding onto any of those things in fields of your singleton. You can always use tools like Leak Canary to try to see if you are leaking a context.
common-pile/stackexchange_filtered
How can I record both the screen and webcam using Canvas at 1080p and 30fps? I tried this and it worked, but the video starts lagging after 30 seconds. No matter what I do, the video records smoothly for 30 seconds and then starts lagging. Am I missing something? I'm not using requestAnimationFrame because it only works if the tab is active. I'm seeing my PC's memory and CPU usage while I'm recording. I don't see any huge spikes const screenVideo = document.createElement("video"); screenVideo.style.display = "none"; screenVideo.srcObject = screenStream; screenVideo.muted = true; const webcamVideo = document.createElement("video"); webcamVideo.style.display = "none"; webcamVideo.srcObject = videoStream; webcamVideo.muted = true; webcamVideo.onloadedmetadata = () => { webcamVideo.play(); }; canvas = document.createElement("canvas"); screenVideo.onloadedmetadata = () => { screenVideo.play(); canvas.width = screenVideo.videoWidth; canvas.height = screenVideo.videoHeight; }; canvasContext = canvas.getContext("2d"); const drawCombinedStream = () => { if (!canvasContext || stopDrawingFrames) return; canvasContext.clearRect(0, 0, canvas.width, canvas.height); canvasContext.drawImage(screenVideo, 0, 0, canvas.width, canvas.height); const overlaySize = 250; const overlayX = 20; const overlayY = canvas.height - overlaySize - 20; const overlayRadius = overlaySize / 2; const webcamAspectRatio = webcamVideo.videoWidth / webcamVideo.videoHeight; let drawWidth, drawHeight; if (webcamAspectRatio > 1) { drawHeight = overlaySize; drawWidth = overlaySize * webcamAspectRatio; } else { drawWidth = overlaySize; drawHeight = overlaySize / webcamAspectRatio; } const offsetX = overlayX - (drawWidth - overlaySize) / 2; const offsetY = overlayY - (drawHeight - overlaySize) / 2; canvasContext.save(); canvasContext.beginPath(); canvasContext.arc( overlayX + overlayRadius, overlayY + overlayRadius, overlayRadius, 0, Math.PI * 2, ); canvasContext.clip(); canvasContext.drawImage( webcamVideo, offsetX, offsetY, drawWidth, drawHeight, ); canvasContext.restore(); setTimeout(drawCombinedStream, 1000 / 30); }; drawCombinedStream(); combinedVideoStream = canvas.captureStream(30); See timeouts in inactive tabs @JaromandaX Thank you very much for the quick suggestion. You just pointed me to the right direction. I fixed it by adding a muted sound on loop so that Chrome doesn't throttle the timeout function. Thank you again!
common-pile/stackexchange_filtered
The jobs unicorn screams in vain in Internet Explorer 11 On the jobs page, a clever little unicorn lurks behind the Search Jobs tab. Hovering the cursor over the unicorn causes it to pop up and scream "New features!" Clicking on the eyeless screaming unicorn in Firefox, Chrome, or Edge triggers the Meet the New Job Search tour. However, clicking on the eyeless screaming unicorn in Internet Explorer has no effect. Unicorns are allergic to IE. As is everyone else.... @JacobGray I can confirm that. Can confirm, jobs are not compatible with IE 11. @Travis, you would be surprised. IE11 is such a PITA you need professionals to handle it. Not worth the time. Website fails because user had IE 11? Status: By design. To note: IE 11 is only 4% of all internet use, mostly by government offices which do not browse casually. At Stack Exchange, where the users are primarily in the tech sector, the usage is a far smaller percent. That said, I am sure that this can be addressed rather easily since it does just seem to be an issue with an event handler. However, trying to find a job solely on being an "IE 11 professional" is probably going to be the best joke I hear all day.... is it April 1st already? @Travis, the SO folks most probably worked hard to implement that cute unicorn effect, but it did fail on IE11 (at least for one user, so we may be making a mountain out of nothing, but it's not like it stopped us before ;) However, I can assure you that IE11 is special, and that if you have to maintain a reasonably-old product that relies on the obvious differences from the good old days, you will have a lot to refactor to accommodate IE11, especially if you still want to support the earlier versions. I get it. My products run on IE 11. That doesn't mean anyone is happy about it ;) Nor happy about what that meant when we had to keep the other scoundrels supported (i.e. 10, or 9, or 8, or 7, or 6... well, you get the picture). Conversely, maybe this has to do with upgrading to jQuery 1.12.4. Assuming you mean that the bug is that you can't click on the unicorn or his little balloon... It's not clickable in FF, Chrome or Edge either (all current versions) @Machavity I respectfully disagree. Clicking on the unicorn in Firefox, Chrome, or Edge triggers the Meet the New Job Search tour for me. @Thriggle Ah, I see the problem now. The banner isn't loading either (the unicorn is trying to interact with something that doesn't exist). The banner already exists in the others so clicking it tries to load content already there. IE11 console says SCRIPT438: Object doesn't support property or method 'startsWith' tour.bubble.min.js (1,605) So yeah Thanks for reporting this bug. Fix is already in repo waiting to fly to prod. You should see it fixed in up to 24h.
common-pile/stackexchange_filtered
SwiftUI TextEditor internal scroll padding without text cropping Im building note view with footer over whole UI var body: some View { ZStack(alignment: .bottom) { VStack(alignment: .leading) { Text("\(note.date.formatted())") .padding([.leading, .trailing]) TextEditor(text: $note.text) .padding() } Footer {} } } There is title text with date, TextEditor and a Footer element. Footer just floats over TextEditor and blocks text from view. That's what i need, but here's catch I need to add padding to TextEditor's internal scroll so text scrolls under footer element, but i can scroll up enough so i can see it all. If i add .padding([.bottom], 150) to TextEditor it just crops text and it looks ugly in layman's terms i need the illusion that there is like 5 or so "\n" in the end of the text, but without adding "\n" You might want to try contentMargins(_:for:) from iOS 17: TextEditor(text: $note.text) .padding() .contentMargins(.bottom, .init(top: 0, leading: 0, bottom: 50, trailing: 0)) //<- here For similar task I preferred to use scrollClipDisabled() rather than contentMargins or safeAreaInset(edge:alignment:spacing:content:) both of which have one annoying thing - they provide background which covers scrolling content entirely. I noticed this happens only with TextEditor, meanwhile ScrollView works perfectly fine with mentioned modifiers. scrollClipDisabled() doesn't have this problem and seems the best option to use in your situation to beautifully and partially cover the scrolling content. struct FooterAboveScrollingText: View { var body: some View { VStack(spacing: 0) { Text("14 October, 2023") .frame(height: 60) .frame(maxWidth: .infinity) .background { Rectangle().foregroundStyle(.white).ignoresSafeArea() // <-- Attention here! } .zIndex(1) // <-- And here! TextEditor(text: { your huge text }) .scrollClipDisabled() RoundedRectangle(cornerRadius: 20) .frame(maxHeight: 60) .foregroundStyle(.white) .shadow(radius: 15) .padding() } } } However, as you can see, you still need to make a couple of adjustments to your date-title. You need to add a background and zIndex(1) to make sure that your title is not overlapped by scroll content. The result: NOTE: One more thing to know, this solution is for iOS 17 and up, meanwhile safeAreaInset(edge:alignment:spacing:content:) is available from iOS 15. .scrollContentBackground(.hidden) removes background for contentMargins. thanks for answer. you've been very helpful
common-pile/stackexchange_filtered
Why do my nested python class instances become tuples? I have defined some classes thusly: class CustomParameter(): def __init__(self, strFriendlyAttribName, strSystemAttribName): self.FriendlyAttribName = strFriendlyAttribName self.SystemAttribName = strSystemAttribName class PartMaster(): AttribNameList = ["Part Number", "Name", "Standard Part", "Part Type", "ControlledBy", "PIN", "Design Responsibility"] def __init__(self): self._UUID = None self.PartNumber = CustomParameter("Part Number", "V_ID"), self.Name = CustomParameter("Name", "V_name"), self.StandardPart = CustomParameter("Standard Part", "V508_isStandardPart"), self.PartType = CustomParameter("Part Type", "V511_PartType"), self.ControlledBy = CustomParameter("ControlledBy", "V511_ControlledBy"), self.PIN = CustomParameter("PIN", "BOECACPinItemNumber"), self.DesignResponsibility = CustomParameter("Design Responsibility", "BOECACDesignRpnse") class Part(): def __init__(self, PartNumber): self.PartNumber = PartNumber #This instance wraps self.PartMaster = PartMaster() #create new instance test = Part("ABC") I would expect that test.PartMaster.PIN would be an instance of CustomParameter, but instead it is a tuple tuple: (<__main__.CustomParameter instance at 0x0000000002D724C8>,) Why is this, and how can I make it not be so? I'd like to construct my classes such that test.PartMaster.PIN gives me back the instance instance of my CustomParameter class. Any ideas? Because your instance vars of the PartMaster class are set with commas at the end whenever your class is initialized :) Python interprets this: x = 'test', as: ('test',) Try this instead: def __init__(self): self._UUID = None self.PartNumber = CustomParameter("Part Number", "V_ID") self.Name = CustomParameter("Name", "V_name") self.StandardPart = CustomParameter("Standard Part", "V508_isStandardPart") self.PartType = CustomParameter("Part Type", "V511_PartType") self.ControlledBy = CustomParameter("ControlledBy", "V511_ControlledBy") self.PIN = CustomParameter("PIN", "BOECACPinItemNumber") This has happened to me a bunch of times. Whenever I switch from writing out a ton of dictionaries to setting vars in classes like this I always forget about the comma. But pull your hair out over it once and you'll always know what to look for! Aww sphincters. Thanks for the assist! @nickvans Please accept this as an answer for others to find if it helped you out! Sorry! It was non obvious on my phone... Because I want paying attention. Again, thanks a million!
common-pile/stackexchange_filtered
React MUI Autocomplete Store chosen Values im new to React / Typescript. I just want to store the options that a user chose at the Autocomplete component. After that, i'd need to send the chosen values to an API. How do i do this?... Code: <Autocomplete multiple id="tags-roles" options={roles} getOptionLabel={(option) => option.title} renderInput={(params) => ( <TextField {...params} variant='standard' label="Choose Roles" placeholder='Roles' /> I already tried asking ChatGPT and seeing the Autocomplete doc on the MUI page but couldnt find anything You tried creating React.useState and using onChange prop and to update it? @VladVladov yes, i could save the value like this, but in my case it wasnt any helpful because i need the selected values as a string or smth, when i tried to log the value of the selected options, it says: [object Object] can you update your question and provide full code with store and console.log? BTW you can do JSON.stringify(your object) in logging to see the value the value returned from the autocomplete might be an object ,access the value from it and store in the state or just store the data in the state and while making the API call , manipulate the value to a string . Whenever you see the data print as [object Object], it is because the data you are trying to print is being converted to a string and objects don't natively have a convenient way to do that. Like one of the earlier commentors mentioned, you can use JSON.stringify(...the object...) to have a better string output. JSON.parse(...) does the opposite, taking that converted string and giving you back the original value. If the autocomplete is handing you back an object, it sounds like these two pieces might provide you what you need! Allright i got the answere if others are looking for an answere in the future for this case: const handleRolesChange = (event: any, value: any) => { const uniqueRoles = value.filter((role: any, index: number, self: any[]) => self.findIndex((r) => r.value === role.value) === index); setRole(uniqueRoles); } <Autocomplete multiple id="tags-roles" options={roles} value={role} onChange={handleRolesChange} getOptionLabel={(option) => option.title} renderInput={(params) => ( <TextField {...params} variant='standard' label="Choose Roles" placeholder='Roles' /> Dig into the MUI Autocomplete docs and you will find examples, play with them and combine them and you will get code like this codesandbox Basically, set up your state. Mutate as needed. Then when you are ready grab those values and send them to your API as needed.
common-pile/stackexchange_filtered
Redirecting from Facebook/Instagram in-app browser to default browser on iOS I am trying to create a redirect to the default browser if a user opens my website link using the Facebook or Instagram in-app browser. So far, my solution works on Android, where a dialog box informs the user that they are about to leave the app, and the user has to click "Continue." This behavior is acceptable for my needs. However, on iOS/iPhone, my code doesn't seem to work at all. I can't figure out how to make the code work on iOS as well. I suspect it might be related to the fact that iOS does not support the googlechrome:// scheme in the same straightforward way Android supports intent://. I tried using http:// as a fallback, but that didn't work either. Here is my current code: (function() { function isFacebookOrInstagramApp() { var ua = navigator.userAgent || navigator.vendor || window.opera; return (ua.indexOf("FBAN") > -1) || (ua.indexOf("FBAV") > -1) || (ua.indexOf("Instagram") > -1); } if (isFacebookOrInstagramApp()) { var url = window.location.href; var iosUrl = 'googlechrome://' + url.replace(/^https?:\/\//, ''); var androidUrl = 'intent://' + url.replace(/^https?:\/\//, '') + '#Intent;scheme=http;package=com.android.chrome;end'; // Check if the device is iOS or Android if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { window.location.href = iosUrl; } else if (/Android/i.test(navigator.userAgent)) { window.location.href = androidUrl; } else { // Fallback for other devices window.location.href = 'http://' + url.replace(/^https?:\/\//, ''); } } })(); I resorted to using branch.io in order to get this to work Thanks! I will try to look into branch.io:) Is this solution still working for you on Android? I have tried this approach, but on Android it's not working for both Instagram and Facebook.
common-pile/stackexchange_filtered
How do I pass a function as a parameter to in elisp? I'm trying to pass one method to another in elisp, and then have that method execute it. Here is an example: (defun t1 () "t1") (defun t2 () "t1") (defun call-t (t) ; how do I execute "t"? (t)) ; How do I pass in method reference? (call-t 't1) First, I'm not sure that naming your function t is helping as 't' is used as the truth value in lisp. That said, the following code works for me: (defun test-func-1 () "test-func-1" (interactive "*") (insert-string "testing callers")) (defun func-caller (callee) "Execute callee" (funcall callee)) (func-caller 'test-func-1) Please note the use of 'funcall', which triggers the actual function call. Yes, you definitely want to avoid trying to use the symbols t and nil as names for anything. (Except, of course, for themselves -- evaluating them yields the same symbol back.) The func-caller function is redundant in this scenario, of course, unless you needed it to evaluate some additional code upon every such function call. The note towards the end of "§13.7 Anonymous Functions" in the Emacs Lisp manual says that you can quote functions with #' instead of ' to signal to the byte compiler that the symbol always names a function. Above answers are okey, but you can do something more interesting with defmacro, wich evaluates functions later for some reason: (defun n1 () "n1") (defmacro call-n (n) (apply n)) (call-n (n1)) A practical example with a for loop that takes any amount of functions and their arguments: (defmacro for (i &optional i++ &rest body) "c-like for-loop" (unless (numberp i++) (push i++ body) (setq i++ 1)) (while (/= i 0) (let ((args 0)) (while (nth args body) (apply (car (nth args body)) (cdr (nth args body))) (setq args (1+ args)))) (setq i (- i i++)) ) )
common-pile/stackexchange_filtered
Better way to terminate / stop / kill Spark jobs from a Play Framework controller using an API? I do have a controller named SparkJobController class SparkJobController @Inject()(cc: ControllerComponents, actorSystem: ActorSystem)(implicit exec: ExecutionContext) extends AbstractController(cc) { val jobsMap = scala.collection.mutable.Map.empty[String, SparkAppHandle] /* POST request that takes ID to pass to the spark-submit (to be) jar */ def run: Action[AnyContent] = Action.async { request => request.body.asJson.map { json => Json.fromJson[String](json).asOpt match { case Some(id) => val job = new SparkLauncher() .setSparkHome("/usr/local/spark") .setMaster("local[*]") .setAppName("spark-app") .setAppResource("/usr/abc/spark.jar") .setMainClass("example.job.MainClass") .addAppArgs(id) val jobHandle = job.startApplication() jobsMap += (appId -> jobHandle) Future.successful(Ok(Json.toJson(appId))) case None => Future.successful(BadRequest) } }.getOrElse(Future.successful(BadRequest)) } /* POST request to kill a job taking ID returned by run API */ def stop: Action[AnyContent] = Action.async { request => request.body.asJson.map { json => Json.fromJson[String](json).asOpt match { case Some(appId) => jobsMap.get(appId).map { job => job.kill() Future.successful(Ok(Json.toJson(s"Successfully stopped application with appId = $appId."))) }.getOrElse(Future.successful(NotFound(Json.toJson("Couldn't find in queue.")))) case None => Future.successful(BadRequest) } }.getOrElse(Future.successful(BadRequest)) } } I want to persist the jobsMap in database or in the cache somewhere (Redis may be). How can I do that? Or if not, what should I do to make a queuing system that gets job requests from API (run) and provides an API (stop) to stop/kill/terminate running jobs. What is the most graceful way to do this? FYI, Spark version is 2.3.1 Play version is 2.6.13 Scala version is 2.11.11 Did you consider using https://github.com/RedisLabs/spark-redis? That's cool. I am checking it out.
common-pile/stackexchange_filtered
Is this concept possible with iOS navigation tools Lets say we have a starting point, (x,y). By using iOS navigation can we tell how far from that starting point we moved to another location (a,b). So if i walked 20 feet in a certain direction after starting would it be able to tell me how far I've moved and in which direction? If this technology exists can I get info on where to start learning about it? This also needs to be done without GPS, sorry. GPS can't necessarily detect small changes. I'm not sure whether or not 20 feet is a big enough change for GPS to accurately detect. Yes sorry, @rmaddy i meant to include without using gps No, you can't determine location changes accurately without GPS, even with GPS it is difficult to accuracy measure position change as small as 20 feet (GPS 5m accuracy means a +/-15 foot error) In theory you might be able to write software to create an Internal Navigation System using the built in accelerometers, gyros, and magnetometers, but in practice they are too noisy and have too much error for this kind of use (see this question). A better rocket scientist than me might be able to make it work but it was also need to use the GPS to keep it from drifting. The M7 chip on the 5S might make this feasible.
common-pile/stackexchange_filtered
Listen to body attach event I have written a script which will be included in <head> tag of an HTML page. It is supposed to add a special marker <div> in body and attach a listener on it before any other script in body is executed. I cannot consume DOMContentLoaded event as it will be fired after all scripts have been loaded and executed. If there a way I can get an event as soon as <body> is appended to document, my job is done. May you post an [mcve] of your issue? use promises .then, .then, when the first function get executed it will do .then, something like callback I just updated my post. I'm writing a library which will be included by developer in his website. Sorry for the confusion.
common-pile/stackexchange_filtered
Opening a browser within native mobile app I'm developing a native mobile app for Android and iOS using PhoneGap.I have a requirement to open a hyperlink in my applcation. I don't want the user to navigate away from my application by opening it in device's browser. Also I need to reuse the cookies that I set in my native app in the application that will be opened from the URL. How do I open link in a browser (which has Address bar) within my native app? I have seen in iOS apps like GMail, Facebook app etc, a browser can be opened within the application. Could you please help me to implement this? Please let me know if my question is not clear or need any further details. Thanks in advance. There is a plugin called Childbrowser (as Kerri suggest). It exists for several platforms (iOS, Android...) and is used very widely. Take a look here: https://github.com/purplecabbage/phonegap-plugins/tree/master/iPhone/ChildBrowser https://github.com/phonegap/phonegap-plugins/tree/master/Android/ChildBrowser What I've done in the past is create a "WebView" view controller which has properties such as URL and Title. The view it controls is simply a UIWebView and when you want to open a page inside your app you do something like: WebViewController *view = [[WebViewController alloc] initWithNibName:@"WebView" bundle:nil]; view.passedURL = self.url; view.title = self.nameLabel.text; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:view]; [self presentModalViewController:navController animated:YES]; [view release]; [navController release]; This slides it up from the bottom and loads the web page. Thanks for your reply, I'll surely give a try. We need to do that in platform independent manner. I use the ChildBrowser plugin -- it essentially does what @bipolarpants is doing, but already has the interface with icons built. That's for iOS... I can't help you with Android. :-(
common-pile/stackexchange_filtered
Angular 1.3 getter setter ng-model Im starting to learn the new features in angular 1.3, and i don`t understanding this feature, what he does and what is benefit? This will be a good place to read the benefits and the basic usage of ngModel https://docs.angularjs.org/api/ng/directive/ngModel I dont mean all ngModel im only mean the new feature of getter setter, and i read the docs and dont understand thats why im asking here. From the angular documentation, they state that the getter/setter function can be helpful because it's sometimes "useful to use this for models that have an internal representation that's different than what the model exposes to the view." That being said, the getter/setter method just attaches itself to the ngModel of whatever DOM element it is connected to, and either sets, or gets the current model value. The JavaScript equivalent to this would be something like: this.getValue = function() { return this.value; }: this.setValue = function(val) { this.value = val; }; document.getElementById('el').addEventListener('change', setValue );
common-pile/stackexchange_filtered
Where does YouTube's offline feature store video files? I'm using YouTube offline feature on my Android device, so that I can playback the offline videos within the YouTube app even there is no internet connection. When I searched for any of the video files, I can't find them on device/SD card memory. Are they encrypting the file so that it can be played only with YouTube app? Does anyone know the specific folder for offline video data? The location for those videos on my Samsung Galaxy Tab 2 is as below: Internal storage/Android/data/com.google.android.youtube/files/Offline/(system generated folder name)/streams There might be a minor change to this location or path on other Android devices, but all those downloaded files are saved as .exo files, in an Internal Storage of a device! But it is also true (to the best of my knowledge) that those "offline" videos can only be played using official YouTube App, and those videos simply can not be played using any other Video/Media player application. YouTube (means Google) controls the access to the offline file. The permission is controlled on their server per account basis, to access those downloaded files. There are 2 other discussions related to offline functionality here and here, which should be helpful to enrich the info about YouTube offline feature. Offline YouTube videos don't vanish after 48 hours Read more at: http://indiatoday.intoday.in/technology/story/surprise-offline-youtube-videos-dont-vanish-after-48-hours/1/407062.html @Sanjeev OK, edited the Answer to remove 48 hr line and thanks for hint
common-pile/stackexchange_filtered
Browser downloads a file instead of showing my website when I visit it I have tried various troubleshooting methods such as analyzing the .htaccess file, changing the PHP version, checking the theme files, and disabling any conflicting plugins, but unfortunately, none of these solutions have resolved the issue. File is downloading when I visit Homepage or any category page. If I open any blog post directly it’s working fine. I'm running unmanaged server ubunto, bought from Contabo, Any solution for it? The file that is downloading has this code like this: https://i.imgur.com/ENdrcI6.png .htaccess file code: # BEGIN WP Rocket v3.15.1 # Use UTF-8 encoding for anything served text/plain or text/html AddDefaultCharset UTF-8 # Force UTF-8 for a number of file formats <IfModule mod_mime.c> AddCharset UTF-8 .atom .css .js .json .rss .vtt .xml </IfModule> # FileETag None is not enough for every server. <IfModule mod_headers.c> Header unset ETag </IfModule> # Since we’re sending far-future expires, we don’t need ETags for static content. # developer.yahoo.com/performance/rules.html#etags FileETag None <IfModule mod_alias.c> <FilesMatch "\.(html|htm|rtf|rtx|txt|xsd|xsl|xml)$"> <IfModule mod_headers.c> Header set X-Powered-By "WP Rocket/3.15.1" Header unset Pragma Header append Cache-Control "public" Header unset Last-Modified </IfModule> </FilesMatch> <FilesMatch "\.(css|htc|js|asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$"> <IfModule mod_headers.c> Header unset Pragma Header append Cache-Control "public" </IfModule> </FilesMatch> </IfModule> <IfModule mod_mime.c> AddType image/avif avif AddType image/avif-sequence avifs </IfModule> # Expires headers (for better cache control) <IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 1 month" # cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5) ExpiresByType text/cache-manifest "access plus 0 seconds" # Your document html ExpiresByType text/html "access plus 0 seconds" # Data ExpiresByType text/xml "access plus 0 seconds" ExpiresByType application/xml "access plus 0 seconds" ExpiresByType application/json "access plus 0 seconds" # Feed ExpiresByType application/rss+xml "access plus 1 hour" ExpiresByType application/atom+xml "access plus 1 hour" # Favicon (cannot be renamed) ExpiresByType image/x-icon "access plus 1 week" # Media: images, video, audio ExpiresByType image/gif "access plus 4 months" ExpiresByType image/png "access plus 4 months" ExpiresByType image/jpeg "access plus 4 months" ExpiresByType image/webp "access plus 4 months" ExpiresByType video/ogg "access plus 4 months" ExpiresByType audio/ogg "access plus 4 months" ExpiresByType video/mp4 "access plus 4 months" ExpiresByType video/webm "access plus 4 months" ExpiresByType image/avif "access plus 4 months" ExpiresByType image/avif-sequence "access plus 4 months" # HTC files (css3pie) ExpiresByType text/x-component "access plus 1 month" # Webfonts ExpiresByType font/ttf "access plus 4 months" ExpiresByType font/otf "access plus 4 months" ExpiresByType font/woff "access plus 4 months" ExpiresByType font/woff2 "access plus 4 months" ExpiresByType image/svg+xml "access plus 4 months" ExpiresByType application/vnd.ms-fontobject "access plus 1 month" # CSS and JavaScript ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" </IfModule> # Gzip compression <IfModule mod_deflate.c> # Active compression SetOutputFilter DEFLATE # Force deflate for mangled headers <IfModule mod_setenvif.c> <IfModule mod_headers.c> SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding # Don’t compress images and other uncompressible content SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png|rar|zip|exe|flv|mov|wma|mp3|avi|swf|mp?g|mp4|webm|webp|pdf)$ no-gzip dont-vary </IfModule> </IfModule> # Compress all output labeled with one of the following MIME-types <IfModule mod_filter.c> AddOutputFilterByType DEFLATE application/atom+xml \ application/javascript \ application/json \ application/rss+xml \ application/vnd.ms-fontobject \ application/x-font-ttf \ application/xhtml+xml \ application/xml \ font/opentype \ image/svg+xml \ image/x-icon \ text/css \ text/html \ text/plain \ text/x-component \ text/xml </IfModule> <IfModule mod_headers.c> Header append Vary: Accept-Encoding </IfModule> </IfModule> <IfModule mod_mime.c> AddType text/html .html_gzip AddEncoding gzip .html_gzip </IfModule> <IfModule mod_setenvif.c> SetEnvIfNoCase Request_URI \.html_gzip$ no-gzip </IfModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTPS} on [OR] RewriteCond %{SERVER_PORT} ^443$ [OR] RewriteCond %{HTTP:X-Forwarded-Proto} https RewriteRule .* - [E=WPR_SSL:-https] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=WPR_ENC:_gzip] RewriteCond %{REQUEST_METHOD} GET RewriteCond %{QUERY_STRING} ="" RewriteCond %{HTTP:Cookie} !(wordpress_logged_in_.+|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_) [NC] RewriteCond %{REQUEST_URI} !^(/(?:.+/)?feed(?:/(?:.+/?)?)?$|/(?:.+/)?embed/|/(index.php/)?(.*)wp-json(/.*|$))$ [NC] RewriteCond %{HTTP_USER_AGENT} !^(facebookexternalhit|WhatsApp).* [NC] RewriteCond "%{DOCUMENT_ROOT}/wp-content/cache/wp-rocket/%{HTTP_HOST}%{REQUEST_URI}/index%{ENV:WPR_SSL}%{ENV:WPR_WEBP}.html%{ENV:WPR_ENC}" -f RewriteRule .* "/wp-content/cache/wp-rocket/%{HTTP_HOST}%{REQUEST_URI}/index%{ENV:WPR_SSL}%{ENV:WPR_WEBP}.html%{ENV:WPR_ENC}" [L] </IfModule> # END WP Rocket # BEGIN LSCACHE ## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ## <IfModule LiteSpeed> RewriteEngine on CacheLookup on RewriteRule .* - [E=Cache-Control:no-autoflush] RewriteRule \.litespeed_conf\.dat - [F,L] ### marker CACHE RESOURCE start ### RewriteRule wp-content/.*/[^/]*(responsive|css|js|dynamic|loader|fonts)\.php - [E=cache-control:max-age=3600] ### marker CACHE RESOURCE end ### ### marker LOGIN COOKIE start ### RewriteRule .? - [E="Cache-Vary:,wp-postpass_a32e1c423bc7b98d00670577598ed785"] ### marker LOGIN COOKIE end ### ### marker FAVICON start ### RewriteRule favicon\.ico$ - [E=cache-control:max-age=86400] ### marker FAVICON end ### ### marker DROPQS start ### CacheKeyModify -qs:fbclid CacheKeyModify -qs:gclid CacheKeyModify -qs:utm* CacheKeyModify -qs:_ga ### marker DROPQS end ### </IfModule> ## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ## # END LSCACHE # BEGIN NON_LSCACHE ## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ## ## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ## # END NON_LSCACHE # BEGIN WordPress # The directives (lines) between "BEGIN WordPress" and "END WordPress" are # dynamically generated, and should only be modified via WordPress filters. # Any changes to the directives between these markers will be overwritten. <IfModule mod_rewrite.c> RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress Website URL: https://hpusermanualguide.com/ What file is downloaded? I can't read the file properly, it's just downloading with the name of "download" no any extension. BTW you can check it by visiting the website: https://hpusermanualguide.com/ Please open the file with a text editor. The fact that it does not have a "file name extension" does not somehow magically make its content unreadable. File name extensions are something from the 1980th, no operating system relies on those any more. With the exception of MS-Windows, sad enough. Also take a look into the console of your browser, check the response headers of the response you get from the server. Add that information to the question itself, not as a comment here. Really sorry, I added the SS in Question. I also check for header in network tab but there is nothing that load. Can you please take a look by visiting the website? Please add the content of that ".htaccess" file to the question. And also any other configuration rules that might be in place. Thank you so much for the guidance, I added the htaccess code as well. :) I stumble over that last catch-all rule in the configuration file that appears to deliver something from some cache instead of normally processing the content. Just looks funny to me. But overall this setup is unbelievable complex, never seen something like that, good luck with debugging that. You might want to temporarliy enable rewrite logging to understand what is actually going on inside your rewriting logic. I assume you do have a local dev environment where you can test and debug, of course. If I use Firefox your site is giving a content-type: application/octet-stream header. If I use Curl on the command line I get content-type: text/html; charset=UTF-8. My guess is that your rules for HAVE_Accept-Encoding are messing up. Try removing them. Probably by uninstalling WP Rocket. Thank you so much Stephen let me try it.
common-pile/stackexchange_filtered
How to make search results include subdocument using .find() in Node js with MongoDB Good Day, For context, I am using node js, express and MongoDB in my project. I have this code: router.get('/test3', async (req, res) => { const cookies = req.cookies; // eslint-disable-next-line dot-notation const to = cookies['to']; console.log.apply(to); SearchDb.findOne({"to": to}, (err, item) => { console.log(item); }); res.json("see cnsole"); }); and it returns something like this on the terminal School { _id: new ObjectId("619be4e74c6a2504334f4a4d"), from: 'Home', to: 'School', step: [ { _id: new ObjectId("61a733c0a7614d6ba7f91561"), start: 'Home', vehicle: 'Taxi', end: 'School', cost: 100, ave_time: 20 } ] } However, I don't really want to use .findOne(), I want to use .find() in case there are multiple search results, when I replace .findOne with .find() though, this is what shows on the terminal School { _id: new ObjectId("619be4e74c6a2504334f4a4d"), from: 'Home', to: 'School', step: [ [Object] ] } The subdocument "step" now returns [ [Object] ], which makes it hard to do things like item.step.length since it will now return undefined. What should be done to make .find() show the whole document including the subdocuments just like .findOne? @Bsn try this here I'm sending your result on front try POSTMAN for get or browser in console you are getting [object] but in your actual result you will get whole array of an object :) router.get("/test3", async (req, res) => { const cookies = req.cookies; // eslint-disable-next-line dot-notation const to = cookies["to"]; console.log.apply(to); try { SearchDb.find((err, item) => { res.json(item); }); } catch (err) { res.json(err); } });
common-pile/stackexchange_filtered
Receive POST from External Form I have a form on another website (using a different backend) that I want to be able to POST to my Rails application (on a different domain). How do I generate a valid authenticity token for the external form so that my Rails app will accept it? Assuming I can do the answer to the above question--is there anything else special I need to do to make this work? Apart from the authenticity token, the rest of it seems pretty straightforward to me... Thanks for the help! You can't generate an autenticity token from outside your Rails app. What you can do, is to disable the token protection only for this action and use a custom implementation based on a before_filter. skip_before_filter :verify_authenticity_token, :only => :my_action before_filter :verify_custom_authenticity_token, :only => :my_action def verify_custom_authenticity_token # checks whether the request comes from a trusted source end You could just remove the check by adding a filter like: skip_before_filter :verify_authenticity_token, :only => :action_name Doesn't this open me up to anyone posting to my rails app? Isn't this a security concern? You can add whatever other verification mechanism you want (ip address, whatever) in another filter, for example.
common-pile/stackexchange_filtered
issue with angular2 routing i have an issue using Angular2 routings , i build an application with three buttons , each button takes me to a specific route. This is my app-routing.module page : /***** importation Components****/ import {NgModule} from '@angular/core'; import {DashboardComponent} from './dashboard/dashboard.component'; import {PlayersComponent} from './players/players.component'; import {PlayerDetailsComponent} from './player-details/player-details.component'; import {RouterModule,Routes} from '@angular/router'; const routes : Routes=[ { path : '',redirectTo:'dashboard',pathMatch: 'full'}, { path: 'dashboard',component:DashboardComponent}, { path: 'players',component:PlayersComponent}, { path: 'detail/:id',component:PlayerDetailsComponent} ] ; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {} This is my app.component.html page that containes the buttons : <ul class="nav nav-pills nav-justified" > <li class="element" role="presentation" ><a routerLink="/dashboard" routerLinkActive="active">Dashboard</a></li> <li class="element" role="presentation" ><a routerLink="/players" routerLinkActive="active">Players</a></li> <li class="element" role="presentation" ><a href="test">Statistics</a></li> </ul> <router-outlet></router-outlet> My app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; /***********Importation Components********************/ import { AppComponent } from './app.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { PlayersComponent } from './players/players.component'; import { PlayerDetailsComponent } from './player-details/player-details.component'; /*****Importaion Service*******************************/ import {PlayerService} from './player.service'; /**** Importation fichier routing**************/ import {AppRoutingModule} from './app-routing.module'; @NgModule({ declarations: [ AppComponent, DashboardComponent, PlayersComponent, PlayerDetailsComponent ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [PlayerService], bootstrap: [AppComponent] }) export class AppModule { } and when i click a button it dosen't take me to component i want , On the other hand if i type the path in adress bar it take me to the component adequate . i guess my routing version is this : "scripts": {}, "typings": "./router.d.ts", "version": "4.1.3" } EDIT : i found out that after removing recent updates i have done the routing starts working again. Those are my 2 pages i have updated. dashboard.component.html import { Component, OnInit } from '@angular/core'; import {Player} from '../player'; import {PlayerService} from '../player.service'; import {Router} from '@angular/router'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { players : Player[] = []; bestPlayer:Player; data:Player[]; max:number =0; constructor(private playerService : PlayerService ,private router: Router) { } ngOnInit() { this.playerService.getPlayers() .then(players=> this.players = players); this.data=this.playerService.getDatas(); for (var i = 0; i <= this.data.length; i++) { if (this.data[i].likes>this.max) { this.max=this.data[i].likes; this.bestPlayer=this.data[i]; } } } viewDetails(bestPlayer: Player):void{ this.router.navigate(['/detail',this.bestPlayer.id]); } } <div class="container well-sm bloc" > <div class="row"><h1 style="font-family: 'Lobster', cursive;color: white"><span class="glyphicon glyphicon-star" style="color: #FFC153"></span> Player of the week is </h1> </div> <div > <h2>{{bestPlayer.name}} <span class="badge badge1">{{bestPlayer.number}}</span></h2> <h2>with : {{max}} Likes <span class="glyphicon glyphicon-heart " style="color: red"></span></h2> <br><button class="btn btn-success" (click)="viewDetails(bestPlayer)">View player details</button> </div> </div> Could you please add the configuration of you app module? @Jota.Toledo i did check the edit There are 2 routings? AppRoutingModule and routing? @Jota.Toledo No routing is a const in AppRoutingModule i only added it to test , i delet it and i have the same issue always Can you reproduce the problem in a plnkr? For example here http://plnkr.co/edit/o077B6uEiiIgkC0S06dd @Jota.Toledo here we go http://plnkr.co/edit/dBh42S4riDBxVOpFQQUh @Jota.Toledo actually i founded whats bloc the routing , i delete a page i added it recently and the routing worked again . i'am adding the dashboard.component.ts and dashboard.component.html on my question check them out Im waiting for the update It isnt clear what solved the problem, you could write an answer to the question with a clear explanation yourself @Jota.Toledo ok thanks for your help man try with: In app.component.html <a [routerLink]="['dashboard']">Dashboard</a> <a [routerLink]="['players']">Players</a> <router-outlet></router-outlet> router config const routes : Routes=[ { path : '',redirectTo:'dashboard',pathMatch: 'full'}, { path: 'dashboard',component:DashboardComponent}, { path: 'players',component:PlayersComponent}, { path: 'detail/:id',component:PlayerDetailsComponent} ] ; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {} import {AppRoutingModule} from './app-routing.module'; @NgModule({ declarations: [ AppComponent, DashboardComponent, PlayersComponent, PlayerDetailsComponent ], imports: [ AppRoutingModule, BrowserModule, FormsModule, HttpModule, ], providers: [PlayerService], bootstrap: [AppComponent] }) export class AppModule { } Be careful: you can only call RouterModule.forRoot() once. It seems that you have to calls of this function in your app @Jota.Toleda this is what i tried and its always the same issue I found out that an issue in my dashboard.component.ts is causing the problem. i wrote a function that get and show the "best player" in my array of objects (the player who has more likes). this is what the function looks like ngOnInit() { this.playerService.getPlayers() .then(players=> this.players = players); this.data=this.playerService.getDatas(); for (var i = 0; i <= this.data.length; i++) { if (this.data[i].likes>this.max) { this.max=this.data[i].likes; this.bestPlayer=this.data[i]; } } } viewDetails(bestPlayer: Player):void{ this.router.navigate(['/detail',this.bestPlayer.id]); } when i run the app the browser show me an error function in the console "this.data[i] is undefined" but the app runs anyway. when i delete this the router starts working again
common-pile/stackexchange_filtered
How to communicate different rectangle positions between classes python Here I have 2 classes; Player and Obstacle. Player has some basic movement with input from keys. I change Player.rect.x to change the position of player. In Obstacle I have a code that detects if the Player.rect.x reaches the same x postion as Obstacle.rect.x, if so print "test". Code: import pygame pygame.init() class Player(pygame.sprite.Sprite): def __init__(self): #initializing code def movement(self): #code for movement def update(self): self.movement() class Obstacle(pygame.sprite.Sprite): def __init__(self): #intitializing code def test(self): player_char = Player() if self.rect.x == player_char.rect.x : print("test") def update(self): self.test() I used print statements to figure out that player_char.rect.x changes in the Player class but not in the Obstacle class. Hence player_char.rect.x stays the same as it was when we did move it. player_char.rect.x simply doesn't update so the if statement will never become true. How can I update player_char.rect.x in Obstacle class also? I am pretty new to python so this might turn out to be a stupid mistake. It's hard to tell what your question is. If you want to compare a Player object with an Obstacle you can overide __eq__ for example. player_char = Player() creates a completely new player object and does not refer to an existing one. If you want to detect the collision of objects, see How do I detect collision in pygame? Your test doesn't look at an existing player. It creates a BRAND NEW character, and then compares the location. You would need to pass the player you want to check into Obstacle.test so it can fetch the location. I assume you have a global player object, or maybe a list of players.
common-pile/stackexchange_filtered
URL changes when using ErrorDocument 403 in .htaccess I have written a .htaccess file to make sure that visitors are always redirected to https and to www. In addition to that I have also added a custom html page for 404 errors. When visitors try to access a forbidden file I want them to see my custom 404 message, as to not reveal that the path contains a forbidden file. Here is the problem. When writing for example "example-domain.com/.htaccess" (no www or https) in the browser, the URL in the address field in the browser changes to "https://www.example-domain.com/missing.html". But I want it to say "https://www.example-domain.com/.htaccess" while displaying my 404 page. It works for 404 errors. But when typing in a path in the address field which both triggers the 403 error and fulfill at least one of the rewrite conditions in my .htaccess file (missing https and/or www) I experience the above described problem. Here is the code in the .htaccess file: RewriteEngine On RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} ^example-domain.com [NC] RewriteRule ^(.*)$ https://www.example-domain.com/$1 [L,R=301,NC] ErrorDocument 403 /missing.html ErrorDocument 404 /missing.html Best regards What you describe shouldn't happen with the directives posted on Apache (or LiteSpeed). What webserver are you on / version? How is .htaccess being blocked? Can you confirm the HTTP redirects (and status codes) you are seeing in the browser. Do you have any other directives in the .htaccess file? Any other .htaccess files? Server config?
common-pile/stackexchange_filtered
Assigned Generator Class on Hibernate Annotations Hibernate newbie here. I am working on a simple Hibernate mapping file. When I am using the xml approach, I set the generator class to assigned. There are certain logic that must be checked before an employee id is assigned so I cant generate it automatically. <id name="id" type="string" column="emp_id"> <generator class="assigned"> </generator> </id> But I am also studying the annotation type and annotation seems to be in thing nowadays as frameworks are moving away from configuration files. But I cant find any generation type to match the assigned value public class Employee{ String id; @column(name="emp_id", unique=true) public String getID(){ return id; } } Does this mean that I dont need to add any sequence generator annotation when it is assigned? Thanks Just use the @Id annotation which lets you define which property is the identifier of your entity. You don't need to use the @GeneratedValue annotation because I don't think you want hibernate to generate this property for you. @Id String id;
common-pile/stackexchange_filtered
Docker - Share environment variables with referenced volume containers Is there a possibility to let Docker share the environment variables of containers that are linked with --volumes-from at runtime, the same way it does with containers linked with --link? I'm using data-only containers for persistent data in my applications and I would like to check in the entrypoint script of my application container whether or not a data container was referenced at runtime and cancel if there is none. My idea was checking whether or not the environment variable of the data container (containing the path of the exposed volume) was set, I was also planning on using its value at certain points in the script (e.g. setting the data directory of my application in its configuration files). Is there any way to achieve this and if not what would be the next best way to do the things I described? I found that docker inspect returns all volumes-from containers under HostConfig.VolumesFrom. This does not completely solve the sharing problem since I would like to check for a fixed value (the environment variable's name) and not a container name and need the variable's value as well, but it's a start. You could save your dot files in the images. @Kosch What dot-files do you mean exactly? Like .bashrc, .bash_profile, etc. places to set variables and other fun stuff. the answers below are really good and speak to separation of concerns related to organizing your configurations. Basically you need a way to get you config on the machine. So it's just a matter of getting the right file to the right place at the right time. I'm not sure I can follow you, I want to share the environment variables between two containers that are connected by the means of --volumes-from. The configuration files of my main machine are not the problem. Is there any way to achieve this and if not what would be the next best way to do the things I described? You cannot expose environment variables from one container to another using --volumes-from. Your application shouldn't necessarily care whether or not a data container was referenced at runtime. You should declare a VOLUME in your Dockerfile so that either (a) the application will initialize a new data store using the anonymous volume that results from the VOLUME directive, or will (b) make use of a volume presented using wither --volumes-from or using -v on the docker run command line. You could simply provide the location of the data volume as an environment variable when you start the application container (-e DATA_PATH=/path/to/my/data). If you care whether the data volume has been "initialized" in some fashion, you can check the DATA_PATH location for a specific flag file of some sort (if ! [ -f "$DATA_PATH/flagfile" ]; then ...). I actually want the data container to be mandatory to encourage separation of application and data for similar reasons as described in http://stackoverflow.com/questions/18496940/how-to-deal-with-persistent-storage-e-g-databases-in-docker and the referenced articles. Using runtime environment variables is a good idea, however I feel like they don't really enforce the data containers as they can be used with runtime volumes as well.
common-pile/stackexchange_filtered
How to map enum with ebean? I am using play framework 2 and ebean I have such enum, and saving Integer id at database public enum Permission { local$company$company_panel(2_001, "local.company.company_panel", "вход в компанийскую админку ") Integer id; String name; String description; Permission(Integer id, String name, String description) { this.id = id; this.name = name; this.description = description; } @DbEnumValue(storage = DbEnumType.INTEGER) public Integer getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public static Permission findById(Integer id) { for(Permission permission : Permission.values()) { if(permission.getId().equals(id)) { return permission; } } return null; } } Then I have this collection @DbArray @Column(name = "permissions") private List<Permission> permissions = new ArrayList<>(); And when i try to get enum from database, i have such error: Caused by: java.lang.IllegalArgumentException: No enum constant models.permission.Permission.2001 If this is a copy/paste of your code, you wrote "2_001" instead of "2001" in your enum definition. Update : Seeing how your enum is constructed, If you want to use local$company$company_panel, It would seem you have two way of doing that : Permission myPermission = Permission.local$company$company_panel or Permission myPermission = Permission.getById(2001) If you want to be able to access it using Permission.2001 you need to name it 2001 and not local$company$company_panel I have changed it for "2001", it doesn't helps
common-pile/stackexchange_filtered
number of relations that are reflexive and symmetric but not transitive I'm familiar with Number of relations on A that are reflexive and symmetric but not transitive but I'm not clear on how to close out the problem. Let $S$ be a set with $5$ elements. How many relations on $S$ are reflexive and symmetric but not transitive? I totally agree that relations that are all three are equivalence relations and are enumerated by the Bell number $B(5)$. So my thinking is that I'll add up all relations that are reflexive, $2^{20}$, and then add up all the relations that are symmetric, $2^{\binom{5}{2}}$, and then subtract $B(5)$. My problem with this though is that amidst the $2^{20}$ relations that are reflexive, some are ALSO symmetric, and I'm having a lot of trouble figuring out what else I need to subtract by. A similar problem is that I don't know how to count the relations that are ONLY transitive. If I did then (call that number $A$) the answer is just $B(5)-A$. After rereading the linked post, it seems $2^{\binom{5}{2}}$ is the number of relations that are (at least?) reflexive and symmetric. So then the answer is $2^{10}-B(5)=2^{10}-52$. Does that work? Yes, $2^{10}-B(5)$ is correct, since $2^{n\choose 2}=$ the number of reflexive, symmetric, transitive relations $+$ the number of reflexive, symmetric, nontransitive relations, while $B(n)=$ the number of reflexive, symmetric, transitive relations, hence their difference counts what you want. Relation $R$ over $S$ is reflexive and symmetric when:$$\forall x{\in}S~.(\langle x,x\rangle{\in}R\wedge\forall y{\in} S~. (y\succ x\wedge \langle x,y\rangle{\in} R\to\langle y,x\rangle{\in} R))$$ That is to say, if we represent a relation as a $5\times 5$ grid with a check in every cell where the ordinates are in the relation, then the above will be true when every diagonal cell is checked, and a selection from the 10 cells in the upper triangle are check, as are the corresponding cells in the lower triangle. So just count the ways to do this.
common-pile/stackexchange_filtered
Python 3 - transform Form to nested json I am integrating an active campaign with my fastapi endpoint. However when the webhook is called, i get all the fields as a list of tuples. Example: [ ("deal[fields][0][id]", 1), ("deal[fields][0][key]", "My Custom Field"), ("deal[fields][0][value]", "The field value"), ("deal[fields][1][id]", 2), ("deal[fields][1][key]", "My Other Custom Field"), ("deal[fields][1][value]", "The other field value"), ] And I want to transform it to a json, like the example below: { "deal": { "fields": [ { "id": 1, "key": "My Custom Field", "value": "The field value" }, { "id": 2, "key": "My Other Custom Field", "value": "The other field value" } ] } } I'm stuck in how to split, and create this json. I managed only to get a list with the json keys, but couldn't go further for text, value in [ ("deal[fields][0][id]", 1), ("deal[fields][0][key]", "My Custom Field"), ("deal[fields][0][value]", "The field value"), ("deal[fields][1][id]", 2), ("deal[fields][1][key]", "My Other Custom Field"), ("deal[fields][1][value]", "The other field value"), ]: filtered_keys = text.split("[") Any idea / suggestion on how to achieve the result? REGEX is welcomed EDIT: Updated json to valid, as pointed by scott hunter You could start by fixing the syntax error(s). And your example target JSON isn't valid JSON. can you show us how are you fetching the data? @ScottHunter, i've updated the json to be valid. But since there is already a response, you don't have to worry about it. Thank you! @WilliamsBobadilla I'm getting the info as an url encoded form, which is later transformed into this list of tuples res = dict() res['deal'] = dict() res['deal']['fields'] = list() for text, value in [ ("deal[fields][0][id]", 1), ("deal[fields][0][key]", "My Custom Field"), ("deal[fields][0][value]", "The field value"), ("deal[fields][1][id]", 2), ("deal[fields][1][key]", "My Other Custom Field"), ("deal[fields][1][value]", "The other field value"), ]: filtered_keys = text.split("[") if int(filtered_keys[-2][:-1]) == len(res['deal']['fields']): res['deal']['fields'].append(dict()) res['deal']['fields'][int(filtered_keys[-2][:-1])][filtered_keys[-1][:-1]] = value I think this should work. This really solved my problem. Thank you very much!
common-pile/stackexchange_filtered
What is the proper way to handle assembly version? I am looking forward to implementing a daily build for an upcoming project. But before doing that, I need to know how to properly version an assembly. I have the following concerns: Should each assembly have an independent version number or should they all share the same version? Should I use a * version for build and revision? Is revision relevant to daily build? We stamp all the assemblies within our products with the same version number using the following steps: Link all assemblies to an AssemblyInfoCommon.cs containing the version number info: see here for an example. Generate the AssemblyInfoCommon.cs file as part of the build using (in our case) the NAnt asminfo task, Cruise Control .NET and the SVN revision labeller In our case, we don't use the * version. All deployed versions are built on the build server. We don't worry about version number on our desktops. +1 for build numbers by the build server. Builds should be repeatable, which means they should be scripted, and doing them on your desktop makes it too easy to be lazy and "just know" how to do it rather than go through the trouble of creating a build script. The answer really depends on what you are trying to accomplish with the assembly version numbers. If you are doing a ClickOnce deployment and want to do independent downloads of updated assemblies, you will need to have each assembly independently versioned -- otherwise, I think it's often nice to have assembly versions match the software release number. In more complex scenarios you may need another strategy. A scheme I used at a prior company was major.minor.revision.build -- so in version 1.0 of the product, the assembly version and assembly file version on each assembly was <IP_ADDRESS>9 (for example). This made it easy to match up what assemblies were part of which software release, down to the build number. We accomplished this using a pre-compilation search and replace in each AssemblyInfo.cs file to replace a token with the version numbers provided by our automated build process. So Each assembly should have the same version which is typically a combination of the release version ie 3.4 + the build number which is a sequence that represents the number of times that release has been compiled on the build server. The revision is relevant because it demonstrates the number of builds that you have created for that release. You can really do this in one of 2 ways. The first way would be that if you planned a release ie 3.4 then when you start working on that release then that is your major version number and your minor version number increments with the build. Another way to do this is to tightly control the build versions in that when you are ready to perform your release to QA / Regression you set your major version to 3.4 and you leave your minor version number to 0. You keep things tightly controlled this way until you release. This way you can control your service pack numbering through the minor version number. Hope this helps. I would normally agree that all assemblies should have the same version number; however, I would make one caveat to that. If one of the assemblies is used somewhere else outside of this project or if it is considered it's own project it should have it's own version number. It should also probably be moved out of that solution and into it's own. The only reason I mention this is that I have seen numerous occasions where people have an assembly that's used in a couple of other places, but mainly in one place and they try and keep the version straight. It's a bad idea to do that. I think the Single Responsibility Principle applies at the solution/project level as well. As far as numbering goes, I agree with Guy Starbuck (major.minor.revision.build). That's the way I've always done it and it has always worked well. We have a large app (hundreds of assemblies) with frequent releases (about 1 a month). We went for the "give every assembly the same version" but its a constant source of fustration to me that assemblies for 1 version are completely incompatible with those from another, despite the fact that the interfaces of these assmblies rarely (if ever) change. If this is case for you then you might benefit from versioning assemblies separately - each time you update your assembly only bother to increment the version number in cases where you actually want to break assembly binding (for example if the interface changes, or the changes are otherwise significant enoigh that you want to prevent someone from accidentially using the previous version).
common-pile/stackexchange_filtered
Branching in visual studio moves wrong dll's I have a main branch in Visual Studio where my project uses Microsoft.reportViewer dll's with version 10.x.x.x, but when I branch the project to a new branch, ex. from main to production, the Microsoft.ReportViewer dll's get updated to version 12.x.x.x Why does it do this? I have to manually check the dll's everytime i branch and I wan't it to do it correctly. Anyone know how to fix this problem? Is there really nobody who can answer my question? I could really use some help on this issue.
common-pile/stackexchange_filtered
Clear SMB network share credentials in OS X I'm mounting a Windows network share on OS X 10.7 without being asked for the credentials. How can I make OS X forget any stored credential so it asks me? I've already searched all displayed items in the Keychain, but none looks like it belongs to the Finder. These are called Network Passwords and don't actually belong to Finder. You'll probably find them in your "login" keychain if you have a closer look (you can also search for the server's name). Never mind that this is a VNC password, it stores them for AFP and SMB as well. Is it possible to clear them via shell command ? If anyone else but wonders how? Open Finder, the menu select "Go", then "Utilities", then "Keychain Access". Took me a good while to figure that one out... :-)
common-pile/stackexchange_filtered
MATLAB: bsxfun unclear. Want to accelerate minimum distance between segments Using MATLAB, Imagine a Nx6 array of numbers which represent N segments with 3+3=6 initial and end point coordinates. Assume I have a function Calc_Dist( Segment_1, Segment_2 ) that takes as input two 1x6 arrays, and that after some operations returns a scalar, namely the minimal euclidean distance between these two segments. I want to calculate the pairwise minimal distance between all N segments of my list, but would like to avoid a double loop to do so. I cannot wrap my head around the documentation of the bsxfun function of MATLAB, so I cannot make this work. For the sake of a minimal example (the distance calculation is obviously not correct): function scalar = calc_dist( segment_1, segment_2 ) scalar = sum( segment_1 + segment_2 ) end and the main Segments = rand( 1500, 6 ) Pairwise_Distance_Matrix = bsxfun( @calc_dist, segments, segments' ) Is there any way to do this, or am I forced to use double loops ? Thank you for any suggestion bsxfun takes as argument a function C = fun(A,B) where A, B, C should have the same size. Is not the case for your function. what if my function returns a 1 by 6 copy of the scalar, so that A,B and C have the same size ? +1 for minimal example @Mathusalem If you read carefully the requirements for fun argument of bsxfun, the function needs to accept arguments of arbitrary size, which is not your case again (because your args need to be 1x6). I think you need pdist rather than bsxfun. pdist can be used in two different ways, the second of which is applicable to your problem: With built-in distance functions, supplied as strings, such as 'euclidean', 'hamming' etc. With a custom distance function, a handle to which you supply. In the second case, the distance function must be of the form function D2 = distfun(XI, XJ), taking as arguments a 1-by-N vector XI containing a single row of X, an M2-by-N matrix XJ containing multiple rows of X, and returning an M2-by-1 vector of distances D2, whose Jth element is the distance between the observations XI and XJ(J,:). Although the documentation doesn't tell, it's very likely that the second way is not as efficient as the first (a double loop might even be faster, who knows), but you can use it. You would need to define your function so that it fulfills the stated condition. With your example function it's easy: for this part you'd use bsxfun: function scalar = calc_dist( segment_1, segment_2 ) scalar = sum(bsxfun(@plus, segment_1, segment_2), 2); end Note also that pdist works with rows (not columns), which is what you need. pdist reduces operations by exploiting the properties that any distance function must have. Namely, the distance of an element to itself is known to be zero; and the distance for each pair can be computed just once thanks to symmetry. If you want to arrange the output in the form of a matrix, use squareform. So, after your actual distance function has been modified appropriately (which may be the hard part), use: distances = squareform(pdist(segments, @calc_dist)); For example: N = 4; segments = rand(N,6); distances = squareform(pdist(segments, @calc_dist)); produces distances = 0 6.1492 7.0886 5.5016 6.1492 0 6.8559 5.2688 7.0886 6.8559 0 6.2082 5.5016 5.2688 6.2082 0 The funny part is that, internally, pdist uses double loops to compute the pairwise distance. :-) Just edit pdist and look at the code around from line 250 onwards (I have access to Revision: <IP_ADDRESS>) @CST-Link It also says "Call a mex file to compute distances for the standard distance measures" (revision <IP_ADDRESS>). That more or less confirms that it's faster with built-in distance functions I skipped those lines... indeed, for the standard distances and non-sparse input, it will use the MEX function. Thank you both Luis Mendo and CST-Link. In my mind you both provided an answer in which I learned something. I selected the answer at random :/ Your method accelerated my execution time by a factor 1.5 @Mathusalem: See this question and my answer for further tips on speeding up pdist for calculating pairwise Euclidean distance.
common-pile/stackexchange_filtered
Represent a dictionary within a dictionary I am creating UML diagrams that will represent C# code and I've reached somewhat of an impasse. I am currently representing a Dictionary<object, object> by using a qualified association, where the qualification is the key type and the class at the end of the association is the value type. Now I would like to represent a type in UML, like so: Dictionary<int, Dictionary<object, object>. Is there any type of standard I can use to create a relationship that will accurately represent this relationship? Possible duplicate of How can I represent a Python dictionary in UML? Although it's for Python, the principle should be the same. I did find that one and it did help me with representing a singularDictionary object. The problem I am having is I cannot find an explanation for nested Dictionary objects. As in, a Dictionary within a Dictionary. @Peter Oh, I didn't realize an association could have two qualifiers. That's perfect. Thank you very much! Did you want to add this as an answer so I can accept it? @SpencerElliott sorry I spoke too soon; you can have multiple qualifiers, but the meaning of it is a bit different. I will try to write a more complete answer soon. @SpencerElliott speaking of which, could you be a more specific about the context of your problem -- e.g. an actual example instead of just a generic Dict<obj, Dict<obj, obj>>, because there are different ways how to approach that -- also it is not clear what the "user" actually owns in the relationships. That line with angle brackets is merely a declaration that says what relations the class will have. You cannot show the declaration in the UML, except in a note (also useful it can be). But you can (and you should) show the relations themselves. Practically, the line Dictionary<int, Dictionary<object, object> can be taken as a strict declaration of a simple class diagram.
common-pile/stackexchange_filtered
Write tiff 6.0 in strips after output from imagemagick or libtiff I'm adjusting some brightness/contrast of tiff 6.0 images with bytes arranged in strips using imagemagick. The outputs are tiff 5.0 images with bytes in strips. I tried to force the output to tiff 6.0 format by tiffcp -t however the bytes are arranged in tiles. Is there a way to maintain tiff 6.0 specification with strips instead of tiles or any programs/cmd that can adjust brightness/contrast while keeping the same specification? update imagemagick: convert test.tif -brightness-contrast 50,50 result.tif convert-im6.q16: Unknown field with tag 37553 (0x92b1) encountered. TIFFReadDirectory' @ warning/tiff.c/TIFFWarnings/949. convert-im6.q16: Unknown field with tag 37554 (0x92b2) encountered. TIFFReadDirectory' @ warning/tiff.c/TIFFWarnings/949. convert-im6.q16: Unknown field with tag 37554 (0x92b2) encountered. `TIFFReadDirectory' @ warning/tiff.c/TIFFWarnings/949. photoshop brightness:+50 contrast:+50, save in index format without compression and ICC profile both methods yielded tiff 5.0 reflected by jhove. tiffinfo test.tif TIFFReadDirectory: Warning, Unknown field with tag 37553 (0x92b1) encountered. TIFFReadDirectory: Warning, Unknown field with tag 37554 (0x92b2) encountered. TIFF Directory at offset 0x1d4c08 (1920008) Subfile Type: (0 = 0x0) Image Width: 1600 Image Length: 1200 Bits/Sample: 8 Compression Scheme: None Photometric Interpretation: palette color (RGB from colormap) Orientation: row 0 top, col 0 lhs Samples/Pixel: 1 Rows/Strip: 20 Min Sample Value: 0 Max Sample Value: 255 Planar Configuration: single image plane Color Map: (present) Software: SPOT 4.6 DateTime: 2018:06:11 14:30:49 Tag 37553: 355,4014058950 Tag 37554: 0x0,0x1,0x0,0x1,0x8,0x0,0x35,0x0,0x18,0x32,0x30,0x31,0x38,0x3a,0x30,0x36,0x3a,0x31,0x31,0x20,0x31,0x34,0x3a,0x33,0x30,0x3a,0x34,0x39,0x2e,0x30,0x33,0x30,0x0,0x0,0x9,0x0,0x4,0x0,0x0,0x0,0x1,0x0,0x4,0x0,0x8,0x0,0x0,0x0,0x0,0x5,0xf5,0xe1,0x0,0x0,0x8,0x0,0x2,0x0,0x20,0x0,0x38,0x0,0x2,0x0,0x0,0x0,0x1d,0x0,0x1,0x1,0x0,0x3c,0x0,0x8,0x0,0x0,0x1c,0xe8,0x0,0x0,0x1c,0xe8,0x0,0x14,0x0,0x1,0x1,0x0,0x2a,0x0,0x1,0x1,0x0,0x20,0x0,0x1,0x1,0x0,0x74,0x0,0x4,0x0,0x0,0x0,0x1,0x0,0x71,0x0,0x2,0x0,0x1,0x0,0x72,0x0,0x2,0x1,0x1,0x0,0x64,0x0,0x9,0x7a,0x56,0x65,0x74,0x5f,0x44,0x41,0x50,0x49,0x0,0x65,0x0,0x5,0x70,0x72,0x69,0x6e,0x74,0x0,0xc8,0x0,0x2,0x0,0x4,0x0,0xc9,0x0,0x2,0x0,0x6,0x0,0xca,0x0,0x2,0x0,0x4,0x0,0xcb,0x0,0x2,0x0,0x6,0x0,0x66,0x0,0x4,0x32,0x35,0x2e,0x34,0x0,0x67,0x0,0x6,0x32,0x35,0x34,0x30,0x38,0x36,0x0,0x3a,0x0,0x2,0x33,0x32,0x0,0x39,0x0,0x4,0x0,0x1,0x86,0xa0,0x0,0x34,0x0,0xd,0x63,0x36,0x30,0x0,0x31,0x0,0x31,0x0,0xb5,0x6d,0x0,0x31,0x0 TIFFReadDirectory: Warning, Unknown field with tag 37554 (0x92b2) encountered. TIFF Directory at offset 0x1d5690 (1922704) Subfile Type: reduced-resolution image (1 = 0x1) Image Width: 63 Image Length: 47 Bits/Sample: 8 Compression Scheme: JPEG Photometric Interpretation: YCbCr Orientation: row 0 top, col 0 lhs Samples/Pixel: 3 Rows/Strip: 32 Min Sample Value: 0 Max Sample Value: 255 Planar Configuration: single image plane Reference Black/White: 0: 0 255 1: 128 255 2: 128 255 Tag 37554: 0x0,0x39,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x34,0x0,0xd,0x63,0x36,0x30,0x0,0x31,0x0,0x31,0x0,0xb5,0x6d,0x0,0x31,0x0 JPEG Tables: (574 bytes) tiffinfo result.tif TIFF Directory at offset 0x57e408 (5760008) Subfile Type: multi-page document (2 = 0x2) Image Width: 1600 Image Length: 1200 Bits/Sample: 8 Compression Scheme: None Photometric Interpretation: RGB color FillOrder: msb-to-lsb Orientation: row 0 top, col 0 lhs Samples/Pixel: 3 Rows/Strip: 1200 Planar Configuration: single image plane Page Number: 0-2 White Point: 0.3127-0.329 PrimaryChromaticities: 0.640000,0.330000,0.300000,0.600000,0.150000,0.060000 TIFF Directory at offset 0x5807c8 (5769160) Subfile Type: multi-page document (2 = 0x2) Image Width: 63 Image Length: 47 Bits/Sample: 8 Compression Scheme: None Photometric Interpretation: RGB color FillOrder: msb-to-lsb Orientation: row 0 top, col 0 lhs Samples/Pixel: 3 Rows/Strip: 47 Planar Configuration: single image plane Page Number: 1-2 White Point: 0.3127-0.329 PrimaryChromaticities: 0.640000,0.330000,0.300000,0.600000,0.150000,0.060000 test.tif Are you sure you mean tiff 5.0? The tiff 6.0 spec was published in 1992, I don't think tiff 5.0 is still used. Perhaps you mean bigtiff? In any case, imagemagick should always write a strip tiff unless you've asked it to tile. Post an example of the exact command that's failing, a sample image, and the tiffinfo output you get. @jcupitt updated the post with the required info. Thanks for the help. Hi again, the test file you've linked is a JPEG, is that correct? Your result.tif is a strip tiff, not a tiled tiff, though it does have one huge strip, which is odd. I tried with imagemagick7 and it always writes a tiff6 file, you could try updating to that. im6 and im7 both write a sensible rows/strip for me.
common-pile/stackexchange_filtered
Why isn't my array being populated? I have a javascript function that returns 2 Arrays. Each array element is an array, and each of those arrays contains a coursject object. I know this is complicated, but the other people on my team are in charge of generating possible schedules from the classes and they want me to return to them like that. I've run some test on what I have, and for some reason the second level of arrays isn't getting populated or defined. Like if I put one optional class as my input (we have a UI), the OptcourseArray has elements that are undefined. Below is just the code for creating the OptcourseArray. Does it seem to correctly make an array of arrays of objects? I think I must have messed something up in it. For code context: numOptCourses is the number of optional courses. optCourses is an array of course objects. courseNumber is the course number of the class, as is catalog_num. This is so that classes with multiple sections go into the same array. var OptcourseArray = []; var catNum = 0; for(var j = 0; j < numOptCourses; j++){ catNum = optCourses[j].courseNumber; var myArray = []; for(var h = 0; h < OptclassList.length; h++){ if (OptclassList[h].catalog_num === catNum){ myArray.push(OptclassList[h]); } } OptcourseArray.push(myArray); } Acoustic77, Could you possbily provide an example of the output that you are seeing? I mocked up some data and your code certainly seems to be producing an Array of Arrays: [[{"name":"class1","catalog_num":"course1"},{"name":"class2","catalog_num":"course1"}],[{"name":"class2","catalog_num":"course2"}],[{"name":"class3","catalog_num":"course3"}],[{"name":"class4","catalog_num":"course4"}]] Code looks fine. Not much we can do without more information. I suggest you create a http://jsfiddle.net/ that reproduces the problem. Here's a JSfiddle of some of the UI and the full code above http://jsfiddle.net/9KDVX/1/ (code to create possible schedules and send to Full Calendar isn't included). I don't know how to format my output for comments, but I added a "console.log" line to the javascript. I've been testing with just one optional class called EECS 214-0 If you put those files in a folder and test with just EECS 214-0 you'll see the "undefined" that I get for the first element object in the array updated jsfiddle: http://jsfiddle.net/acoustic7/c335t/ It looks like your code is reliant upon the OptclassList which is being constructed on success of your first $.getJSON. Since the operation is asynchronous the code that requires OptclassList is being called before the OptclassList is being generated. That's my current take anyway. I'm correcting the code now. Is this more like what you would like to see? ---- classTest.html:271 [[{"title":"Data Structures & Data Management","professor":"Morteza Amir Rahimi","catalog_num":"214-0","section":"21","subject":"EECS","meeting_days":"MoWeFr","start_time":"11:00:00","end_time":"11:00:00"}]] Duplicate of Why is my variable undefined after I modify it inside of a function? - Asynchronous code reference. You are trying to access OptclassList before it has elements. Read the question to understand how asynchronous code works and how to solve your problem. Acoustic77, Here is the modified queryCourseData method. I converted your $.getJSON to $.ajax using async:false (this may or may not have been an issue on my end, so I encourage you to try and set it to true and test whether it works on your end or not). I then noticed that your startTime and endTime are in the format {hour:#,minute:#} while the item.start_time and item.end_time are time strings in 24 hour format. I wrote some code to convert the former form into 24 hour format ( I am certain there is a more elegant way of doing this than I did). I also later, after my initial answer, noticed that you were setting myArray to [] every step of your inner for loops where you are constructing the ReqcourseArray and OptcourseArrays. Moving var myArray=[] outside of the inner for was my final fix. I left my console.log's in place so you could see the results. function queryCourseData(startTime, endTime, optCourses, reqCourses, numOptCourses, numReqCourses) { var numClasses = optCourses.length; var OptclassList = []; var i = 0; for(var m = 0; m < numClasses; m++) { //IrishGeek82@SO, 2014-06-05 //Your ajax calls were taking too long to call so the code that needed them was //getting called before the data was ready. //This could be a problem on my end so you can always set async to true and test from your end. $.ajax({url:"http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject="+optCourses[m].subject, async: false, dataType: 'json', success:function(result) { //IrishGeek82@SO, 2014-06-05 //Your start and end times are objects of the format //{hour:x, minute:x} //While your item.start_time and item.end_time are 24 hour time strings. //I am sure there is a more elgant way to do this but here is a dirty conversion //from one to the other. var sTime = (startTime.hour<10?"0"+startTime.hour:startTime.hour) + ":" + startTime.minute+"00"; var eTime = (endTime.hour<10?"0"+endTime.hour:endTime.hour) + ":" + endTime.minute+"00"; $(result).each(function (index, item) { if (item.start_time > sTime) { if (item.end_time < eTime) { if (item.catalog_num == optCourses[m].courseNumber) { var coursject = { title: item.title, professor: item.instructor.name, catalog_num: item.catalog_num, section: item.section, subject: item.subject, meeting_days: item.meeting_days, start_time: item.start_time, end_time: item.start_time }; //IrishGeek82@SO //Now Pushing Entries Into Array OptclassList.push(coursject); i++; } } } }); } }); } var OptcourseArray = []; for(var j = 0; j < numOptCourses; j++) { var catNum = optCourses[j].courseNumber; //IrishGeek82@SO //You were resetting your myArray every time you in the loop below. //Subsequently, only the last entry would every get added and you were //getting empty arrays. var myArray = []; for(var h = 0; h<OptclassList.length; h++) { if (OptclassList[h].catalog_num == catNum) { myArray.push(OptclassList[h]); } } OptcourseArray.push(myArray); } console.log("--OPT--"); console.log(JSON.stringify(OptcourseArray)); console.log("--OPT--"); var ReqclassList = []; var g = 0; for(var n = 0; n < reqCourses.length; n++) { //IrishGeek82@SO, 2014-06-05 //Your ajax calls were taking too long to call so the code that needed them was //getting called before the data was ready. //This could be a problem on my end so you can always set async to true and test from your end. $.ajax({url:"http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject="+reqCourses[n].subject, async: false, dataType: 'json', success: function(result) { //IrishGeek82@SO, 2014-06-05 //Your start and end times are objects of the format //{hour:x, minute:x} //While your item.start_time and item.end_time are 24 hour time strings. //I am sure there is a more elgant way to do this but here is a dirty conversion //from one to the other. var sTime = (startTime.hour<10?"0"+startTime.hour:startTime.hour) + ":" + startTime.minute+"00"; var eTime = (endTime.hour<10?"0"+endTime.hour:endTime.hour) + ":" + endTime.minute+"00"; $(result).each(function (index, item) { if (item.start_time > sTime) { if (item.end_time < eTime) { if ($.trim(item.catalog_num) == $.trim(reqCourses[n].courseNumber)) { var coursject = { title: item.title, professor: item.instructor.name, catalog_num: item.catalog_num, section: item.section, subject: item.subject, meeting_days: item.meeting_days, start_time: item.start_time, end_time: item.start_time }; //IrishGeek82@SO //Now Pushing Entries Into Array ReqclassList.push(coursject); g++; } } } }); } }); } var ReqcourseArray = []; for(var j = 0; j < numReqCourses; j++) { var catNum = reqCourses[j].courseNumber; //IrishGeek82@SO //You were resetting your myArray every time you in the loop below. //Subsequently, only the last entry would every get added and you were //getting empty arrays. var myArray = []; for(var h = 0; h < ReqclassList.length; h++) { if ($.trim(ReqclassList[h].catalog_num) == $.trim(catNum)) { myArray.push(ReqclassList[h]); } } ReqcourseArray.push(myArray); } console.log("--REQ--"); console.log(JSON.stringify(ReqcourseArray)); console.log("--REQ--"); return [OptcourseArray, ReqcourseArray]; } The results of my testing are as follows: Test Case: 2 courses EECS 214-0 (optional) EECS 223-0 (required) Results: XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". --OPT-- [[{"title":"Data Structures & Data Management","professor":"Morteza Amir Rahimi","catalog_num":"214-0","section":"21","subject":"EECS","meeting_days":"MoWeFr","start_time":"11:00:00","end_time":"11:00:00"}]] --OPT-- XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". jquery.min.js:4 --REQ-- [[{"title":"Fundamentals of Solid State Engineering","professor":"Koray Aydin","catalog_num":"223-0","section":"01","subject":"EECS","meeting_days":"MoTuWeFr","start_time":"09:00:00","end_time":"09:00:00"}]] --REQ-- Test Case: 5 courses: EECS 214-0 (optional) EECS 223-0 (required) EECS 110-0 (required) EECS 213-0 (required) EECS 203-0 (optional) Results: XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". jquery.min.js:4 XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". jquery.min.js:4 --OPT-- [[{"title":"Data Structures & Data Management","professor":"Amartya Banerjee","catalog_num":"214-0","section":"20","subject":"EECS","meeting_days":"MoWeFr","start_time":"09:00:00","end_time":"09:00:00"},{"title":"Data Structures & Data Management","professor":"Morteza Amir Rahimi","catalog_num":"214-0","section":"21","subject":"EECS","meeting_days":"MoWeFr","start_time":"11:00:00","end_time":"11:00:00"}],[{"title":"Introduction to Computer Engineering","professor":"Hai Zhou","catalog_num":"203-0","section":"01","subject":"EECS","meeting_days":"MoWeFr","start_time":"11:00:00","end_time":"11:00:00"}]] --OPT-- XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". jquery.min.js:4 XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". jquery.min.js:4 XHR finished loading: GET "http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=EECS". jquery.min.js:4 --REQ-- [[{"title":"Fundamentals of Solid State Engineering","professor":"Koray Aydin","catalog_num":"223-0","section":"01","subject":"EECS","meeting_days":"MoTuWeFr","start_time":"09:00:00","end_time":"09:00:00"}],[{"title":"Introduction to Computer Programming","professor":"Aleksandar Kuzmanovic","catalog_num":"110-0","section":"20","subject":"EECS","meeting_days":"MoTuWeFr","start_time":"10:00:00","end_time":"10:00:00"}],[{"title":"Introduction to Computer Systems","professor":"Peter A Dinda","catalog_num":"213-0","section":"20","subject":"EECS","meeting_days":"TuTh","start_time":"14:00:00","end_time":"14:00:00"}]] --REQ-- Please let me know if this helps :) Thank you so much! That fixes it perfectly. I can't thank you enough, all of your changes make sense to me, and I really appreciate you taking the time to go spot those errors.
common-pile/stackexchange_filtered
Finding the real solutions of the radical equation $\sqrt{3x+10}-\sqrt{x+2}=2$ Find the solutions to the following:$$\sqrt{3x+10}-\sqrt{x+2}=2$$ This is what I tried so far: \begin{align*} (\sqrt{3x+10}-\sqrt{x+2})^2 & =2\\ (3x+10)+(x+2)-2\sqrt{(x+2)(3x+10)} & =2\\ 2x+5-\sqrt{3x^2+16x+20} & =0 \end{align*} Now I do not know where to go from here... I just thought I'd point out that your equation is not a polynomial. Hint: $2x+5-\sqrt{3x^2+16x+20}=0\iff2x+5=\sqrt{3x^2+16x+20} \Longrightarrow\\(2x+5)^2=3x^2+16x+20.$ Rather than squaring both sides as stated, it might be more useful to use $$ \sqrt{3x+10}=2+\sqrt{x+2} $$ which can then be squared to get $$ 3x+10 = 6+x+4\sqrt{x+2} $$ You can probably finish it from here for yourself.
common-pile/stackexchange_filtered
Why re-verify with CAPTCHA on failed form entry? Is there a reason for sites to ask for another CAPTCHA verification when some other part of the registration form, e.g. the username, was invalid? what you mean with "another CAPTCHA"? it did ask once and then after an failed login attempt, it show one another CAPTCHA? @VP01: Yes (after a failed registration attempt). If the site has a means of knowing it's the same user in the same session, then no. So for example given a cookie or an ssl session then it seems OK to assume it's still a human user (within the limits of captcha). If it's just a cookie that establishes the session (i.e. this is over http without SSL) then make sure to time it out tho. And you should be using SSL anyhow :-) So this wide-spread practice is just the result of lazy programmers? no if the site, without CAPTCHA is vulnerable to CSRF. The browser being authenticated don't means that the user is authenticated to do this action. Example: http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352 @VP01 - but that is true for every single request. Are you saying that every single request made to the site should have a CAPTCHA? @João Portela, i don't know where in my comment i stated that. Do I? maybe this was a wrong use of words on my part. What I meant was: You said that the CAPTCHA avoids CSRF and that it should be kept even after the first CAPTCHA was successfully filled, to avoid CSRF. I also assumed that if the registration page is vulnerable to CSRF so should all of the other site pages be (there no reason to make the registration page less secure for the user). From that I inferred that if he wanted to prevent CSRF he would have to use a CAPTCHA on every request. Summing up: CAPTCHA is not the right tool to avoid CSRF. @João Portela ooh I so agree. I'd change that though: CAPTCHA is not the right tool. Period. for anything. No. But then, was there a reason to ask for a CAPTCHA in the first place? Let's take a random example of a platform that implements CAPTCHA; say, Stack Exchange. What Stack Exchange sites want is a collection of high-quality questions and answers on a particular topic. There's nothing there that intrinsically requires humans to supply the questions and answers: they just need to be good. This quality of goodness is determined and filtered for after the content has been published, by the community of voters and moderators. There's also no guarantee that once you've determined the layer 8 hardware is a human, they're predestined to provide good content either. Indeed that's the easiest way to circumvent website CAPTCHAs: find some poor people and give them not very much money to fill in CAPTCHAs for you. So implementing a CAPTCHA makes it harder for people (much harder, in some cases, as many CAPTCHA mechanisms are inaccessible to people with sight difficulties) to use the platform, while only making it a little bit harder for people to abuse the platform. In return, you get no useful information related to your goal. Whether CAPTCHAs are useful or not is a subject of discussion. It definitely raises the barrier of entry to spamming, though. Here, I can't see any advantage at all, and was wondering if I had been missing something. @Tim, it is only a very slight barrier. Like trying to stop an automobile using marshmallows. It goes back to the point, using CAPTCHA is misplaced in the first place. @Tim see also this question where the (f)utility of CAPTCHA is discussed. http://security.stackexchange.com/questions/778/anyone-using-asirra-in-production-are-there-similar-alternatives/786#786 I hope I could downvote this answer since only its first 3 chars actually adress que question, you should have made it a comment at most. feel free to start a new question to discuss the effectiveness of using captchas to stop spam. :) @João: my answer addresses the general question "Why verify with CAPTCHA at all?" of which @Tim's question is a specific case. @Graham Lee - if you read the question again you'll see that @Tim implicitly assumes that CAPTCHAS are useful to prevent unwanted registrations, and is just trying to figure why they are requested multiple times when some other part of the registration form is wrong. I think the main reasons are: It is the default behaviour that works out of the box. If the programmer has to rememer that the captcha was solved, he will have to write extra code. And it has to be remembered in a way that cannot be manipulated by the user (e. g. the session), so a <input type="hidden"> field with a flag is no good. After validation of personal information has failed once or twice and the users have to reenter the captcha every time, it gets really annoying. So people are more likely to provide real personal data instead of fake data. (This item only applies to company that ask about a lot of personal information that is not strictly required to offer the service the user is looking for.) As far as usibility for picking usernames is concerned, I suggest to check them right away using Ajax before the form is submitted. Alternativly you can use email addresses which are (mostly) unique. Knowing the username may make it easier for an attacker to crack passwords: A smart attacker, who is not interested in one particular account, will pick a password and then brute forces through usernames. So that is something to keep in mind, unless you have a public user directory anyway. Even without a user directory, there is a set of usernames that are likely picked by people. So a rate limit for failed login attempts is required anyway in order to prevent this kind of attack. That will completely depend on what the purpose of the form is, i.e. what kind of information is being collected. One very common case is a login re-try after a failed login on a website. In this case the CAPTCHA serves a dual purpose: It's making it harder to automate login attemps with a bot, thus making it harder to automate a password guessing attack, and It is slowing down login attempts; making an online brute force attack harder to mount. (Note, this shouldn't be left to the CAPTCHA alone, the backend authentication system should have rate limiting and/or max failed login attemps handling.) It's also common that the entire form has to be re-submitted if just a single field was wrong. There is really no good technological reason for that, it comes from not prioritizing usability. Using SSL, sessions and CSRF protection tokens the webapp can reliably know that the end user solved the CAPTCHA in his first attempt, and then not require CAPTCHA again -- but it's more work to implement this correctly. Sorry, I forgot to mention that I was thinking about registration forms. Disagree strongly with that - the purpose of a captcha system is to verify the user isn't a bot, and that's it (and obviously these systems have limited effectiveness too). But concerns should be separated. Avoiding password guessing is better done via a measure specific to that issue, e.g. back off delays. @frankodwyer: I didn't say that a CAPTCHA should be the only rate limiting mechanism, that's your reading. :-) But I will make it more clear. The reason to change always the challenge is to make harder for bruteforce attacks. Imagine that the CAPTCHA don't change after the first failed try. So a hacker could first try manually to fill in the form, introduce the right challenge and then start a bruteforce tool, that fills the input box form the captchas always with the same value making the CAPTCHA useless. It is useful to create, for example user mass creation in services like for example, gmail. Why would you brute-force a registration form? i fixed my answer :-) I understand that the CAPTCHA should change after a successful registration, but what about failed ones? for example, forms that allows the hacker to do user enumeration. e.g: if in the error message you can identify if the user that you are trying to create already exist. You can use it to find valid users and then do a more precise bruteforce :-) usernames are not supposed to be private, being worried that people could now your username is like being worried about people knowing your public key: from a security point of view they are not supposed to be a secret. maybe in YOUR application it shouldn't be secret. But in other applications, where the user name a social security number is the user, maybe for privacy the stakeholders want that as well private.
common-pile/stackexchange_filtered
javascript alternating row color when data change I want to add alternating colors to rows in a table, but instead of changing color every other row I want to switch color when the data in the first column changed compare to the row above. For example in the table below, the first two row would have the same color since the first fields are both "1", and the third row would have a different color. I'm looking for a solution without third-party libraries like jquery. 1 | A 1 | B 2 | C 3 | D 4 | E Here's one way of doing it: jsfiddle demo This little chunk of code is pretty nice if your table is 1 dimensional: (function(){ var trs = document.getElementById('thetable').getElementsByTagName('tr'); var last, toggle = false; for(var i = 0; i < trs.length; i++){ var tds = trs[i].getElementsByTagName('td'); toggle ^= last != tds[0].innerText; trs[i].style.backgroundColor = toggle ? '#AAAACC' : '#CCDDCC'; last = tds[0].innerText; } })(); JSFiddle If you have tables within your table some modifications would need to be made. If the rows are already sorted, you could just cycle through them and assign classes as needed: var trs = document.getElementById('yourTable').rows, i = 0, l = trs.length, altValue = true, currentTr, tdValue; while (i) { i -= 1; currentTr = trs[i]; tdValue = currentTr.getElementsByTagName('td')[0].innerHTML; if (tdValue !== currentValue) { altValue = altValue ? false : true; } if (altValue) { currentTr.className = currentTr.className ? 'alt' : currentTr.className + ' alt'; } } And this could all be put in a function, so that you don't pollute the global namespace.
common-pile/stackexchange_filtered
The formation keeps breaking apart every time one of the hexapods starts limping. That's the problem with waiting until complete failure. By then the partially faulty robot has already disrupted the collective behavior for minutes. But if we isolate robots too early, we lose functional units unnecessarily. There's this sweet spot where degradation is detectable but the robot can still navigate to safety. Right, like using behavioral feature vectors to characterize normal versus abnormal movement patterns. Instead of just monitoring hardware sensors, we observe how each robot interacts with its neighbors. Exactly. A robot might have perfect sensors but still exhibit
sci-datasets/scilogues
jquery load to hide content There is javascript on my webpage, but I need to hide it from my users (I don't want them to be able to see it because it contains some answers to the game.) So I tried using Jquery .load in order to hide the content (I load the content from an external js file with that call). But it failed to load. So I tried ajax and it failed too. Maybe the problem comes from the fact that I'm trying to load a file located in my root directory, while the original page is located in "root/public_html/main/pages": <script type="text/javascript"> $(document).ready(function() { $.ajax({ url : "../../../secret_code.js", dataType: "text", success : function (data) { $("#ajaxcontent").html(data); } }); }); </script> 1) Why can't I load a file from the root directory with ajax or load method? 2) Is there another way around? PS: I'm putting the file in the root directory so people can't access it directly from their browsers... This won't actually hide anything from your users, only make it very slightly harder to find. @jimw How is that? How can you see JS loaded asynchronously? Is there a way to hide it correctly? Just a tip, I do this all day long, if you use .load to load a "view partial" with js in it, only the html and style script(if available) will show up in error console, the js itself is added to the page header but is not easily made visible, tho a crafty user, can always get the js on a page. if you want real security, use $.ajax and maaintain your "answers" server side sending only what needs to be seen to the client and returning client info in order to get next answer or whatever Adam: Well, it depends when you're loading it: after it's been loaded the user can see it - it's in the client, so he must be able to. If you only load the answers after the user has submitted his answers, then that's not a problem, except if they can come back and try again knowing the answers to the ones they got wrong. What is your system setup? Are you using a CMS? Even if you add the javascript to the page after page load a user with a tool like firebug can go and view it. I don't think what you are doing is really going to secure it. An alternate solution is that you could minify and obfuscate the javascript that you use in your production environment. This will produce near unreadable but functioning javascript code. There are a number of tools that you can run your code through to minify and obfuscate it. Here is one tool you could use: http://www.refresh-sf.com/yui/ If that isn't enough then maybe you could put the answers to the game on your serverside and pull them via ajax. I don't know your setup so I don't know if that is viable for you. I'm on a VPS so I have full access. According to you, I should obfuscate and minify the code - and can I add an additionnal htaccess restriction to prevent users from accessing the js itself? What line would it be (I'm not very familiar with htaccess except for error pages...) Thanks As far as I know, if the browser can access your javascript file so that you can run it then the user can too. I don't think you can grant the browser access and not the user. If you need to hide any data or logic then it will need to live in server-side code. 1) if the file isn't accessible via web browsers, than it's not accessible via ajax (ajax is part of the web browsers 2) try /secret_code instead of ../../../secret_code.js I don't want my users to be able to have access to the JS @AdamStrudwick if you use a js file the user can see it. There's no way to prevent it. Sorry, the browser isn't a black box (well, IE is, but not the good ones.) Maybe you'd like to make a proprietary desktop app instead of a web page? People can use eg the chrome inspector to see every byte that's sent by or received by the browser. Doesn't matter if its javascript. If people want to cheat badly enough, they will. Just do what's reasonable, and deal with cheaters if needed later. You can only load files that are accessible directly from browsers, for example, http://www.mydomain.com/secret_code.js If it can't be accessed directly by the browser, it can't be accessed by the browser via ajax. You can however use .htaccess to prevent users from opening up a js file directly, though that doesn't keep them from looking at it in the google chrome or firebug consoles. If you want to keep it secret, don't let it get to the browser. How would you prevent direct access to a script with htaccess? Actually that isn't possible. I'm not sure what I was thinking. Navigate to the URL, not the directory. Like $.ajax({ url : "http://domain.com/js/secret_code.js", .. I don't want users to be able to access it directly via the Web. With your solution, they can see secret_code.js if they try to access it... by putting it in the root directory, I hide it. Putting it in the root directory( or any other non-web-accessible directory) is the only way to prevent users from seeing the javascript. However, it also prevents your code from seeing it. There is no way to run code in the browser while hiding it. @AdamStrudwick, There isn't a way where you can stop the user to not to see the scripts that are already loaded on them. Try jQuery's $.getScript() method for loading external Script files, however, you can easily see the contents of the script file using Firebug or the developer toolbar! Security first You can't access your root directory with JavaScript because people would read out your database passwords, ftp password aso. if that would be possible. so is there a real way to prevent JS from being accessible to users? @AdamStrudwick Yes, however it would then not be accessible to the browser and your application (making it useless). Even if you load your content dynamicly, it's quite easy to see content of the file using firebug, fiddler or any kind of proxy. I suggest you to use obfuscator. It will be harder for user to find answer Take a look at the jQuery.getScript() function, it's designed for loading Javascript files over AJAX and should do what you need.
common-pile/stackexchange_filtered
How to pivot table in R I've been trying learn R for a while but haven't got my knowledge up to even a decent level yet. Please help me in this pivot. I have a csv data file with 5000 rows with the following data fields: Name, channel (Internal or external), Survey sent date & Survey received date. Base data would look like this I want this to be put up in the below format I tried this library("reshape2") dcast(w, Recruiter~channel)" which is working fine but i dont know how to add count of "Survey sent" , "Survey received & "survey sent - survey recieved" http://www.r-bloggers.com/pivot-tables-in-r/ You should post sample data, e.g. output of dput(head(data,20)) here for others to help you better. Depends: is your question "how to use reshape to combine the data in two columns," or is it "how to write a logical expression like if(Survey_Sent & Survey_Received) " ? For "Survey sent" and "Survey received", you could use aggregate, eg. aggregate(Survey.sent~Name, w, length). dplyr solution... > head(data) Name Channel Sent Recd 1 A Internal 2014-07-10 2014-07-12 2 A Internal 2014-07-16 <NA> 3 A External 2014-08-04 2014-08-10 4 A Internal 2014-08-16 2014-08-18 5 A Internal 2014-07-29 <NA> 6 A External 2014-08-05 2014-08-14 and then: require(dplyr) data %>% group_by(Name) %>% summarise( External=sum(Channel=="External"), Internal=sum(Channel=="Internal"), Total=n(), Sent=sum(!is.na(Sent)), Recd=sum(!is.na(Recd)) ) %>% mutate(Pending=Sent-Recd) gives: Name External Internal Total Sent Recd Pending 1 A 6 4 10 10 8 2 2 B 2 7 9 9 6 3 3 C 4 5 9 9 4 5 Note I've used real Date objects for dates and NA for missing data. Data generated thus: data = structure(list(Name = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Channel = c("Internal", "Internal", "External", "Internal", "Internal", "External", "External", "External", "External", "External", "Internal", "External", "Internal", "Internal", "Internal", "External", "Internal", "Internal", "Internal", "Internal", "Internal", "External", "Internal", "External", "External", "External", "Internal", "Internal"), Sent = structure(c(16261, 16267, 16286, 16298, 16280, 16287, 16294, 16292, 16291, 16282, 16304, 16297, 16262, 16274, 16264, 16270, 16252, 16276, 16279, 16275, 16277, 16293, 16253, 16272, 16288, 16283, 16281, 16296 ), class = "Date"), Recd = structure(c(16263.5024573486, NA, 16292.4899729695, 16300.3446546271, NA, 16296.9054549634, 16301.318120582, 16301.4672047794, 16295.238142278, 16286.8117301762, NA, 16306.6499495078, NA, 16282.0412430186, 16272.4275530744, 16273.9005153924, 16255.7532094959, NA, 16284.9287535194, NA, 16279.182732366, 16302.4864703286, NA, NA, 16296.6838856321, NA, 16290.3657759354, NA), class = "Date")), .Names = c("Name", "Channel", "Sent", "Recd"), row.names = c(NA, -28L), class = "data.frame") Or using data.table (Using @Spacedman's data) library(data.table) DT1 <- setDT(data)[, indx:= Channel=="External"][, list(External=sum(indx), Internal=sum(!indx), Total=.N, Sent=sum(!is.na(Sent)), Recd=sum(!is.na(Recd))), by=Name][, Pending:=Sent-Recd] DT1 # Name External Internal Total Sent Recd Pending #1: A 6 4 10 10 8 2 #2: B 2 7 9 9 6 3 #3: C 4 5 9 9 4 5 Try following simple code: outdf = dcast(ddf, name~channel, length) outdf$total_channel = outdf$external + outdf$internal outdf$survey_sent = data.frame(table(ddf$name))$Freq outdf$survey_rcd = data.frame(with(ddf[ddf$survey_rcd!="",], table(name)))$Freq outdf$survey_pending= outdf$survey_sent - outdf$survey_rcd outdf # name external internal total_channel survey_sent survey_rcd survey_pending #1 a 0 4 4 4 2 2 #2 b 4 1 5 5 2 3 #3 c 2 2 4 4 3 1 Sample data: ddf = structure(list(name = c("a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c"), channel = c("internal", "internal", "internal", "internal", "external", "external", "external", "external", "internal", "internal", "internal", "external", "external"), survey_sent = c("15/02/13", "16/02/13", "17/02/13", "18/02/13", "19/02/13", "20/02/13", "21/02/13", "22/02/13", "23/02/13", "24/02/13", "25/02/13", "26/02/13", "27/02/13"), survey_rcd = c("26/03/14", "", "", "29/03/14", "30/03/14", "", "", "", "03/04/14", "04/04/14", "", "06/04/14", "07/04/14")), .Names = c("name", "channel", "survey_sent", "survey_rcd"), class = "data.frame", row.names = c(NA, -13L)) ddf name channel survey_sent survey_rcd 1 a internal 15/02/13 26/03/14 2 a internal 16/02/13 3 a internal 17/02/13 4 a internal 18/02/13 29/03/14 5 b external 19/02/13 30/03/14 6 b external 20/02/13 7 b external 21/02/13 8 b external 22/02/13 9 b internal 23/02/13 03/04/14 10 c internal 24/02/13 04/04/14 11 c internal 25/02/13 12 c external 26/02/13 06/04/14 13 c external 27/02/13 07/04/14
common-pile/stackexchange_filtered
How to delete comment that is inside of Post schema? I'm working on social network app where user can make post and comment. I'm trying to delete comment that is inside of a post. I work with MERN (mongoose, express, react, nodejs). I can successfully delete post, but don't know how to delete its comment. This is my Mongo connection: const db = config.get('mongoURI') mongoose.connect(db,{useNewUrlParser: true,useUnifiedTopology: true}) .then(() => console.log('Connected to MongoDB.')) .catch(err => console.log('Fail to connect.', err)) this is Post Schema const mongoose = require('mongoose') const Schema = mongoose.Schema const PostSchema = new Schema({ userID: { type: Schema.Types.ObjectId, ref: 'user' }, content: { type: String, required: true }, registration_date: { type: Date, default: Date.now }, likes: [ { type: Schema.Types.ObjectId, ref: "user" } ], comments: [ { text: String, userID: { type: Schema.Types.ObjectId, ref: 'user' } } ] }) module.exports = User = mongoose.model('posts', PostSchema) and here is where i tried to delete it: router.delete("/comment/:postId/:commentId", auth, function (req, res) { Post.findByIdAndUpdate( (req.params.postId), { $pull: { comments: req.params.commentId } }, { new: true } ) .then(post => console.log(post) .then(() => { res.json({ success_delete: true }) }) .catch(() => res.json({ success_delete: false }))) }); what error are you get when you tried router.delete("/comment/:postId/:commentId", auth, function (req, res) ? TypeError: Cannot read property 'then' of undefined... but i just don't know how to implement functionality of deleting comment, i don't know what i need to write in my code to delete it, this code is probably wrong Well, I think you are creating an app named DevConnector. So I wrote code for the same in the past. router.delete('/comment/:id/:comment_id', auth, async (req, res) => { try { const post = await Post.findById(req.params.id); // Pull out comment const comment = post.comments.find( comment => comment.id === req.params.comment_id ); // Make sure comment exists if (!comment) { return res.status(404).json({ msg: 'Comment does not exist' }); } // Check user if (comment.user.toString() !== req.user.id) { return res.status(401).json({ msg: 'User not authorized' }); } // Get remove index const removeIndex = post.comments .map(comment => comment.user.toString()) .indexOf(req.user.id); post.comments.splice(removeIndex, 1); await post.save(); res.json(post.comments); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); thanks, that's it! i just had to adjust 'comment.user' to 'comment.userID' and everything is perfect :)
common-pile/stackexchange_filtered
Trouble tracing error "Invalid Metadata Provided" I followed this tutorial to learn how to use the tensorflow.js model mobilenet in node.js:link Now I am trying to use my own tensorflow.js model trained in teachable machine using the @teachablemachine/image package: link Here is my code: const tf = require('@tensorflow/tfjs'); const tfnode = require('@tensorflow/tfjs-node'); const tmImage = require('@teachablemachine/image'); const fs = require('fs'); const path = require('path'); const FileAPI = require('file-api'), File = FileAPI.File; global.FileReader = FileAPI.FileReader; global.Response = require('response'); const uploadModel = "model.json" const uploadModelPath = path.join(process.cwd(), uploadModel); const uploadModelFile = new File({ name: "model.json", type: "application/json", path: uploadModelPath }); const uploadWeights = "weights.bin" const uploadWeightsPath = path.join(process.cwd(), uploadWeights); const uploadWeightsFile = new File({ name: "weights.bin", path: uploadWeightsPath }); const uploadMetadata = "metadata.json" const uploadMetadataPath = path.join(process.cwd(), uploadMetadata); const uploadMetadataFile = new File({ name: "metadata.json", type: "application/json", path: uploadMetadataPath }); const readImage = path => { const imageBuffer = fs.readFileSync(path); const tfimage = tfnode.node.decodeImage(imageBuffer); return tfimage; } const imageClassification = async path => { const image = readImage(path); const model = await tmImage.loadFromFiles(uploadModelFile,uploadWeightsFile,uploadMetadataFile); //const model = await tmImage.load('https://teachablemachine.withgoogle.com/models/25uN0DSdd/model.json','https://teachablemachine.withgoogle.com/models/25uN0DSdd/metadata.json'); const predictions = await model.predict(image); console.log('Classification Results:', predictions); } if (process.argv.length !== 3) throw new Error('Incorrect arguments: node classify.js <IMAGE_FILE>'); imageClassification(process.argv[2]); When I run it I get error: > (node:94924) UnhandledPromiseRejectionWarning: Error: Invalid Metadata provided at C:\Users\Awesome\Google Drive\Source\Programming\JS\Testing\node_modules\@teachablemachine\image\dist\custom-mobilenet.js:163:27 Which leads me to: var processMetadata = function (metadata) { return __awaiter(void 0, void 0, void 0, function () { var metadataJSON, metadataResponse; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(typeof metadata === 'string')) return [3 /*break*/, 3]; return [4 /*yield*/, fetch(metadata)]; case 1: metadataResponse = _a.sent(); return [4 /*yield*/, metadataResponse.json()]; case 2: metadataJSON = _a.sent(); return [3 /*break*/, 4]; case 3: if (isMetadata(metadata)) { metadataJSON = metadata; } else { throw new Error('Invalid Metadata provided'); } _a.label = 4; case 4: return [2 /*return*/, fillMetadata(metadataJSON)]; } }); }); }; full file here: link So I can see case 0-2 aren't being triggered and for case 3 the metadata file isn't passing the isMetadata function which is: var isMetadata = function (c) { return !!c && Array.isArray(c.labels); }; Which I think tests that the file is not undefined and has an array of labels. Where to go from there I am not sure because I don't understand the rest of the code in that file. I am going to try an alternative approach but I thought I might post this encase someone with more experience can see the problem clearly and wants to help teach me something or point me in the right direction or just simply tell me that at my experience level this isn't the right use of my time. Thanks for reading. I shall reach out to the team to see, this seems fine. Thanks that would be great
common-pile/stackexchange_filtered
Apache Airflow Celery Executor: Import a local custom python package I'm using Bitnami's prepackaged Airflow Multi-tier architecture found here: https://azure.microsoft.com/en-us/blog/bitnami-apache-airflow-multi-tier-now-available-in-azure-marketplace/ Here's what they have to say about how the DAGS are shared across nodes: All nodes have a shared volume to synchronize DAG files. DAG files are stored in a directory of the node. This directory is an external volume mounted in the same location in all nodes (both workers, scheduler, and web server). Since it is a shared volume, the files are automatically synchronized between servers. Add, modify or delete DAG files from this shared volume and the entire Airflow system will be updated. So, I've set up my dag directory as so: /opt/bitnami/airflow/dags | ├── dag.py └── package ├── __init__.py └── module.py This is what the import in my DAG looks like: from package.module import something But I get this error: Broken DAG: [/opt/bitnami/airflow/dags/dag.py] No module named 'package' I've read other threads, and tried those solutions, but nothing seems to work. Does the fact I'm using the celery executor change anything? I'm new here so please, if you need more details, let me know. Well, I found a solution. First, I discovered the airflow plugins manager. It looked like it was mainly for building your own custom operators, hooks, etc, but I figured I could use it for my scenario. So I checked the airflow.cfg file bitnami provided and saw the parameter: plugins_folder=/opt/bitnami/airflow/plugins This directory didn't exist in the machine, so I created it and dropped my package in there (without making any changes to it). Then, I restarted the web server node and scheduler nodes to pick this change up. Now I can run the import in my DAG script same as before with no issues: from package.module import something Next steps for me will be synchronizing this plugins folder with the repository that contains our package(s), the same way I synchronized the DAGS folder found here: https://docs.bitnami.com/azure-templates/infrastructure/apache-airflow/configuration/sync-dags/ I'm not sure the plugins folder is meant to be used this way, but this works. Not sure if still relevant, but how we are handling this is having custom airflow images that have all the dependencies needed - in our case a python library that offers domain specific concepts for defining dags. This way we can just import the library as normal, as it is globaly available.
common-pile/stackexchange_filtered
What is the name of this style? (Karate maybe?) I've seen this video around a fair bit, but I can't find much background about who / what organization / style it is? That's a godan grading! Words fail me... Whatever style it is, stay as far away from it as you can! Even though the style is rather questionable, I don't think we should revert to name-calling here. Can you please change the question's tag? the tag is how its tagged on the internet @KeithNicholas - The internet has different standards than most SE sites. I am in Michael Dealys class. There is no contact and we do Tae Kwon Do. I hope this was helpful. The video is from the World Martial Arts Association which was setup by Michael T. Dealy in the early 1990s, Mike Dealy trained under Grandmaster Duk Sung Son. The style is Chung Do Kwan, a form of Tae Kwon Do with light or no-contact. The WMAA has a video channel on Youtube, but about a year ago all video's were removed, probably because of the criticism they received. The WMAA is often ridiculed on the Internet as being a McDojo/McDojang (for example see here, here and here) More information: http://wmaa.com/about/ http://www.oneworldtaekwondo.com/html/history.html
common-pile/stackexchange_filtered
How to validate cascade delete when no corresponding table entry exists for that entry? I have these 2 models class Category(models.Model): store = models.ForeignKey(Store, related_name="categories") name = models.CharField(max_length=100) and class Item(models.Model): store = models.ForeignKey(Store, related_name="items") category = models.ForeignKey(Category, related_name="items") name = models.CharField(max_length=100) isPartiallySellable = models.BooleanField(default=False) note = models.CharField(max_length=500,default="") when I am deleting a category entry, I am getting the following error on django column item.isPartiallySellable does not exist LINE 1: ...currentlyInStock", "item"."unit", "... ^ Now, I don't have any entry in Item table, but still getting this error. I want the cascading to happen but I am not able to debug this particular error. On a side note this error has a partial one, how can I get the full error message here. Did u added isPartiallySellable after migrating? If yes, did u run makemigrations and migrate? This is a real issue with your database where constraints aren't guaranteed. You should run a sanity check to ensure all the foreign keys are up to date. Note: if you can't fix the database itself, you'll have to override the delete function and ensure the FK do exist by yourself. yeah, my migrations were not synced. Faked them and deleted objects again. worked like a charm.
common-pile/stackexchange_filtered
How javascript regexp.compile() works? Possible Duplicate: Javascript: what's the point of RegExp.compile()? Javascript is said to be an interpreted language, then how actually the compile method works for regular expressions. Does it is really compiles the pattern or it is just an abuse of notation. The verb "compile" alone does not imply machine code. "RegExp methods: The compile method is deprecated." @James McLaughlin: When I tried to find answer I found this article. http://www.w3schools.com/jsref/jsref_regexp_compile.asp The article itself says "The compile() method is used to compile a regular expression during execution of a script." On Chrome, I sometimes get different result when i first time use test after compile. For example, patt.test(x)->true, patt.test(x)->false, patt.test(x)->false, etc. And yes, I am not using the "g" flag. compile was depreciated in JavaScript 1.5 It's true that Javascript is an interpreted language, but all browsers handle Javascript differently. Google Chrome for example goes great lengths to compile JS code upon first execution; the underlying V8 engine translates JS into machine code to increase performance in huge web applications like Gmail. Therefore Chrome compiles all JS code and not just regular expressions, maybe one could say that is an abuse of notation. The Mozilla docs say that Firefox uses compilation of regular expressions, but then again, SpiderMonkey / TraceMonkey is a JIT compiler which generates bytecode. I haven't found information about how the Internet Explorer handles things, I assume a little bit of everything, depending on the version number. The really interesting question is: Why do you need this piece of information? If you want to optimize your Javascript code, I suggest to benchmark different approaches in all browsers you want to support and end up using the best-performing one. That should get you further than trying to understand internal browser functions which differ from version to version anyway.
common-pile/stackexchange_filtered
How to do data binding in polymer with meteor I'm very new to data binding and the two frameworks. Right now I'm pretty stuck at how to bind the data within a polymer element. For example, I have a book list with books' name. If I only use blaze to do the rendering, I would do it in the follow way: //app.js Template.bookList.helpers({ books: function () { return Books.find({}); } }); //app.html <template name="bookList"> <h1>List</h1> <ul> {{#each books}} {{> book}} {{/each}} </ul> </template> <template name="book"> <li>{{name}}</li> </template> Now I'm using it with polymer, I do: //my-book-list.html <polymer-element name="my-book-list"> <template> <h1>List</h1> <content></content> </template> </polymer-element> //app.html <template name="bookList"> <my-book-list> <ul> {{#each books}} {{> book}} {{/each}} </ul> </my-book-list> </template> <template name="book"> <li>{{name}}</li> </template> So I place the dynamic data inside of the polymer item through the content block. Although it still does the job, I don't want it that way. I want to do the data-binding inside the polymer element, something like(I hope it makes sense to you): //my-book-list.html <polymer-element name="my-book-list"> <template bind="{{books}}"> <h1>List</h1> <ul> <template repeat> <li>{{name}}</li> </template> </ul> </template> </polymer-element> //app.html <template name="bookList"> <my-book-list></my-book-list> </template> Is there a way to do it? Thanks in advance. Progress: I now can put books purely inside the polymer element, the problem now is that it doesn't seem to react when the data change because polymer doesn't observe change of a object, and I am struggling in finding a way to observe all the nested values inside a object: <polymer-element name="my-book-list"> <template bind="{{books | mapBooks}}"> <h1>List</h1> <ul> <template repeat> <li>{{name}}</li> </template> </ul> </template> <script> Polymer("my-book-list", { books: Books.find(), mapBooks : function(booksCursor) { return booksCursor.map(function(p) { return {id: p.id, name: p.name}}) } }); </script> </polymer-element> There's an extensive discussion on Meteor and Polymer in the MeteorCommunity repo. Thanks, the discussion gave me some inspiration Finally got a hacky solution, but I don't know if this is the best practice or not: <polymer-element name="my-book-list"> //Force polymer to update DOM when books.lastUpdate change <template bind="{{books.lastUpdate | getBooks}}"> <h1>List</h1> <ul> <template repeat> <li>{{name}}</li> </template> </ul> </template> <script> Polymer("my-book-list", { ready: function() { var books = this.books; this.books.observeChanges( //Observe the change of cursor and update a field { added: function(id, fields) { console.log("Item added"); books.lastUpdate = new Date(); }, changed: function(id, fields) { console.log("Item changed"); books.lastUpdate = new Date(); }, removed: function(id, fields) { console.log("Item deleted"); books.lastUpdate = new Date(); } } ), books: Books.find(), getBooks : function() { return Books.find().map(function(p) { return {id: p.id, name: p.name}}) } }); </script> </polymer-element>
common-pile/stackexchange_filtered
Return typed object property when accessed by key Hard to explain so here is an example: interface O { n: number; s: string; } const f = (key: keyof O, o: O) => o[key]; const value = f('n', { n: 1, s: '' }); // value type is (string | number) In this situation I'd like value type to be number because the key n points to a number property You can accomplish this by using generic syntax for the f function. For an anonymous function like you have there you could do: const f = <O, K extends keyof O>(key: K, o: O) => o[key]; This allows typescript to infer the key parameter to be a specific key of the O object, where before it couldn't be narrowed to anything more specific than just keyof O (which represents the union of all keys). Now, your example will give the right type for each key: const value = f('n', { n: 1, s: '' }); // value type is: number const other = f('s', { n: 1, s: '' }); // other type is: string great! so this solution does not depend on interface itself, right ? Thanks, that works! And O does not need to be a generic. You can just do: f = <K extends keyof O>(key: K, o: O) => o[key]. But then I don't understand why it works and this doesn't: f = (key: keyof O, o: O) => o[key]
common-pile/stackexchange_filtered
A subset of a metric space is dense if... Let $(X,d)$ be a metric space, $E$ a subset of $X$ and $p$ a point of $X$. A neighborhood of $p$ is a subset of $X$ consisting of all points $q$ of $X$ with $d(p,q)<r$, some $r>0$. $p$ is a limit point of $E$ if every neighborhood of $p$ contains a point $q\neq p$ of $X$ which is a point of $E$ Definition 1 $E$ is said to be dense in $X$ if every point of $X$ is a limit point of $E$. Definition 2 $E$ is said to be dense in $X$ if every point of $X$ is a limit point of $E$, or a point of $E$ (or both) Is "..or a point of $E$, (or both)" really necessary in definition 2? In other words, are the two definitions defining the same class of subsets of $X$? I was thinking: If a point of $X$ is a point of $E$, then it is a limit point of $E$, unless $E$ has some isolated points, in that case I would have that $E$ is not dense into itself, according to definition 1. Is that the only circumstance where I need to specify "..or a point of $E$", or there are many cases of spaces $X$ and subspaces $E$ where the two definitions are actually not equivalent? Consider any set $X \neq \emptyset$ with the discrete metric. Then $X$ is dense in itself but no point of $X$ is a limit point of $X$, so we must require ".. or a point of $E$" in the definition. In other words, in my example definition (2) holds while definition (1) fails. In fact, instead of asking for limit point as you defined, you can just define an adherent point of $E$ as a point $x \in X$ such that for every neighbood of $x$ contains a point of $E$. Then it is easy to see that a set $E$ is dense in $X$ iff every point of $X$ is an adherent point of $E$, so you don't need to distinguish cases. Note also that the set of adherent points of $E$ is exactly the closure of $E$, so basically the definition then becomes $X= \overline{E}$.
common-pile/stackexchange_filtered
GT521F52 Fingerprint sensor library I have a GT-521F32/52 FP sensor and Rpi 3 B. I am looking at this library but it doesn't seem to work. http://www.yoctopuce.com/EN/article/test-of-the-gt-521f52-fingerprint-reader I also checked this http://www.yoctopuce.com/EN/article/test-of-the-gt-521f52-fingerprint-reader but doesn't fit with what I want. Do you know other fingerprint python library that works with GT-521F32/52? Unfortunately, requests for off-site resources are off-topic for SO. However, looking at this library it looks extremely simple. It shouldn't be too hard to find out why it's not working. Bet bet: Have a go, and when you get stuck, come back here with a specific question, about the bit you're stuck with. Unless it's a hardware-y Pi-specific problem, of course, there are other SE sites for that. Are you also using the Yocto USB-serial PCB? If not, then that is most likely your problem, as the library depends on it.
common-pile/stackexchange_filtered
Swift, load video of the gallery without compression When you offer the possibility to a user to use a video previously registered in the gallery of the iPhone with a UIImagePickerController, it's imported and compressed to 1280x720 regardless of the original resolution. Is it possible to get the original video at the original quality with UIImagePickerController ? The url returned by UIImagePickerController.InfoKey.mediaURL seem to be a temporary url to the compressed file, so not usable to get the original file. Two ways I can think of for that problem. First, there is a property of UIImagePickerController called videoExportPreset. You can set that property to AVAssetExportPresetPassthrough. videoExportPreset can be used to specify the transcoding quality for videos (via a AVAssetExportPreset* string). If the value is nil (the default) then the transcodeQuality is determined by videoQuality instead. Not valid if the source type is UIImagePickerControllerSourceTypeCamera. Remember to do import AVFoundation. Second way is to implement your own picker, that is, using PHAsset. Example: let fetchResult = PHAsset.fetchAssets(with: .video, options: nil) let videoRequestOptions = PHVideoRequestOptions() videoRequestOptions.version = .original fetchResult.enumerateObjects { (asset, index, _) in PHImageManager.default().requestAVAsset(forVideo: asset, options: videoRequestOptions) { (avAsset, audioMix, infoDic) in //---- } } I didn't saw the videoExportPreset property, thanks ! you can set AVCaptureSession.Preset according to your need. var session: AVCaptureSession? func video(){ // Don't trigger camera access for the background guard AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized else { return } do { // Prepare avcapture session session = AVCaptureSession() session?.sessionPreset = AVCaptureSession.Preset.high //medium or low // Hook upp device let device = AVCaptureDevice.default(for: AVMediaType.video) let input = try AVCaptureDeviceInput(device: device!) session?.addInput(input) // Setup capture layer guard session != nil else { return } let captureLayer = AVCaptureVideoPreviewLayer(session: session!) captureLayer.frame = bounds captureLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill cameraBackground.layer.addSublayer(captureLayer) self.captureLayer = captureLayer } catch { session = nil } }
common-pile/stackexchange_filtered
Tab bar controller inside a navigation controller, or sharing a navigation root view I'm trying to implement a UI structured like in the Tweetie app, which behaves as so: the top-level view controller seems to be a navigation controller, whose root view is an "Accounts" table view. If you click on any account, it goes to the second level, which has a tab bar across the bottom. Each tab item shows a different list and lets you drill down further (the subsequent levels don't show the tab bar). So, this seems like the implementation hierarchy is: UINavigationController Accounts: UITableViewController UITabBarController Tweets: UITableViewController Detail view of a tweet/user/etc Replies: UITableViewController ... This seems to work[^1], but appears to be unsupported according to the SDK documentation for -pushViewController:animated: (emphasis added): viewController: The view controller that is pushed onto the stack. It cannot be an instance of tab bar controller. I would like to avoid private APIs and the like, but I'm not sure why this usage is explicitly prohibited even when it seems to work fine. Anyone know the reason? I've thought about putting the tab bar controller as the main controller, with each of the tabs containing separate navigation controllers. The problem with this is that each nav controller needs to share a single root view controller (namely the "Accounts" table in Tweetie) -- this doesn't seem to work: pushing the table controller to a second nav controller seems to remove it from the first. Not to mention all the book-keeping when selecting a different account would probably be a pain. How should I implement this the Right Way? [^1]: The tab bar controller needs to be subclassed so that the tab bar controller's navigation item at that level stays in sync with the selected tab's navigation item, and the individual tab's table controller's need to push their respective detail views to self.tabBarController.navigationController instead of self.navigationController. The two previous answers got it right - I don't use UITabBarController in Tweetie. It's pretty easy to write a custom XXTabBarController (plain subclass of UIViewController) that is happy to get pushed onto a nav controller stack, but still lives by the "view controller" philosophy. Each "tab" on the account-specific view (Tweets/Replies/Messages) is its own view controller, and as far as they are concerned they're getting swapped around on screen by a plain-ol UITabBarController. How does your custom tab bar controller class handle plumbing for the navigationItem and navigationController properties of its child controllers? Has this changed in iOS 5? I seem to be able to add a UITabBarController into a UINavigationController without too much of a problem, even as a the root controller. I'm building an app that uses a similar navigation framework to Tweetie. I've written a post about how to do this on my blog www.wiredbob.com which also links to the source code. It's a full template you could take and use as a basis for another project. Good luck! For those wondering, the link to the mentioned blog post is http://www.wiredbob.com/blog/2009/4/20/iphone-tweetie-style-navigation-framework.html @Robert Conn, really nice tutorial. I am using your concept, but for some reason my tabBar is not active. Did this happened to you when you were implementing your app? @ASalcedo: I too had this problem but found that it was because I needed to reduce the size of the views associated with the tab bar items, the default height size of 460 was to large, in the source code at www.wiredbob.com you will see that the height set for the tab items is 369 to allow for the tab bar. In order to change the height in interface builder you also have to ensure that status, top and bottom bar are all set to none in the attributes inspector of the view(not immediately obvious). The blog post is dead for me, any chance some one has that lying around? working blog post link: http://www.wiredbob.com/2009/04/iphone-tweetie-style-navigation.html You shouldn't link to an external resource for the answer. Instead you should provide the answer here, and refer to an external resource for more in-depth information for example. It's possible to add a UITabBar to any UIViewController. That way you don't actually have to push a UITabBarController and therefore stay within the guidelines of the Apple API. In interface builder UITabBar is under "Windows, Views & Bars" in the Cocoa Touch Library. Hi! @Himadri Choudhury can you explain "and therefore stay within the guidelines of the Apple API" - or give the reference ? I can't find where this guideline is told (I don't doubt it exists, but I can't find the URL). Thank you very much I do this in a couple of my apps. The trick to adding a tab bar to a navigationController based app is to NOT use a TabBarController. Add a Tab Bar to the view, make the view controller for that view a TabBarDelegate, and respond to user selections on the tab bar in the code of the view controller. I use Tab Bars to add additional views to the Tab Bar's view as sub-views, to reload a table view with different datasets, to reload a UIPickerView, etc. I was struggling for the past hour to implement a UITabBar because it would get hidden when I tried to display my view; then I found this post: Basically, make sure you insert your new view below the tabbar, per this line of code: [self.view insertSubview:tab2ViewController.view belowSubview:myTabBar]; Thanks this helped fix my disappearing tab bar. I used the same code that Robert Conn proposed but somehow the ui tab bar disappears when I switch to the second view. In my app, the root view controller is a UINavigation controller. At a certain point in the app, I need to display a UITabBar. I tried implementing a UITabBar on a UIView within the navigation hierarchy, as some of the previous posts suggested, and this does work. But I found that I wanted more of the default behavior that the tab controller provides and I found a way to use the UITabBarController with the UINavigation controller: 1) When I want to display the UITabBarController's view, I do this: MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; appDelegate.window.rootViewController = myUiTabBarControllerInstance; 2) When I want to return to where I was in the navigation hierarchy, I do this: appDelegate.window.rootViewController = myNavControllerInstance; This is how i did it. This is actually pushing a tabbarcontroller onto navigation controller. It works fine. I didn't find anywhere in the documentation that apple doesn't support this way. Can someone give me link to this warning? If this is truth, is it possible that apple refuses to publish my app to appstore? -(void)setArrayAndPushNextController { MyFirstViewController *myFirstViewController = [[MyFirstViewController alloc] init]; MySecondViewController *mySecondViewController = [[MySecondViewController alloc] init]; myFirstViewController.array = self.array; NSArray *array = [[NSArray alloc] initWithObjects:myFirstViewController, mySecondViewController, nil]; UITabBarController *tab = [[UITabBarController alloc] init]; tab.viewControllers = array; [array release]; UITabBarItem *item1 = [[UITabBarItem alloc] initWithTitle:@"first title" image:nil tag:1]; UITabBarItem *item2 = [[UITabBarItem alloc] initWithTitle:@"second title" image:nil tag:2]; myFirstViewController.tabBarItem = item1; mySecondViewController.tabBarItem = item2; [self stopAnimatingSpinner]; [self.navigationController pushViewController:tab animated:YES]; [tab release]; [item1 release]; [item2 release]; } you fogot to release your UIViewControllers This could be achieved by simply embedding the TabBarController in the Navigation Controller. In the storyboard: Drag a ViewController Click on the ViewController's Scene Click on editor >> Embed in >> Navigation Controller. Drag a button on the same ViewController. Drag a TabBarController Connect the button on the ViewController to the TabBarController via push Segue Action. In this case only the TabBarController's RootViewController would be in the Navigation Controller's stack. All The TabBarItems would have the Navigation Bar at the top and user can go to Home Screen at any time, irrespective of the selected TabBarItem This could be done at any ViewController in the Navigation Controller's stack. If it works, please suggest me how to increase the reputation so that I can post the images and the code in the next answer. :) I wrote a blog post on how I approached this problem. For me, using a modal view was a simpler solution than writing a custom tab-bar implementation. http://www.alexmedearis.com/uitabbarcontroller-inside-a-uinavigationcontroller/
common-pile/stackexchange_filtered
Where should I put my form validation in codeigniter in fat model and thin controller approach? I am confused on where to put the form validation in fat model and thin controller approach in codeigniter. I want to separate the business logic. Is including the form validation destroying the business logic separation? I would personally keep you're form_validation out of the models, however, you don't have to put all the rules in the controller either. application/config/form_validation.php <?php //array('field' => '', 'label' => '', 'rules' => '') function arrayf($field, $label, $rules) { return array('field' => $field, 'label' => $label, 'rules' => $rules); } $config = array( 'recipients/add' => array( arrayf('title', 'Title', 'required|trim|min_length[3]'), arrayf('description', 'Description', 'min_length[10]'), arrayf('amount', 'Amount', 'required|numeric'), arrayf('date', 'Date', 'required|valid_date'), ), 'recipients/delete' => array( arrayf('id', 'Id', 'required'), arrayf('confirm', 'Confirm', 'required'), ), ); The above is an a basic example. Then in your controller you would just have: if ($this->form_validation->run('recipients/add') !== FALSE) { //Do whatever } Notice how the first validation group has the same index as param passed to $this->form_validation->run('recipients/add') This way you can use the same validation rules in different controllers without writing them all out again. Note The function arrayf() is used to format the array because otherwise you would have to write out each validation rule with the array keys as well e.g. array('field' => '', 'label' => '', 'rules' => '') Hope this helps! Hey, if this worked for you could you mark the question as answered? :)
common-pile/stackexchange_filtered
Query both first_name and last_name from wp_usermeta at the same time I'm trying to fetch both the first_name and last_name of all users at the same time, using the wpdb-object and the wp_usermeta table. I can't seem to figure out how to get both in the same query. Below is what I've got so far. global $wpdb; $ansatte = $wpdb->get_results("SELECT user_id, meta_value AS first_name FROM wp_usermeta WHERE meta_key='first_name'"); foreach ($ansatte as $ansatte) { echo $ansatte->first_name; } Using the above code I'm able to echo out the first names of all users, but i would like for the last_name to be available aswell, like so; foreach ($ansatte as $ansatte) { echo $ansatte->first_name . ' ' $ansatte->last_name; } Any ideas? If you must use raw SQL, which I advise against, don't hard code the table names, and use those provided by the $wpdb object, else you risk compatability issues across sites and multisite installs I can't find a clean, native way to pull this data. There are a couple of ways I can think of to do this: First, something like: $sql = " SELECT user_id,meta_key,meta_value FROM {$wpdb->usermeta} WHERE ({$wpdb->usermeta}.meta_key = 'first_name' OR {$wpdb->usermeta}.meta_key = 'last_name')"; $ansatte = $wpdb->get_results($sql); var_dump($sql); $users = array(); foreach ($ansatte as $a) { $users[$a->user_id][$a->meta_key] = $a->meta_value; } var_dump($users); You can then do: foreach ($users as $u) { echo $u['first_name'].' '.$u['last_name']; } ... to echo your user names. The second way, a more pure SQL way, is what you were attempting: $sql = " SELECT {$wpdb->usermeta}.user_id,{$wpdb->usermeta}.meta_value as first_name,m2.meta_value as last_name FROM {$wpdb->usermeta} INNER JOIN {$wpdb->usermeta} as m2 ON {$wpdb->usermeta}.user_id = m2.user_id WHERE ({$wpdb->usermeta}.meta_key = 'first_name' AND m2.meta_key = 'last_name')"; $ansatte = $wpdb->get_results($sql); foreach ($ansatte as $ansatte) { echo $ansatte->first_name . ' ' . $ansatte->last_name; } You could also use get_users() or WP_User_Query to pull users but the meta_data you want isn't in the data returned and it would take more work to retrieve it. Doesn't it return all users with fist_name = Me AND last_name = Myselfandi? Yes, it does. Isn't that what you asked for? I didn't ask that question and I don't think that's what this question asks for. Please take a closer look at the question. I believe it's an interesting question. Yes, you are correct @sakibmoon Thank you! So, if i remove those two values I'll be getting what I'm after? I've figured out an alternative solution, quering for the user_id and using get_user_meta($ansatte->user_id, 'first_name', true) and get_user_meta($ansatte->user_id, 'last_name', true) to fetch both names. But thats probably not ideal. @s_ha_dum +1. Nice one. :) This is a straight MySQL pivot answer for phpMyAdmin assuming your Wordpress table prefix is "wp_"; SELECT t1.id, t1.user_email, MAX(CASE WHEN t2.meta_key = 'first_name' THEN meta_value END) AS first_name, MAX(CASE WHEN t2.meta_key = 'last_name' THEN meta_value END) AS last_name FROM wp_users AS t1 INNER JOIN wp_usermeta AS t2 ON t1.id = t2.user_id GROUP BY t1.id, t1.user_email; This is the correct approach using just SQL: SELECT id , (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'first_name') first_name , (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'last_name') last_name FROM wp_users Here are approaches that don't work: JOIN once for each metadata field does not work because there is no UNIQUE key on wp_usermeta(user_id, meta_key) Using subquery SELECT without MAX fails because there is no UNIQUE key on wp_usermeta(user_id, meta_key) And for some reason this is faster than using a single select and join.
common-pile/stackexchange_filtered
How to save videos from "file:///" to camera roll in Swift? In my app, I have a custom Camera that writes captured video to a temporary path that looks like this: file:///private/var/mobile.... My question is, how do I save the video to camera roll? What I have tried: PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL) // I've also tried this // let exportURL = URL(fileURLWithPath: videoURL.absoluteString, isDirectory: true) // PHAssetChangeRequest.creationRequestForAssetFromVideo(atFile: exportURL) }, completionHandler: { success, error in if success { print("Successful") } else if let error = error { print("\(error.localizedDescription)") } }) But it always prints: This operation could not be completed Any thoughts? Have you checked if the user has accepted the PhotoLibraryUsage info plist keys yet? as matter of fact you should First of all check the File Extension.if The Extension is not Supported by apple you can not save it in camera roll.you can check the saving Process by trying to save .mp4 file in camera roll to see wether saving process works or not.
common-pile/stackexchange_filtered
Merge 2 array of objects with different properties I have 2 arrays of objects: array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}]; array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}]; I want to merge them so it looks like this: [{"id":1,"cost":200,"qty":56,"desc":"a good one"},{"id":2,"cost":100,"qty":16,"desc":"a bad one"}]; Please notice the new array has properties from both arrays but it left out the object that was not present in the first one. I tried this: var mergethem = function() { var array1 = [{"id":1,"cost":200,"qty":56},{"id":2,"cost":100,"qty":16}]; var array2 = [{"id":1,"cost":200,"desc":"a good one"},{"id":2,"cost":100,"desc":"a bad one"},{"id":3,"cost":50,"desc":"an okay one"}]; var newarray= array2.filter(i => array1.map(a=> { if(a.id == i.id) i.qty = a.qty; return i; })); return newarray.filter(i=> { if(i.qty) return i; }); } console.log(mergethem()); this seems to work sometimes and some times it doesn't depending on the environment. I can't pinpoint what the problem is so I would like to ask for alternatives to try out. what error do you get? The 3rd element is included too even though is supposed to be left out. Does this answer your question? Merge two array of objects based on a key and JavaScript merging objects by id or How to merge arrays of objects by Id key? or Merge two array of objects based on same key and value You could get references of the objects of the second array and map the first while adding properties of the second array, if exist. const array1 = [{ id: 1, cost: 200, qty: 56 }, { id: 2, cost: 100, qty: 16 }], array2 = [{ id: 1, cost: 200, desc: "a good one" }, { id: 2, cost: 100, desc: "a bad one" }, { id: 3, cost: 50, desc: "an okay one" }], references2 = Object.fromEntries(array2.map(o => [o.id, o])), result = array1.map(o => ({ ...o, ...references2[o.id] })); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } You already posted comment that this solution is more robust, awesome! The only thing worth mentioning - that we need somehow be sure that 'o.id' is in our array of references - otherwise we would get 'undefined' I believe? Sorry but I get this error: Object.fromEntries I am on node.js @ByteMaster, undefined spreads in objects into as empty object. @CainNuke, mabe you take a new edition of node. does spreading ... works? probably but I dont wanna risk breaking my whole application by upgrading node. you could replace this line references2 = Object.fromEntries(array2.map(o => [o.id, o])), with references2 = array2.reduce((r, o) => (r[o.id] = o, r), {}), which creates an object. const array1 = [ {"id":1,"cost":200,"qty":56}, {"id":2,"cost":100,"qty":16} ]; const array2 = [ {"id":1,"cost":200,"desc":"a good one"}, {"id":2,"cost":100,"desc":"a bad one"}, {"id":3,"cost":50,"desc":"an okay one"} ]; const result = array1.reduce((previousValue, currentValue) => { const needObj = array2.find(o => o.id === currentValue.id) ?? {}; previousValue.push({...currentValue, ...needObj}); return previousValue; }, []); console.log(result); this works only if the items are at the same index for merging. even op is usning a find function and checks id of both arrays. Cool, cool - it takes me a while to understand why and how this works. Thanks for such an interesting approach! Basically trick here is that secondly 'spread-ed' object would be iterated over all keys - and all of the keys would be written into object A! And because we have same value for the 'id' key - we would get expanded object! @Nina Scholz , yes, or maybe the objects go sequentially? )) But you are right, I have edited the answer according to your comment. Thank you! Sorry I get this error: Unexpected token ? (the one before {};) I might as well just take that part out like this: const needObj = array2.find(o => o.id === currentValue.id); seems to work anyway ?? - This is nullish coalescing operator. It is surprising that you are getting an error, because it works in all modern browsers. But you can check needObj for undefined use if (needObj) { previousValue.push( { ...currentValue, ...needObj } ); }
common-pile/stackexchange_filtered
'AutoField' object has no attribute 'remote_field' I am getting a strange error in Django 1.8: 'AutoField' object has no attribute 'remote_field' I have a model like: from django.db import models from django.utils import timezone class Event(models.Model): product_type = models.CharField(max_length=250, null=False, blank=False) received_time = models.DateTimeField(editable=False) source_json = models.TextField() event_id = models.CharField(max_length=250, null=False, blank=False) # https://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add def save(self, *args, **kwargs): if not self.id: self.received_time = timezone.now() return super(Event, self).save(*args, **kwargs) @classmethod def event_id_is_already_saved(cls, event_id_in_question): items_found = cls.objects.filter(event_id=event_id_in_question) if items_found: return True return False views like: import json from django.http import HttpResponse from rest_framework import viewsets from events.utils.elastic_db_utils import get_elastic_exact_search_from_query_dictionary from events.serializers import EventSerializer from events.models import Event def list_events(request): all_events = Event.objects.all() serialized = [EventSerializer(event) for event in all_events] return HttpResponse(json.dumps(serialized)) class EventViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Event.objects.all().order_by('-received_time') serializer_class = EventSerializer urls: from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'events', views.EventViewSet) urlpatterns = [ url(r"^$", views.search_elastic_db, name='search-elastic-db'), url(r"^events", views.list_events, name='list-events'), url(r'^api/', include(router.urls)), ] Neither my viewset, nor the ^events endpoint work, both get same error. There is nothing wrong with my model that you can see in a shell: In [1]: from events.models import Event In [2]: Event.objects.all() Out[2]: [<Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>] I don't think you can deduce the exact cause from the code you've provided, but based on the error message, it seems likely you're using code elsewhere—likely in a third-party library—that was written for newer versions of Django. The remote_field attribute was added to Field in Django v1.9, as noted in the release notes. (This attribute is clearly absent in v1.8.) Your options are: Upgrade your project to a more recent Django release. Backport the third-party library, change the offending Field to use rel, and rewrite any other incompatible code. Replace the third-party library with a different one that supports Django v1.8. (I'd recommend the first option, since upgrading between Django versions is well-documented.) excellent, ty profusely. Just upgrading to 1.9 was enough and nothing broke
common-pile/stackexchange_filtered
How to SELECT data from one table that meets all requirements in another table I have a really simple table here with applicants, skills and another table with just skills. My goal is to see which applicants meet ALL requirements in the required skill table. p1 Java p1 Oracle p2 Java p2 C# p2 Oracle p3 C# AND Java C# SELECT a.NAME FROM APPLICANTS a, SKILLS s WHERE a.SKILL = s.SKILL This returns me everyone except who ever has Oracle. Iv'e tried GROUP BY HAVING as well as what ever the book/internet have conjured in the past few hours. All I'm looking to have reported in this instance is p2. This is my first day with a database hands on but the idea of this task seems so simple yet I can't grasp it. Any help, hints, or clues would be extremely appreciated. Do you have some example of the rows in applicants and skills table You need to group the skills by people but limit the result to the people/skills combinations that have skills in the skills table SELECT A.NAME, FROM APPLICANTS A INNER JOIN SKILLS ON S.SKILL = A.SKILL GROUP BY A.NAME HAVING COUNT(*) = (SELECT COUNT(*) FROM SKILLS) A person who has all skills will have a count of skills = the number of skills in the skills table. This assumes that there is only one Person/skill combo in the table if you have multiple rows you should be able to use a sub query to get the Distinct rows first. SELECT A.Name FROM (SELECT DISTINCT NAME, SKILL FROM APPLICANTS) A INNER JOIN SKILLS ON S.SKILL = A.SKILL GROUP BY A.SKILL HAVING COUNT(*) = (SELECT COUNT(*) FROM SKILLS) Suppose, a person has skills Java and Oracle, Skills table has entries C++ and Perl, in that case also it will return Name, we cannot guarantee correct results just by matching counts, I guess. Ahh i see what you're saying - yes there needs to be a join too. I've corrected it to limit the first table to only have those skills that are in the Skills table. Then the count is reasonable. One way could be using scalar sub-query, to find language in skills tables for each skills of an applicant and then counting not nulls from the result WITH APPLICANTS(P_ID, LANG) AS ( SELECT 'p1', 'Java' FROM DUAL UNION ALL select 'p1', 'Oracle' from dual union all SELECT 'P2', 'Java' FROM DUAL UNION ALL SELECT 'P2', 'C#' FROM DUAL UNION ALL SELECT 'p3', 'Oracle' FROM DUAL UNION ALL SELECT 'p3', 'C#' FROM DUAL), SKILLS (LANG) AS ( SELECT 'Java' FROM DUAL UNION ALL SELECT 'C#' FROM DUAL), -------------- --End if data preparation -------------- APPLICANTS_GROUP AS (SELECT P.P_ID, (SELECT S.LANG FROM SKILLS S WHERE S.LANG = P.LANG AND ROWNUM = 1) LANG FROM APPLICANTS P) SELECT p_id FROM APPLICANTS_GROUP WHERE LANG IS NOT NULL GROUP BY P_ID HAVING COUNT(DISTINCT LANG) = (SELECT COUNT(DISTINCT LANG) FROM SKILLS); Output: | P_ID | |------| | P2 | So, query for your tables(APPLICANTS and SKILLS ) would be WITH APPLICANTS_GROUP AS (SELECT P.P_ID, (SELECT S.LANG FROM SKILLS S WHERE S.LANG = P.LANG AND ROWNUM = 1) LANG FROM APPLICANTS P) SELECT p_id FROM APPLICANTS_GROUP WHERE LANG IS NOT NULL GROUP BY P_ID HAVING COUNT(DISTINCT LANG) = (SELECT COUNT(DISTINCT LANG) FROM SKILLS); Thank you Preet Sangha, you put me on the correct track. I had no idea you could sub query a FROM statement. Looks like you went back and edited to exactly what I was going to point out. Previously those statements without the join on skill returned p1. Seemingly because p1 had 2 skills and there were only 2 required skills but it was not checking whether or not they were the correct skills. This is what I came to before your edit. SELECT A.Name FROM (SELECT APPLICANTS.Name, APPLICANTS.SKILL FROM APPLICANTS, SKILLS WHERE APPLICANTS.SKILL = SKILLS.SKILL) A GROUP BY A.Name HAVING COUNT(*) = (SELECT COUNT(*) FROM SKILLS)
common-pile/stackexchange_filtered
Are there any hidden words in this sentence? Children growing up in Costa Rica are surrounded by some of the most beautiful and diverse landscapes in the world........................................................................................................................ Am I right ?...................... ........................................................................................................... Children "are" growing up in Costa Rica"which they" are surrounded by some of the most beautiful and diverse landscapes in the world. ................................................................................................. Are "are" and "which they" hidden in the above sentence? reduced relative clauses.... some call it, whiz deletion, I think is what you are asking about. I think because the question as it looks, is not very clear. If you want to start a new line, press the spacebar twice and then "enter" tab. Please get rid of those dotted lines. Related: “I hate Jill singing those songs.” = “I hate Jill when she is singing those songs.”? and Shakespearean relative clause: “I have a brother is condemned to die” The word "are" is not missing or hidden, you would simply reposition it. The "which they" would be completely out of place, unless you say "where they..." No, there is no ellipsis in your example. "Children growing up in Costa Rica" could be replace by "childen who grow up/are growing up in Costa Rica" without changing the sense, but that would be a different construction. "Which they" is entirely impossible to put into your sentence, though you could say "[Some] children grow up in Costa Rica, where they are surrounded...". Again, this is a different construction, and not quite the same meaning. The main verb is "are surrounded"; the subject is the entire phrase before that.
common-pile/stackexchange_filtered
Transformation Theorem and Showing Independence of N(0,1) Random Variables I am trying to solve the following problem: Show that the following procedure generates $N(0, 1)$-distributed random numbers: Pick two independent $U(0, 1)$-distributed numbers $U_1$ and $U_2$ and set $X = \sqrt{−2 \log U_1 }·\cos(2 \pi U_2)$ and $Y = \sqrt{−2 \log U_1} ·\sin(2 \pi U_2)$. Show that $X$ and $Y$ are independent $N(0, 1)$-distributed random variables. I am trying to apply the transformation theorem for multivariate random variables. So far I have: $f_{X,Y}(x,y)=f_{U_1,U_2}(u_1(x,y),u_2(x,y))|J|$ where $u_1(x,y),u_2(x,y)$ are the expressions for $u_1,u_2$ in terms of $x,y$. Then I could apply the independence of $U_1,U_2$ to split the joint distribution into the two $U(0,1)$ distributions and substitute in the expressions for $u_1(x,y),u_2(x,y)$. I just feel like something is off because trying to solve $X = \sqrt{−2 \log U_1 }·\cos(2 \pi U_2)$ and $Y = \sqrt{−2 \log U_1} ·\sin(2 \pi U_2)$ for $U_1,U_2$ and then solving for the Jacobian seems excessively difficult. Any tips or ideas would be very helpful. Thanks. Update: You can solve it using what is outlined above. The algebraic details are filled in here as well in section 2.4.3: http://www.mathematik.uni-ulm.de/numerik/teaching/ss09/NumFin/Script/chap2_4-2_5.pdf Nevertheless this is more or less what is to be done... As a preliminary, separate, step, you might want to compute the distribution of $R=\sqrt{-2\log U_1}$. I think I've posted an answer to this question here before. ${}\qquad{}$
common-pile/stackexchange_filtered
Can I use a power supply to power a solenoid electromagnet? I've got several unused coils of 14 gauge wire that have ferrite iron cores cut to the length of their spools. They have maximum current power transmission ratings of ~5.9A, and according to a resistance by length calculator on google the overall resistance is less than an ohm for the entire spool. I'm trying to figure out a part that could be used to power the solenoids. I'm hoping to find a simple unit that can plug into a surge protector with 1 cord for each of the three solenoids. Eventually after the solenoids are each powered correctly, I'll want to be able to control the current going to each with a microcontroller with a reasonable resolution. Is there any simple way to do this without needing to purchase many more components? I've looked into using a voltage-regulator IC + voltage-divider/digital potentiometer setup. The output of the voltage IC would then adjust a power transistor to let current through based on the voltage. Would a power supply such as this one be able to be controlled by a microcontroller in this way? https://www.amazon.com/Adjustable-Converter-110V-220V-Switching-Transformer/dp/B0777MH681?ref_=fsclp_pl_dp_3 Yes but it will not be very powerful (10%) compared to an iron core solenoid. Ferrite cores have low saturation flux density as compared to Iron cores. ... Advantage of ferrite cores lies in their low eddy current losses (due to their higher resistivity) even at high frequencies used in SMPS where iron cores if used result into extremely high losses. So the power supply will work to maybe 10V or 1 Ohm as long as stored energy is not released back into supply. One can superimpose a low frequency sine with DC current and measure the attenuation of 10% to define the max DC current at the threshold of saturation. Such as a rectified sine from a transformer, with an active NPN or Nch load and big heatsink to define this max current as long as transformer has much lower DCR output than solenoid. Then using Ohm’s Law choose Vdc average or RMS from rectified sine or your adequate DC power supply to drive Imax = V/Z(f) where Z(f)= 2pifL + DCR. Current then rises at the rate to Imax after some time, dt with dI=Vdt/L. After time t, the solenoid if current saturates the core, I will accelerate as L drops to 0 then current must be cutoff. For steel this Bmax threshold is smooth, while for ferrite it is lower and sharply reduces L. Therefor the current must be limited by the DCR (<1Ohm) under Imax where inductance drops 10% or limited by thermal rise and thermal resistance ‘C/W. I'm sorry, it is an iron core. 98% Iron and 2% something else. I thought that iron core still act as a ferrite magnet. 2% silicon. This must be cold rolled grain oriented steel laminated in silicate insulation or CRGOS to get high mu. Ferrite is dispersed iron particles in a ceramic binder
common-pile/stackexchange_filtered
Why does tempfile and os.chdir() throw RecursionError? import os, tempfile with tempfile.TemporaryDirectory() as tempdir: os.chdir(tempdir) Why does this throw a RecursionError? How is this bit of code recursive in the first place? How would I go about changing the working directory to that of a temporary one? The traceback should show you where the code loops. Not able to reproduce the problem with provided code Can you add the full traceback error that you get, along with any surrounding code from this snippet? Using just this snippet I get no errors. @KJTHoward Here's the traceback: https://hastebin.com/abamarijit.sql And there is no surrounding code, it's just this "with" statement. There's your real error message: The process cannot access the file because it is being used by another process. You have to leave the folder before it gets destroyed. This might be unique to less tollerant operating systems. @KlausD. You're right. Changing working directory back to original rids the error. The actual error is this: The process cannot access the file because it is being used by another process The working directory needs to be changed before tempdir is deleted.
common-pile/stackexchange_filtered
IF Formula, Within 90 days condition I have a formula which works off two tables. The formula reads the company name in the same row (Column B, in this case row 22), and does a vlookup in another table to find a match. It then looks for the word 'Won' in column Z of the same row, and then if the date in column AH is within 90 days. If both are true, it should return 'Trading', if it returns 'Won' but the date is over 90 days, it should return 'Dormant', and if 'Won' isn't found, it should return 'Potential'. However it's not picking up the date correctly, as changing the date under or over 90 days doesn't change the output. I'm also unsure on the best way to make it equal 'potential' for names it can't find or names that don't equal 'won'. Here's the formula: =IF(AND(LOOKUP(2,1/(KPI!$A$1:$A$14266=""&TEXT(B22,0)&""),KPI!$Z$1:$Z$14266)="Won",LOOKUP(2,1/(KPI!$A$1:$A$14266=""&TEXT(B22,0)&""),KPI!$AH$1:$AH$14266)-TODAY()<=90),"Trading",IF(AND(AND(LOOKUP(2,1/(KPI!$A$1:$A$14266=""&TEXT(B22,0)&""),KPI!$Z$1:$Z$14266)="Won",LOOKUP(2,1/(KPI!$A$1:$A$14266=""&TEXT(B22,0)&""),KPI!$AH$1:$AH$14266)-TODAY()>90)),"Dormant","Potential")) Any help appreciated, thanks! Would you be able to give some sample data or a screenshot of the data you are working with? Dates in Excel are tricky. Are the dates in your data real Excel dates, or are these text fields ? are the dates supposed to be in the future or in the past? As you have "Won" there I assume they should be in the past, but then your LOOKUP(...)-TODAY()>90 is wrong as it only gets positive value if your lookup date is in the future so only returns TRUE if the date lookuped is after 18.3.2019 in case of today which I am not sure is your intention. As @JoeJam correctly stated it would help to have a sample.
common-pile/stackexchange_filtered
How Do I remove video playback on my iPhone 7 completely? Hi I want to completely disable the ability to play videos on my iPhone. I don't mind jailbreaking the phone to change some core settings if this is the solution. I'm not just not sure what to change. Thank you. iPhone 7 OS 12. Welcome to Ask Different. It would help us if you provided additional info, such as the OS version. Also let us know what you've already done to solve the problem yourself. Please see [ask] for how to ask good questions that have a better chance at being answered. - From Review Added the OS. I basically want to know if it is possible to change core setting to stop videos from playing? No it is not possible. If you jailbreak? No idea, that would be best asked on jailbreaking forums. Do you want to stop them from playing automatically or at all? Are you talking about video games? At all, and not just video games, any video playback Can I ask why? We might be able to give you a better answer if we know what you are trying to accomplish. Turn on Screen Time in Settings and you could allow the apps you want or need and keep the ones you don't want out. Also in Screen Time settings under Content & Privacy Restrictions you can turn off or restrick settings. You can choose to not allow apps. You can choose Don't allow Movies and scroll down to the bottom and turn off Show movies in the Cloud.
common-pile/stackexchange_filtered
Detect ScrollView has reached the end I have a Text with long text inside a ScrollView and I want to detect when the user has scrolled to the end of the text so I can enable a button. I've been debugging the event object from the onScroll event but there doesn't seem any value I can use. I did it like this: import React from 'react'; import {ScrollView, Text} from 'react-native'; const isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => { const paddingToBottom = 20; return layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom; }; const MyCoolScrollViewComponent = ({enableSomeButton}) => ( <ScrollView onScroll={({nativeEvent}) => { if (isCloseToBottom(nativeEvent)) { enableSomeButton(); } }} scrollEventThrottle={400} > <Text>Here is very long lorem ipsum or something...</Text> </ScrollView> ); export default MyCoolScrollViewComponent; I wanted to add paddingToBottom because usually it is not needed that ScrollView is scrolled to the bottom till last pixel. But if you want that set paddingToBottom to zero. Note that if your content is shorter than the container, then this will trigger always. If you have a case where your paddingToBottom is negative (e.g. for handling overscroll), then make sure to handle this situation separately (basically by contentOffset.y > -paddingToBottom (note the resulting double negative)) This is not triggering "always" for me. onScroll only is called when the user scrolls. in scroll end it is working perfect but when I scroll up from last ending point then it called. So any solution to stop this issue when scroll up? I had that same problem, on IOS it worked great but android was glitchy. Try using onMomentumScrollEnd instead which calls an event every time the scroll stops. Note that the parameters are destructured twice in his example. It's prone to making mistake. I have implemented the above code and it worked for both iOS and Android, but it is not working on my web browser. Any ideas? As people helped here I will add the simple code they write to make reached to top and reached to bottom event and I did a little illustration to make things simpler <ScrollView onScroll={({nativeEvent})=>{ if(isCloseToTop(nativeEvent)){ //do something } if(isCloseToBottom(nativeEvent)){ //do something } }} > ...contents </ScrollView> isCloseToBottom({layoutMeasurement, contentOffset, contentSize}){ return layoutMeasurement.height + contentOffset.y >= contentSize.height - 20; } ifCloseToTop({layoutMeasurement, contentOffset, contentSize}){ return contentOffset.y == 0; } <... onScroll={(e) => { let paddingToBottom = 10; paddingToBottom += e.nativeEvent.layoutMeasurement.height; if(e.nativeEvent.contentOffset.y >= e.nativeEvent.contentSize.height - paddingToBottom) { // make something... } }}>... like this react-native 0.44 For Horizontal ScrollView (e.g. Carousels) replace isCloseToBottom function with isCloseToRight isCloseToRight = ({ layoutMeasurement, contentOffset, contentSize }) => { const paddingToRight = 20; return layoutMeasurement.width + contentOffset.x >= contentSize.width - paddingToRight; }; how about close to left? is this possible? const isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => { const paddingToBottom = 120 return layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom} <ScrollView onMomentumScrollEnd={({ nativeEvent }) => { if (isCloseToBottom(nativeEvent)) { loadMoreData() } }} scrollEventThrottle={1} > Above answer is correct but to callback on reaching the end in scrollView use onMomentumScrollEnd not onScroll you should remove that async keyword, it's useless, and because of that the isCloseToBottom result will always be detected as true Another solution could be to use a ListView with a single row (your text) which has onEndReached method. See the documentation here But this would require that each paragraph of the text to be treated with a DataSource and create a component (a simple Text would do). Not a bad idea, but might be a little bit more complex to implement. Your onEndReached has saved me a lot of time. ListView is deprecated. https://reactnative.dev/blog/2017/03/13/better-list-views.html @Henrik R's right. But you should use Math.ceil() too. function handleInfinityScroll(event) { let mHeight = event.nativeEvent.layoutMeasurement.height; let cSize = event.nativeEvent.contentSize.height; let Y = event.nativeEvent.contentOffset.y; if(Math.ceil(mHeight + Y) >= cSize) return true; return false; } why should you use the Ceil? As an addition to the answer of Henrik R: If you need to know wether the user has reached the end of the content at mount time (if the content may or may not be too long, depending on device size) - here is my solution: <ScrollView onLayout={this.onLayoutScrollView} onScroll={this.onScroll}> <View onLayout={this.onLayoutScrollContent}> {/*...*/} </View> </ScrollView> in combination with onLayout(wrapper, { nativeEvent }) { if (wrapper) { this.setState({ wrapperHeight: nativeEvent.layout.height, }); } else { this.setState({ contentHeight: nativeEvent.layout.height, isCloseToBottom: this.state.wrapperHeight - nativeEvent.layout.height >= 0, }); } } I use ScrollView and this worked for me Here is my solution: I passed onMomentumScrollEnd prop to scrollView and on the basis event.nativeEvent I achieved onEndReached functionality in ScrollView onMomentumScrollEnd={(event) => { if (isCloseToBottom(event.nativeEvent)) { LoadMoreRandomData() } } }} const isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => { const paddingToBottom = 20; return layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom; }; you can use this function onMomentumScrollEnd to know scroll information (event) <ScrollView onMomentumScrollEnd={({ nativeEvent }) => { handleScroll(nativeEvent) }}> and with these measure (layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom) you can know if the scroll is at the end const handleScroll = ({ layoutMeasurement, contentOffset, contentSize }) => { const paddingToBottom = 20; if (layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom) { ... } }; disregard all convoluted answers above. this works. import React, { useState } from 'react'; import { ScrollView } from 'react-native'; function Component() { const [momentum, setMomentum] = useState(false) return ( <ScrollView onMomentumScrollBegin={() => setMomentum(true)} onEndReached={momentum === true ? console.log('end reached.') : null} onEndReachedThreshold={0} > <Text>Filler Text 01</Text> <Text>Filler Text 02</Text> <Text>Filler Text 03</Text> <Text>Filler Text 04</Text> <Text>Filler Text 05</Text> </ScrollView> ) } When I try this I get an error that property onEndReached does not exist on ScrollView
common-pile/stackexchange_filtered
Equivalent sqlsrv_ for array_push() in PHP, XAMPP, SQL SERVER 2012 Is there an equivalent code for array_push() in sqlsrv_? Like sqlsrv_array_push(). I'm not sure if it has one, I haven't read a documentation on that code. Is there an alternative for this? I tried to re-code it, and this is what I've got so far. EDIT: Added conn.php <?php $serverName = "XXXXXX\XXXXXX"; $connectionInfo = array( "Database"=>"XXXXXX", "UID"=>"XXXXXX", "PWD"=>"XXXXXX"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) { echo "Connection established.<br />"; }else{ echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); } ?> EDIT: Added $and $and = 'AND YEAR(date) = '.$year; $months = array(); $ontime = array(); $late = array(); for( $m = 1; $m <= 12; $m++ ) { $sql = "SELECT * FROM CHECKINOUT WHERE MONTH(CHECKTIME) = '$m' AND CHECKTYPE = 'I' $and"; $oquery = $conn->query($sql); array_push($ontime, sqlsrv_num_rows($oquery)); $sql = "SELECT * FROM CHECKINOUT WHERE MONTH(CHECKTIME) = '$m' AND CHECKTYPE = 'O' $and"; $lquery = $conn->query($sql); array_push($late, sqlsrv_num_rows($lquery)); $num = str_pad( $m, 2, 0, STR_PAD_LEFT ); $month = date('M', mktime(0, 0, 0, $m, 1)); array_push($months, $month); } This is the error that I'm getting. Warning: sqlsrv_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\path\tofile\home.php on line 198 What is $conn and $and? Your query failed, so there's probably a syntax error in the query somewhere. Enable error-reporting and figure out what went wrong. No, PHP Driver for SQL Server hasn't such a function. Can you explain why you need such a function? Probably there is another way to achieve your results. @Qirel $and = 'AND YEAR(date) = '.$year; addendum. @Zhorov I'm trying to make a row on all data available for array_push($ontime, sqlsrv_num_rows($oquery));, I use the data to make a chart. Use sqlsrv_errors() to figure out why the query failed. Clearly the query fails since $Xquery is a boolean. I wasn't aware that there was an OOP interface for sqlsrv_ though. @Qirel, thank you. I used the sqlsrv_errors(). It was the $and = 'AND YEAR(date) = '.$year; It should be $and = 'AND YEAR(CHECKTIME) = '.$year;! I will update you soon. Explanations: If I understand your logic, you need to replace $conn->query($sql); with sqlsrv_query() call. Functions sqlsrv_? are part of PHP Driver for SQL Server and are not object oriented. Example: Next example is based on your code and may help to get your expected results: <?php $and = 'AND YEAR(CHECKTIME) = '.$year; $months = array(); $ontime = array(); $late = array(); for( $m = 1; $m <= 12; $m++ ) { $sql = "SELECT * FROM CHECKINOUT WHERE MONTH(CHECKTIME) = '$m' AND CHECKTYPE = 'I' $and"; $oquery = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET)); if ($oquery === false) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; } array_push($ontime, sqlsrv_num_rows($oquery)); $sql = "SELECT * FROM CHECKINOUT WHERE MONTH(CHECKTIME) = '$m' AND CHECKTYPE = 'O' $and"; $lquery = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET)); if ($lquery === false) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; } array_push($late, sqlsrv_num_rows($lquery)); $num = str_pad( $m, 2, 0, STR_PAD_LEFT ); $month = date('M', mktime(0, 0, 0, $m, 1)); array_push($months, $month); ?> Notes: You may also consider using parameterized queries: <?php $y = 2019; $months = array(); $ontime = array(); $late = array(); for( $m = 1; $m <= 12; $m++ ) { $sql = "SELECT * FROM CHECKINOUT WHERE YEAR(CHECKTIME) = ? AND MONTH(CHECKTIME) = ? AND CHECKTYPE = 'I'"; $oquery = sqlsrv_query($conn, $sql, array(&$y, &$m), array("Scrollable" => SQLSRV_CURSOR_KEYSET)); if ($oquery === false) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; } array_push($ontime, sqlsrv_num_rows($oquery)); $sql = "SELECT * FROM CHECKINOUT WHERE YEAR(CHECKTIME) = ? AND MONTH(CHECKTIME) = ? AND CHECKTYPE = 'O'"; $lquery = sqlsrv_query($conn, $sql, array(&$y, &$m), array("Scrollable" => SQLSRV_CURSOR_KEYSET)); if ($lquery === false) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; } array_push($late, sqlsrv_num_rows($lquery)); $num = str_pad( $m, 2, 0, STR_PAD_LEFT ); $month = date('M', mktime(0, 0, 0, $m, 1)); array_push($months, $month); } ?> This is way better, thank you. All i need now is to set $year; in $y = 2019; since it is a drop-down option. @pjustindaryll Glad to help! I've added sqlsrv tag for future readers. Thanks.
common-pile/stackexchange_filtered
Code your own IOC Container Has anyone out there written their own IOC Container in C#? Or do the vast majority of folks use the various frameworks such as Spring. What are the pro's and con's of each? charkit: I think the question on its own is pretty platform-agnostic. Some platforms may force you to write one, since they've got no existing one, but other than that ... It's a good excercise to write your own but in the end you might want to use an existing container. You could start with this one in 15 lines of code. And then read his follow-up about why you shouldn't make your own: http://ayende.com/Blog/archive/2007/10/20/Dependency-Injection-doesnt-cut-it-anymore.aspx I liked this 33 line container implementation from Ken Egozi inspired by Ayende's 15 liner Huh - I don't know how I missed this answer :) @KenEgozi Your promotions, marketing and SEO teams need to up their act I reckon :D Yeah I'm definitely going to shake their boat! Dead link, can be fixed by removing forward slash from end. @callumWatkins thanks for the alert; fixed. If I see this comment again with an ack and yours gone, I'll delete this... Someone has wrote one in C# : http://ninject.org/. It's open source so you can get the code and see how this guy did it. yea why write your own. Just use this. Phil Haack (Manager of the MVC team) uses it also for Subtext. Unless there's a very good reason I wouldn't go reinvent the wheel and implement a IoC container myself, specially because there are are a lot of good options like Unity, Ninject or Spring.net. If you need/want to remove the dependency to any of these IoC containers you may try out the Common Service Locator interface. I have written an IoC / DI Container in c# that implements the Common Service Locator. I wrote it mostly for learning purposes, but when I completed it, I decided to make it open source. If any of you would like to try out IInject, it can downloaded here. If you are looking for lightweight & high performance IoC container, then you should check out Munq James Kovacs presents a dnrTV episode on this subject here. Here also wrote an article. However during the article he mentions that you would probably want to use one of the pre-built ones. Since there are many diverse looks for them. Ninject, StructureMap, Autofac use a fluent interface. Spring, Castle Windsor, and Unity are more XML config driven. Castle Windsor can also use boo as an interface. Many have hooks to other frameworks such as Unity to EntLib or Castle Windsor to Monorail and the rest of the Castle Project. So unless you really need or want something that is not provided by the IOC frameworks available, then why not use one of them. Autofac is excellent. I've written one myself using less than 15 lines. Just two extensionmethods to a dictionary. IOC container is not hard to write, it is just a well managed global recursive factory with some potential additional features. Using dictionary, reflection and delegate to register and build a simple container... The real question is why and how another new IOC container framework can bring benefits? In most of cases, you think you need more performance? non existing features? But most of time, existing frameworks is just what you need and enough, unless you have become aware of all the nonsense that the framework has forced you to do to use it. has the force of being disappointed by all the implementations of framework of ioc container of has features that are of the order of the antipattern, but also quirky and unreliable syntaxes and worse in ore of imposed couplings, I decided myself to experience it. This is why I made my own (very light) IOC container as open source. You can check it here : Puresharp API .net 4.5.2+ Ayende also wrote about writing your own IoC container in his blog post Building an IoC container in 15 lines of code, I believe he's of the same opinion as everyone else though: don't build your own if you don't have to. Dup of http://stackoverflow.com/questions/386535/c-code-your-own-ioc-container/386618#386618 I created my own IoC container that makes it easier to debug the creation of the object (even when you have no access to the container code). When the object is created, when pressing Step into (F11) you see the code to create the object. Full code can be seen here. The thing is that there are so many IoC and DI libraries which makes you confused. When you develop something with one of them and you grow, you'll tightly couple your product with such tools and you'll need experts in those to continue the development. It's all about the politics of the company and the design complexity. I myself planned to do it manually therefore no much hidden code. I know there are bunch of great open source IoC tools but who actually goes through the code and tries to understand? Not about reinventing the wheel but sometimes it's good if you can your own custom wheel that fits your product better.
common-pile/stackexchange_filtered
How to ignore or exclude a file when pull request in github We have 4 branches, 1-dev, 2-qa, 3-staging, 4-master. We want to update and add some people in CODEOWNERS file in 1-dev, and 2-qa to 4-master's CODEOWNER's file will be retain. Since there are 4 reviewers for 1-dev and 2 reviewers for 2-qa to 4-master. I tried adding .gitattributes file that contains: CODEOWNERS -diff CODEOWNERS linguist-generated=true So I tried to push this in all branches, and update the CODEOWNER file in 1-dev. But when merging from 1-dev to 2-qa, the CODEOWNERS file is still modified. How do I exclude or ignore this file when pull requesting? Thanks. What you're asking for is a way to avoid merging certain files, and GitHub doesn't support this because, in general, Git doesn't support this. This question has been asked on the Git list, and the general answer is that while this is possible with a custom merge driver, it's not a good idea. Since GitHub doesn't use custom merge drivers, you'd need to both create a custom merge driver and set it using the merge attribute in .gitattributes and then do all manual merges with a bot instead of letting GitHub do the merges. That would allow you to do it if you really want to, but, as mentioned above, the Git developers don't recommend it. Thanks for the reply. So it's not possible to use custom merge drivers when using GitHub Website? Correct. The program to run when using a custom merge driver exists in your configuration. Git doesn't allow transferring configuration in the repository for security reasons, so GitHub doesn't even know what tool you're using for your custom merge driver.
common-pile/stackexchange_filtered
Distributed WSO2 APIM: Problems with KeyManager Now I am testing the API-Manager doing a distributed install of pruduct. When I start the Analytitcs and publisher (both in ditributed hosts), the analytic's Log don´t stop to show the error messages: [2018-04-12 15:00:18,770] ERROR {org.wso2.carbon.databridge.core.internal.queue.QueueWorker} - Dropping wrongly formatted event sent for -1234 org.wso2.carbon.databridge.core.exception.EventConversionException: Error when converting loganalyzer:1.0.0 of event bundle with events 1 at org.wso2.carbon.databridge.receiver.thrift.converter.ThriftEventConverter.createEventList(ThriftEventConverter.java:181) at org.wso2.carbon.databridge.receiver.thrift.converter.ThriftEventConverter.toEventList(ThriftEventConverter.java:90) at org.wso2.carbon.databridge.core.internal.queue.QueueWorker.run(QueueWorker.java:73) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: org.wso2.carbon.databridge.core.exception.EventConversionException: No StreamDefinition for streamId loganalyzer:1.0.0 present in cache at org.wso2.carbon.databridge.receiver.thrift.converter.ThriftEventConverter.createEventList(ThriftEventConverter.java:166) ... 7 more This means the APIM (or other product) is sending events with streamId loganalyzer:1.0.0 , however the analytics server has no such stream definition. The analytics server is effectively a WSO2 DAS with preconfigured streams and analytics related to some other product. The log messages indicates, that the analytics application (org_wso2_carbon_analytics_apim-1.0.0.car) is not (yet) deployed. It happens commonly when you start up the analytics server, it receives the product (APIM) events before the analytics app is deployed. Once the analytics app is deployed, the DAS should stop logging these messages So in your case I'd try to have a look on the analytics server in the start of the log file why the analytics application is not properly deployed I will try to make the install using version2.2.0.. The version 2.1 have 38 patchs and I don´t have access to it.
common-pile/stackexchange_filtered
Force content update to cloudfront, without using invalidate I am using cloud front as CDN. Is there a way to force a content update? I have a file on my origin server which I've updated with a new version (same name, new date time stamp). But when I check it in cloudfront, its still the old file. I have seen this thread which suggest one way as invalidate, but I don't want to do that because its an overhead I think and there can be maximum 3 invalidation request running at a time. I read that cloudfront is supporting dynamic content using query parameters, can I make use of it somehow to force cloudfront to pull the latest content from the distribution server. The first one is as you mentioned to explicitly call invalidate(). They do have a 3 invalidation request limit, but each request can contain up to 1000 objects which in most cases are fairly enough. It usually takes 10 - 15 mins according to the doc, but my experience of this is rather fluctuated (can take up to 30min in some cases). The other approach of dynamic parameter is definitely doable and which is a preferred way. What you need to is append a timestamp param at the end of you link's end. Something like: http://www.example.com/img/logo.png?timestamp=123456789 Once you updated your logo.png, change the timestamp to the new one: http://www.example.com/img/logo.png?timestamp=223456789 And cloudFront will be able to distinguish these two and pick the right one. So yes, I believe your analysis is on the right track.
common-pile/stackexchange_filtered
How to run racket with geiser: getting error:Can't exec program: /Applications/Racketv6.0/DrRacket.app I am new to Emacs and I am having a bit of trouble. I am looking to run racket from Emacs using Geiser. I told Emacs where racket is as follows: (setq geiser-racket-binary "/Applications/Racket\ v6.0/DrRacket.app") (I took this from StackOverflow question: Setting Racket Geiser Emacs Path.) I start by compiling the racket code that is saved. However, when I attempt to hit M-x followed by run-geiser, it then prompts me for a Scheme implementation. At this point I type racket. Emacs now opens a racket REPL buffer and in that buffer it leaves the error: Can't exec program: /Applications/Racketv6.0/DrRacket.app . If it helps, here is my .emacs file: (custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(geiser-repl-startup-time 20000) '(package-archives (quote (("gnu" . "elpa gnu packages website") ("melpa" . "http://melpa.milkbox.net/#/")))) '(package-directory-list (quote ("/Applications/Emacs.app/Contents/Resources/site-lisp/elpa"))) '(python-python-command "/usr/local/bin/python3")) (setq geiser-racket-binary "/Applications/Racket\ v6.0/DrRacket.app") (setq-default cursor-type 'bar) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(default ((t (:inherit nil :stipple nil :background "controlDarkShadowColor" :foreground "Green" :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 120 :width normal :foundry "apple" :family "Monaco"))))) (require 'package) (add-to-list 'package-archives '("marmalade" . "http://marmalade-repo.org/packages/")) (package-initialize) I think you are referencing the wrong executable. "DrRacket" is an IDE (with a graphical user interface) for editing Racket code. From man drracket: DrRacket is the Racket programming environment. Try setting geiser-racket-binary to the location of the racket executable (which is the "core Racket implementation") instead. EDIT If the naming scheme of the Mac installation of Racket is anything like the one used for the Linux installation, there should be a binary called Racket or racket in a location similar to where you can find the DrRacket (or drracket) binary: $ locate racket ... /usr/bin/drracket /usr/bin/gracket /usr/bin/gracket-text /usr/bin/racket ... (Not suggesting that you will find the binaries in /usr/bin/, just trying to illustrate that there is a good chance all binaries that are possibly relevant are located in the same directory.) On OS X xxx.app is technically a directory. The actual executable file is located in Content/MacOS/xxx (if my memory serves me correctly). EDIT: In other words, you should write something like: (setq geiser-racket-binary "/Applications/Racket\ v6.0/DrRacket.app/Content/MacOS/DrRacket") Note: I'n not at my Mac so I can't verify the details right now. I suppose that means that I would want for replace "/Applications/Racket\ v6.0/DrRacket.app" with the actual executable file??? Does the "xxx" refer to "/Applications/Racket\ v6.0/DrRacket.app" or some sub-string of this (or something else)? Also does "Content" and "MacOS" refer to something or themselves literally?? I apologize for my confusions, and thank you for your answer, I think you at least got a little closer to understanding what needs to be done.
common-pile/stackexchange_filtered
$\lim\sup$ and $\lim\inf$ of a sequence of independent random variables with two states Let $(X_n)_{n\geq1}$ be a sequence of random variables such that $$ \mathbb{P}(X_n= n^{2/3})=1-\mathbb{P}(X_n=0)=\frac{1}{3n}$$ Find $\lim\sup X_n$ and $\lim\inf X_n$. We know that \begin{align} \{\omega:\limsup X_n(\omega) = +\infty\} \end{align} is equivalent to \begin{align} \forall A >0, \exists n_0\in\mathbb{N} \quad&\text{s.t}\quad \forall n\geq n_0, \quad\sup_{k\geq n}X_k >A \\ \forall A >0, \exists n_0\in\mathbb{N} \quad&\text{s.t}\quad \forall n\geq n_0, \;\exists k\geq n, \quad X_k >A \end{align} and thus we have that \begin{align} \{\omega:\limsup X_n(\omega) = +\infty\} = \bigcap_{A>0}\lim\sup\{X_k>A\} \end{align} and we actually take a sequence $A_k$ of rationals such that $A_k \uparrow \infty$ to make sure that the event is measurable. Finally we check that, $\forall A_k>0$, $$ \sum_{n\geq 1}\mathbb{P}(X_n > A_k) = \sum_{n\geq A^{3/2}}\mathbb{P}(X_n = n^{2/3}) = \sum_{n\geq A^{3/2}}\frac{1}{3n} $$ which diverges because it's basically the harmonic series less a finite set of terms and multiplied by a constant and we conclude by the second Borel-Cantelli lemma that the event occur almost-surely and as all the events of the intersection happen almost-surely then $$ \mathbb{P}\left(\bigcap_{A_k>0}\lim_n\sup\{X_n>A_k\}\right)=1 $$ The $\lim\inf X_n =0$ goes about the same way as I found in other posts, however I don't know if the above answer I wrote is correct. I found many questions showing the calculations for the case where limit superior and limit inferior are equal to a constant, but didn't find any about the sequence diverging. Let $B_n$ be the event $\{X_n=n^{2/3}\}$. Then $\sum_{n\geqslant 1}\mathbb P(B_n)$ diverges hence, as you noticed, by the second Borel-Cantelli lemma, $\limsup_{n\to \infty}B_n$ has probability one hence for almost every $\omega$, there exists an infinite set $I(\omega)\subset\mathbb N$ such that for each $n\in I(\omega)$, $\omega\in B_n$ (that is, $X_n(\omega)=n^{2/3}$) hence we reach your conclusion in a bit shorter way.
common-pile/stackexchange_filtered
Typescript: why this code throws an exception while it is a 100% valid javascript code It is claimed that TypeScript is a superset of Javascript. Here's a question on Stack about this. Here's a quote from spec: TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. Every JavaScript program is also a TypeScript program. So my understanding is that any stand-alone javascript file can be treated as a valid typescript code, i.e. compiled (may be with some additional flags) by tsc compiler. But here's an example of js code: class ClassA {} ClassA.prototype.ping = () => {console.log('PING')} That is valid javascript but if you'll try to compile it with typescript, you'll get: error TS2339: Property 'ping' does not exist on type 'ClassA' One can declare interface which ClassA can implement, also, it's highly untypical to write code like this (combine class and prototype syntaxes) but nevertheless - this looks like an example of valid js code which raises an error while compiling with tsc. So the question is - how this does not contradict to the quote from spec? it might be valid JS, but it's not good JS. If you're using classes, don't do prototype manipulation. Either write true constructor function + prototype code, or use proper class code. Pretty sure typescript's preventing you from doing really weird shit(tm) here. class ClassA { ping() { console.log('PING'); }, ... } For future reference "Why does TS throw an error on this code?" might have been a more straightforward way of asking this same question, without the weirdly accusatory tone. @Retsam sure, let me edit title (at least) to get rid of any accusatory annotations, it's not about any accusations. @Mike'Pomax'Kamermans it definitely non-idiomatic but it's still a valid js code, and when something is claimed to be a superset one can expect this be executed. not necessarily: while the syntax is considered a superset, that does not mean parsing is identical. Compilers are allowed to be opinionated (although within that, there is always room for bugs or incompletions) See What does "all legal JavaScript is legal TypeScript" mean? TypeScript is a syntactic superset of JavaScript that doesn't change JavaScript's runtime behavior. So any expression or statement or declaration you write in JavaScript is syntactically legal TypeScript. This doesn't mean that all JS code is considered to be warning-free TypeScript. After all, a major goal of TypeScript is to identify bad constructs like var s = "hello world" * 423; var t = "qzz".subtr(2); var u = [1, 2, 3] + 5; var w = window.navgtator; These are all "valid" JavaScript expressions, they just happen to have undesirable runtime behavior that people don't want to actually do. As usual in TypeScript, you can tell the type system about extra information class ClassA {} // Declare additional method interface ClassA { ping(): void; } // OK ClassA.prototype.ping = () => {console.log('PING')} A discussion can be found here, same guy I guess commented at the end :) well, but strictly speaking, it's not a warning, it's a compile-time error. I'm not arguing, just saying. TS doesn't have a notion of warning vs error; I say "warning" here because TS will still emit code (unless you have noEmitOnErrors turned on). oh that's just great, thank you for clarification! - I've totally missed the point that code is still generated!
common-pile/stackexchange_filtered
Await inside for loop is admitted in Dart? I have a program like the following: main() async { ooClass = new OoClass(1); int val = await function1(); print(val); ooClass = new OoClass(2); val = await function1(); print(val); ooClass = new OoClass(3); val = await function1(); print(val); } OoClass ooClass; Future<int> function1() async { List list3 = await function2(); return list3.indexOf('Ok'); } Future<List<String>> function2() async { List<String> list1 = new List<String>(); function3(Map<String, int> map1) async { String string1 = ''; bool bool1 = false; List<String> list2 = []; String string2; function4(String string3) async { if (ooClass.function7(string3)) return; if (ooClass.function8() && !bool1) { bool1 = true; return; } string2 = await function5(string3); list2.add(string2); } for (String key in map1.keys) { await function4(key); } string1 = list2.join(', '); list1.add(string1); } for (Map<String, int> idxList in ooClass.function6()) { await function3(idxList); } return list1; } function5(String s1) { return new Future.value('Ok'); } class OoClass { List<Map<String, int>> map2; bool bool3 = false; OoClass(int type) { switch(type) { case 1: map2 = [{'Ok':1}]; break; case 2: map2 = [{'id': 1, 'Ok':1}]; break; case 3: map2 = [{'foo': 1, 'Ok':1}]; bool3 = true; break; } } List<Map<String, int>> function6() { return map2; } bool function7(String string9) { if (string9 == 'id') return true; return false; } bool function8() { return bool3; } } This snippet works perfectly. In my real environment, instead, when await function4(key); is called, function2 returns the list1 List (empty). Function4 call is executed later but the result of function2 is lost. I don't really understand this behavior. Could it be a bug or await inside for loop is not to be used? If await should not be used inside for loop how could I implement it in another way? I'm using dart 1.22.0-dev.4 but I've tried also with older (and stable) versions and I had the same result. I finally got the problem and it did not depend on await in a for loop. It was instead an error in my code. await in for is fine. Your code example is too complex, to bother to investigate further. Yes, await is permitted inside a for loop in Dart, and it will work as expected. for (var o in objects) { await doSomething(o); } And there is even await for for Streams, if that's what you're looking for: await for (var event in eventStream) { print("Event received: $event"); } Your example works correctly in DartPad. It's too complex & abstract to debug but, at least superficially, it should work. You say that the snippet doesn't work in your "real environment", though. Maybe we could help if you explained what you mean by that? Additional tip: take full advantage of static analysis, especially the await_only_futures and unawaited_futures linter rules. This can help you catch many bugs. what if await doSomething(o); has another await inside? Btw it's not working in my case List.forEach → Future.forEach If you happen to be using .forEach() on a List, this won't work: someList.forEach((item) async { await longFunc(item); )} You'll need to use: await Future.forEach<SomeType>(someList, (item) async { await longFunc(item); }); I mistakenly thought this applied to List.forEach until finding this answer. Example As per comments: add the List Type if needed. List<String> names = ['billy', 'joe']; Future.forEach<String>(names, (name) async { await Future.delayed(const Duration(milliseconds: 200)); print(name); }); Note that while this is the best approach, the compiler won't know the type of item within the block. So you may have to call await Future.forEach<TypeOfSomeList>(someList, (item) async { Thank you @DavidChopin -- I was getting an error like The property 'property' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!'). because I wasn't specifying the type in this way, and whatever the default is can be null ... I think this would have take a LONG time to figure out if I hadn't already seen your suggestion of a code tidy up here. Adding this comment in case the SEO brings others here.
common-pile/stackexchange_filtered
Reusing choco solver model to further constrain the solution I'm using the choco solver library to generate a set of puzzles. I need to run the solver, check how many solutions there are and if there is more than one, add an extra constraint. Repeating this will give me a set of constraints (clues) that has a unique solution. However once I've run model.getSolver(findAllSolutions()) any additional checks return zero solutions. I'm guessing I need to somehow reset the model solver but can't find a way of achieving this - I'd rather not generate a new model and recreate the exiting constraints if I have to. The original code has 110 IntVar's and a huge number of constraints, but I've created a much smaller example. Note: in the real application I use model.getSolver().findAllSolutions(new SolutionCounter(model,2)) to speed things up, but I've omitted that step here. Model model = new Model(); // setup two doors A and B, one has the value 0 the other 1 IntVar doorA = model.intVar("Door A", 0, 1); IntVar doorB = model.intVar("Door B", 0, 1); model.allDifferent(new IntVar[]{doorA, doorB}).post(); // setup two windows A and B, one has the value 0 the other 1 IntVar windowA = model.intVar("Window A", 0, 1); IntVar windowB = model.intVar("Window B", 0, 1); model.allDifferent(new IntVar[]{windowA, windowB}).post(); // assign the first constraint and count the solutions model.arithm(doorA,"=",0).post(); // this should force door B to be 1 - there are two remaining solutions List<Solution> solutions = model.getSolver().findAllSolutions(); System.out.println("results after first clue"); for (Solution s : solutions) { System.out.println(">"+s.toString()); } assertEquals("First clue leaves two solutions",2,solutions.size()); // add second clue model.arithm(windowA,"=",1).post(); // this should force window B to by 0 - only one valid solution List<Solution> solutions2 = model.getSolver().findAllSolutions(); System.out.println("results after second clue"); for (Solution s : solutions2) { System.out.println(">"+s.toString()); } assertEquals("Second clue leaves one solution",1,solutions2.size()); For anybody else looking for this, it turns out that the answer is simple. model.getSolver().reset();
common-pile/stackexchange_filtered
KeePass like program without password auth I'm looking for a program that's like KeePass's UI, and self contained 1 database file, but without the master password requirement. Essentially take KeePass, and remove the master password requirement. I'm not looking for a password manager, otherwise I'd just use KeePass. Instead I'm looking for something like KeePass' UI, but without the main password requirement. I will be using this for non-confidential data, but it's a great tool for sorting, searching and portability. Anyone know of something? That is a bad idea because if you don't have a master password, the passwords are stored in clear text or weak encrypted. Always remember if you don''t need a password, neither does an attacker! If you don't care about that, you can make an excel list. I'm not looking for a password safe. If i was, I'd use KeePass. I'm looking for a self contained database with the UI of KeePass. Something like a contact manager? I dont know what you'd call it. @Simon: Filesystem-level encryption. @grawity what do you want to say with that? You need a key to encrypt the file/folder. Edits made to question for clarity. Again, not looking for encryption, or passwords, or anything like that. Just use KeePass and instead of a password, use your user account to unlock it. @OliverSalzburg thought about that, but lacks portability, no? Can't stick it onto a USB stick and bring it to work because the user account UIDs would be different. @Pat: Yeah, you're right. How about a key file then? The key file should be automatically selected when you open your database (as in, KeePass remembers the last used key file in the config). That works for me, but I use a composite key (key file + password). The key file can be anything you want. You could just place it in your KeePass folder. If that isn't an option, I'm out of ideas for now :) You can try Roboform I use it without a master password. It does auto-login for Firefox and IE. You can make an entry not require the master password. Don't see why Roboform would not work in your case...
common-pile/stackexchange_filtered
Accidentally messed up /etc/passwd I accidentally modified the default shell program /bin/bash for my user in /etc/passwd. I didn't set a root password in my ubuntu server installation. Now I can't even login. Is there anything I can do? Boot up into a live disk, mount the partition and fix /etc/passwd :) Or .. start your box in single user mode and modify your passwd file - ubuntu single user mode link.
common-pile/stackexchange_filtered
Exchange email message not being sent through Powershell script Good day, The message for email users about expiring password is not being sent even though the script doesn't show any error message and runs successfully. Need help investigating where is the issue. I have checked O365 exchange admin message trace and there is nothing. Here is the code: # Import Active Directory module Import-Module ActiveDirectory # Set the maximum password age $maxDays = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.TotalDays # Define the email settings $emailFrom =<EMAIL_ADDRESS>$smtpServer = "smtp.office365.com" $smtpPort = 587 $smtpUsername =<EMAIL_ADDRESS># Replace with your SMTP username $smtpPassword = "my account password" # Replace with your SMTP password # Create the SMTP client object $smtp = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort) $smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword) $smtp.EnableSsl = $true # Define the OU and filter for Active Directory users $OU = "OU=xx,DC=xx,DC=xx" $filter = { Enabled -eq $true -and PasswordNeverExpires -eq $false -and Mail -ne $null } # Retrieve and process the Active Directory users within the specific OU $users = Get-ADUser -SearchBase $OU -SearchScope Subtree -LDAPFilter $filter -Properties pwdLastSet | Sort-Object pwdLastSet foreach ($user in $users) { $lastSet = [System.DateTime]::FromFileTimeUtc($user.pwdLastSet) $expires = $lastSet.AddDays($maxDays).ToShortDateString() $daysToExpire = [math]::Round((New-TimeSpan -Start (Get-Date) -End $expires).TotalDays) $firstName = $user.Name if ($daysToExpire -eq 14) { $subject = "Jūsų slaptažodis baigs galioti už $daysToExpire dienas" $body = "$firstName, text" $smtp.Send($emailFrom, $user.Mail, $subject, $body) } elseif ($daysToExpire -eq 3) { $subject = "Jūsų slaptažodis baigs galioti už $daysToExpire dienas" $body = "$firstName, text" $smtp.Send($emailFrom, $user.Mail, $subject, $body) } }``` You forgot to 'ask' to also get the property mail from the users on the Get-ADUser call, so $user.Mail will be $null Also, your $filter should be a string and you're not using ldap syntax on it so at least -LDAPFilter $filter should be -Filter $filter First thing I'd try is simply replacing those $smtp.Send lines with simply outputting the information to screen, eg write-host "emailFrom - $($user.Mail) - $subject - $body" and confirm what output you actually get, eg do you actually get any? That'll narrow down whether the issue is with the earlier query, or with how you're sending.
common-pile/stackexchange_filtered
Find the sum of series $ \sum_{n=1}^{\infty}\frac{1}{n^3(n+1)^3}$ Let it be known that $$\sum_{n=1}^{\infty}\frac{1}{n^2}=\frac{\pi^2} {6}.$$ Given such—find $$\sum_{n=1}^{\infty}\frac{1}{n^3(n+1)^3}$$ Attempt: I have tried using the fact that $\displaystyle \frac{1}{n(n+1)}=\frac{1}{n}-\frac{1}{n+1}$ and then expanding or using known sum types as $\displaystyle \sum_{k=1}^{n} k=\frac{n(n+1)}{2}$ or $\displaystyle \sum_{k=1}^{n} k^3=\frac{n^2(n+1)^2}{4}$ but nothing seems to lead to anything! What have you tried? i have tried using the fact that $\frac{1}{n(n+1)}=\frac{1}{n}-\frac{1}{n+1}$ and then expanding or using known sum types as $\sum_{k=1}^{n} k=\frac{n(n+1)}{2}$ or $\sum_{k=1}^{n} k^3=\frac{n^2(n+1)^2}{4}$ @Math3147 you are right.Sorry for that. HINT: Use the partial fraction decomposition $$\frac{1}{n^3(n+1)^3} = \left(\frac{1}{n^3} - \frac{1}{(n + 1)^3}+ \frac{6}{n} - \frac{6}{n+1}\right) - \left(\frac{3}{n^2} + \frac{3}{(n + 1)^2}\right) $$ The sum equals $(1+6) -( 3 \zeta(2) +3 \zeta(2)- 3)= 10 - \pi^2$. I'm basically just going to use the identity you noted in the comments $\frac 1n-\frac 1{n+1}=\frac 1{n(n+1)}$ repeatedly and then the closed form for $\zeta(2)$. $$\sum_{n=1}^\infty \frac 1{n^3(n+1)^3}=\sum_{n=1}^\infty \left(\frac 1n-\frac 1{n+1}\right)^3=\sum_{n=1}^\infty \frac 1{n^3}-\frac{3}{n^2(n+1)}+\frac{3}{n(n+1)^2}-\frac 1{(n+1)^3}$$ The first and last terms telescope so you get $$=1-3\sum_{n=1}^\infty \frac 1{n(n+1)}\left(\frac 1n-\frac 1{n+1}\right)=1-3\sum_{n=1}^\infty \left(\frac 1n-\frac 1{n+1}\right)^2$$ $$=1-3\sum_{n=1}^\infty \frac 1{n^2}-\frac{2}{n(n+1)}+\frac 1{(n+1)^2}$$ The first and last terms are $\zeta(2)$ and $\zeta(2)-1$ respectively $$=4-6\zeta(2)+6\sum_{n=1}^\infty \frac 1{n(n+1)}=4-6\zeta(2)+6\sum_{n=1}^\infty\frac 1n-\frac 1{n+1}=10-6\zeta(2)=10-\pi^2$$ Hint: $$ \frac{1}{n^3} - \frac{1}{{(n+1)}^3} \;=\; \frac{3n(n+1) + 1}{n^3{(n+1)}^3} $$
common-pile/stackexchange_filtered
Xcode 15+ iOS 17+ error: Failed to install the app on the device Not able to debug Apps from XCode 15+ on iOS 17+ devices. Tried disconnecting the VPN Tried updating path name from /Developer to /Developers Still nothing working on debugging iOS Device not showing up in the Supported Devices list.
common-pile/stackexchange_filtered
Type Casting Issue Using File Writer enter image description hereI have written a file writer and a file reader class in which you put data into and use it by file reader in another class methods. The type of my variable defined in Account class is integer.To write it in file, I change the type as String(because I have my other variables as String)...when I want to use that variable in my method in Account class, I can not compare it with the local variable(which is filled by user).It gives me a "NullPointerException" error. Can anyone help me with this?(The code is just a summary)enter image description here public class Account { int PIN; public void meth_name(){ int pin; if(PIN == pin) } } public class filewriter { public void met_name(){ .... fw.write("PIN: "+ Integer.toString(PIN)); } } Please don't add things like [SOLVED] to a question title. Instead accept the answer that helped you (or if the question is not answered (but not on hold), post your own answer). In Java when you are working with primitive types you cannot get NullPointerException because they are not pointers, they are allocated in Stack Memory. So you are getting NullPointerException because some other variable is null. It is difficult to understand which variable is null from the code snipped you provided. In your case NullPointerException might be thrown because The Account object which PIN you are acquiring is null The fw(filewriter) object which you are using is not yet initialized Please provide more code or the stack trace of NullPointerException to understand exception's root cause. Also please tell what is the type of fw object you used in the code. Is it java.io.PrintWriter or your custom class? I added photos... I assume the array accounts is null or there is such i for which accounts[i] is null. Add null-checks and test it. Also provide the exception Stack Trace. I'm happy that I could help you :D ... Could you please mark the answer as correct one if it really helped you?
common-pile/stackexchange_filtered
How to post and cast payload? My goal is to call api (via post), accept payload as base type and later cast it to concrete type. If I do that from main solution (where my api stands), everything works well. But I can't understand why same code doesn't work from other solutions. So I have my request (declared in different solutions) namespace Nb { public class NbRequestBase { public string BaseProp { get; set; } } public class NbRequestConcrete : NbRequestBase { public string ConcreteProp { get; set; } } } And this is my endpoint: [HttpPost] [Route("payments/nb")] public IHttpActionResult Prepare(NbRequestBase request) { if(request is NbRequestConcrete) { } try { // <<< INSERT CODE HERE >>> NbRequestConcrete nbRequestConcrete = (NbRequestConcrete)request; return Ok(); } catch (Exception ex) { _logger.Error(ex); return InternalServerError(); } } and this is my calling code: NbRequestConcrete requestTwo = new NbRequestConcrete() { BaseProp = "BaseProp", ConcreteProp = "ConcreteProp" }; using (var client = new HttpClient()) { var _clientId = "_clientId"; var _clientSecret = "_clientSecret"; client.BaseAddress = new Uri("http://localhost:50228"); #region Formatter JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter(); formatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All; List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>(); formatters.Add(formatter); #endregion var responseMessage = client.PostAsync($"payments/nb?clientId={_clientId}&clientSecret={_clientSecret}", requestTwo, formatter).Result; responseMessage.EnsureSuccessStatusCode(); } If I put my calling code into other project/solution (for example just new console app), API endpoint is hit, but payload is null. payload when called form console app If I put exacly same calling code into project where my api is (for example in same API endpoint method, at try/catch block start and call it again), API endpoint is hit, payload is NOT null and casting works. Why is it? And how to fix it? payload when called from same solution try/catch start And BTW. How to make this call via postman? Regards request is null or nbConcreteRequest is null? I updated my question. Payload images added This line tells the model binder to set the values of any matching properties in request to the value that was passed to the API: public IHttpActionResult Prepare(NbRequestBase request) The model binder does not attach all the other properties to the request, because it has no idea what they would be. Problem was Assemblies name where NbRequestConcrete in console app lived in one assembly and on API lived in other. So request was different. { "$type": "Nb.NbRequestConcrete, Tester", "ConcreteProp": "ConcreteProp", "BaseProp": "BaseProp" } VS { "$type": "Nb.NbRequestConcrete, MYApi", "ConcreteProp": "ConcreteProp", "BaseProp": "BaseProp" }
common-pile/stackexchange_filtered
Overwriting in a random access file I have a random access file opened in "r+b" mode with records of equal length. Can I change the contents of a record after reading it and overwrite in place? I tried the following code but on running I get: Segmentation fault(core dumped) #include<stdio.h> int main() { struct tala { int rec_no; long file_no; }; FILE *file_locking; struct tala t,f; file_locking = fopen("/path/to/my/file.bin", "rb+"); t.rec_no = 1; t.file_no = 3; if (fwrite(&t, sizeof(struct tala),1,file_locking)==0) printf("Error opening file"); t.rec_no=0; rewind(file_locking); if (fwrite(&t, sizeof(struct tala),1,file_locking)==0) printf("Error opening file"); rewind(file_locking); if (fread(&f, sizeof(struct tala),1,file_locking)==0) printf("Error opening file"); printf("\n %d",f.rec_no); printf("\n %ld", f.file_no); fclose(file_locking); } possible duplicate of Opening mode of Binary files Yes you can. Just remember to always fseek between reads and writes. Quote the fopen man page: Reads and writes may be intermixed on read/write streams in any order. Note that ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file. Extra tip: always check the return value of fopen and related functions, and handle errors (use perror or strerror to print out what failed). @Mat...Will be gratefull if you check my code that i have now included @Lipika: you're not checking the return value of fopen, so you're on your own. Thanks...The problem was with fopen. Opening in rb+ mode does not create the file if it does not exist from before. Yes. The only thing to pay attention is that you have to call flush or a file positioning function before switching from output to input and call a file positioning function or be at end of file before switching from read to write.
common-pile/stackexchange_filtered
Error: Unable to cast object of type 'System.Int32' to type 'System.String' I have finish perfectly coding Register Page, Login and now the UpdateCustomer page has errors - Background info : I'm using Microsoft Access as data source LabelState.Text = (string)Session["sState"]; LabelPostalCode.Text = (string)Session["sPostalCode"]; LabelContactNumber.Text = (string)Session["sContactNumber"]; LabelEmail.Text = (string)Session["sEmail"]; LabelPassword.Text = (string)Session["sPassword"]; Everything here is fine except LabelContactNumber.Text = (string)Session["sContactNumber"]. I believe it is because only ContactNumber in Access is set as Int the rest is Text therefore there's no error when I use (string). LabelContactNumber.Text = (Session["sContactNumber"] != null) ? Session["sContactNumber"].ToString() : string.Empty //or whatever default value your want; Problem : it is failing because you are assigning the Integer type into String. here you need to use explicit conversion to convert the Integer type into String type. Solution : if you want to check wether contact number can be parsed to int or not before assigning it into TextBox use TryParse method int contact; if(int.TryParse(Session["sContactNumber"],out contact)) LabelContactNumber.Text = contact.ToString(); else LabelContactNumber.Text = "Invalid Contact!"; int contactNumber = -1; if( int.TryParse( Session[ "sContactNumber" ], out contactNumber ) == false ) { LastContactNumber = "N/A"; } else { LastContactNumber = contactNumber.ToString( ); }
common-pile/stackexchange_filtered
How to generate a .elf file with keil v5.30 to simulate in proteus how are you?. I'm looking for how to generate a .elf file with keil v5.30 to simulate in Proteus and being able to se the source code while the simulation is running but I can't find nothing, I'm simulating a stm32f103c6 and I think the compiler is ARMCC but not shure. If not possible then is possible to generate the .elf file with another tool from keil or with the ouput files of keil?. Thanks in advance for the help. for me it has, that why I'm asking, otherwise I wouldn't be asking. Please people, If you don't have any constructive to say then don't say anything. To say something not helpful is not giving you adittionall points or reputation. then do not post on the public forum. In adittion, If simulate doesn't have any sense then why so many people in the world tooks the effort to do simulators of electronics, civil construction, rockets, sattellites, etc. Then ask yourself why several big enterprise spends lots of money buying simulators (specially airways companies).I forgot, Spacial agencies train their crews in "simulators", why they do that if it "does not make sense"...I don't know, may be they are all mistaken -I'm being sarcastic if you didn't noted-.
common-pile/stackexchange_filtered
cant figure out how to fix the bug Using JAVA I am trying to sort and array of integers (ascending) by radix sort but dont seem to work out the bug. public class Ex_radix { public static void radixSort(int[] A) { int d = 0; for (int digit = 0; digit < A.length; digit++) {// Checks what is the // maximum amount of // digits in any number int num = A[digit]; int counter = 0; while (num != 0) { num = num / 10; counter = counter + 1; } if (counter > d) { d = counter; } } System.out.println("this is the max number of digits: " + d); int[] B = new int[A.length];// Copying the array for (int j = 0; j < A.length; j++) { B[j] = A[j]; System.out.println("this is cell " + j + ": " + B[j]); } int iteration = 1;//Starting sort while (iteration <= d) { for (int i = 1; i < B.length; i++) { if (B[i] % (10 ^ iteration) < B[i - 1] % (10 ^ iteration)) { int temp = A[i - 1]; B[i - 1] = B[i]; B[i] = temp; } } for (int i = 0; i < B.length; i++) {// Checking System.out.print(B[i] + ", "); } System.out.println(); iteration = iteration + 1; } } public static void main(String[] args) { int[] C = { 329, 457, 657, 839, 436, 720, 355 }; radixSort(C); } } if you run it you see it starts fine but within the first iteration and the next ones numbers gets copied. I tried several methods but coudlnt figure it out. first iteratiom: 457, 657, 839, 436, 839, 355, 720, second iteration: 457, 657, 436, 657, 355, 720, 720, third iteration: 657, 436, 657, 657, 720, 720, 720, ^ is not exponentiation. You could use Math.pow, but I'd keep another variable powerOf10 that holds "10 to the iteration power". Then when you add 1 to iteration, I'll bet you can guess what to do with powerOf10. right. i fixed that, stupid of me. but it still does not solve the problem. im still getting coppied numbers. The reason you're getting the duplication is this: int temp = A[i - 1]; B[i - 1] = B[i]; B[i] = temp; You're getting temp from A and setting it to B. This will stop the duplication, but it won't fix your sort. Radix sort uses buckets to determine sort order (that's the reason for the 2nd array), there's no comparing with each other. You're doing a kind of modified swap.
common-pile/stackexchange_filtered
How to call a method with a parameter decorated with @Vaule annotation in a spring project? When there is a parameter decorated with @Value annotaion in a method, it is ofcourse no compile error. Just like the code bellow: public void Sample0(@Value("${hmac.key}") Optional<String> key) { if (key.isPresent()) { System.out.println(key.get()); } else { System.out.println("can not find key"); } } My Question is how to call a function like this? I try to call it directory, but it failed. The calling function code bellow. @Test public void sampleTest0() { JwtService.Sample0(); } So anyone can tell me what's the right way to call the function? Thx. what are you trying achieve? @Deadpool I just want to test the varied usages of the Value annotation. I think another way of doing this is to save @Value as local variable and then use it into function. I think you can use @Value in parameters only in constructors. Your Sample0 is not a constructor, just a regular method because it has a return type, i.e. void. If you use @Value in constructor parameter, you can autowire Sample0 and spring will inject the value while instantiating it. If you need to pass a value to a regular method instead, you can use @Value on a field in the calling class and then pass that field as an argument to this method in Sample0.
common-pile/stackexchange_filtered
How to hide source code from public view How to hide source code from public view in php, asp.net and with javascript. I have seen many CMS and other website that source is hidden from public view, like wordpress config.php, whmcs configuration.php, and more files are hidden, but inside it have code but when we check in browser view source it display none. How to do like this in php and asp.net or with javascript. I found this article here Source Code Padding Really, the oldest trick in the book. It involves adding a ton of white space before the start of your code so that the view source menu appears blank. However, must all people will notice the scroll bars and will scroll around to find your code. As pointless and silly as this method is, there are some still who use it. No Right Click Scripts These scripts stop users from right-clicking, where the "View Source" function is located. Cons: Notoriously hard to get working across browsers and to actually work properly. The right-click menu, or context menu, includes many helpful tools for users, including navigation buttons and the "Bookmark Page" button. Most users don't take kindly to having their browser functionality disabled and are inclined not to revisit such pages. The View Source function is also available through the top Menu. At the main menu bar at the top of your browser, select View, and then in the sub-menu, you'll see "View Source" or something similar. Also, there are keyboard shortcuts like Ctrl+U that can be used to view source. All this method does is add about a two second delay to someone trying to view your source and it does irritate users who aren't trying to view your source. "JavaScript Encryption" This is by far the most popular way to try to hide one's source code. It involves taking your code, using a custom made function to "encrypt" it somehow, and then putting it in an HTML file along with a function that will decrypt it for the browser. A User is able to view the source, however, it isn't understandable. Cons: Your website is only usable for users with JavaScript enabled. This rules out search engines, users who've chosen to disable JavaScript, and users using a textual browser (such as the blind) that doesn't have JavaScript capabilities. Remember, JavaScript is a luxury, not a necessity on the web. You have to include a means of decrypting the page so the browser can display it. Someone who understands JavaScript can easily decrypt the page. Many browsers provide alternative ways around this. Some allow you to save the page, decrypted for easy viewing later. Others, like FireFox, include tools like the DOM Inspector, which allows you to easily view and copy the XML of the page, decrypted. HTML Protection Software There are some less than honest people who want to sell you software to quickly and conveniently "protect" your source code. This type of software generally employs the above methods, in varying ways, to hide your source code. Many people think that if they are buying it, it must work. It doesn't. As we've seen, the above methods are all easily circumvented, and all this software does is implement these horribly flawed methods for you and take your money. Don't fall for them, I've yet to see a single one that's worked, and they never will. Isn't there Any Hope? The bottom line is that browsers need to see the unencrypted, plain text source code to create a webpage. For that reason, it's impossible to hide your HTML source code. If the browser can read it, which it needs to be able to do to render a webpage, then so can a user. That's the bottom line. But My Page Was Stolen! A lot of people look for this after having their website pirated. I know it's cruel that in a few minutes someone can steal hours of your work, but hiding your source code can't help you. Contacting the person in question and asking them to take it down solves many cases. Otherwise, contact the web host or the person's ISP and explaining the situation is a good course of action. I can't give you legal advice, but if you feel that your copyrights are being infringed, you can contact a lawyer. But hiding (or "encrypting") your source, won't do much of anything at all. The Bottom Line Unfortunately, the short answer to this question is, you can't. There have been various methods put forth, but all of these are easily circumvented. In the end, the only sure fire way to make sure no one can steal your source code is to never put it on the Internet at all. Credits: http://www.htmlgoodies.com/beyond/article.php/3875651/Web-Developer-Class-How-to-Hide-your-Source-Code.htm Good article, but it does not contain more details. If you want to hide the code from view source. You should put the code into external files.Make external JavaScript file with .js ext. And link into in your web page But it also get visible by user that js file, and they open js file and read all source code. i need to hide asp.net, JavaScript and php language Use minify js plugins which will Compressed javascript files But what about the php and asp.net code, how wordpress and other CMS are hiding ?? They are using config file & include the config file where you want. Config file code hidden on that page. if i encrypt my javascript it automatic getting decrypt on front view of browser, and it visible to see
common-pile/stackexchange_filtered
VueJS - how to delay data item updating? Not sure how to title this question, but here's my situation: I have an array of objects. Among other fields, the objects have a date_beginning and a date_ending field. In presenting my array of objects, I break them into two groups -- first group has a value in only the date_beginning while the second group has a value in both the date_beginning and the date_ending fields. Something like: // Only date_beginning present Object 1 Object 2 Object 3 // Has both date_beginning and date_ending Object 4 Object 5 Object 6 Object 7 Now, I have an Edit button on each array item that, when clicked, will present a form for the user to edit both dates. The user edits the dates, then hits SAVE and the app will issue a PATCH request to the backend server to update the record in the database. Here's my problem: If a user enters a date in the date_ending in any object in the first group, as soon as the user finishes entering the date, the object is immediately moved to the second list. I understand this is VueJS "doing its job". But, the problem this creates is that the user hasn't had a chance to click "Save" which means it hasn't been saved to the backend, and further the object they just edited is now in a different list, so they have to go find it again to continue editing the object and to click Save. Hopefully that makes sense. So I'm trying to figure out a better way to somehow delay the update to the object itself, or hide this update from VueJS somehow so that the object doesn't get auto-sorted into the second list. Any ideas? Don't update the object that is being rendered until you get the response back from the server. This may mean when you are editing the object you need to make a copy of the original. @Bert is right, update the object only after the ajax call succeeds, else don't update the object. @Bert So only when the user clicks "Edit" then make a copy of the object, and put that copy into the v-model of all the form inputs. After clicking "Save" and getting a success response, then copy that copy back to the object within the data section of the component? It depends. If your component actually performs the patch, then you can use v-model on the component and only emit changes on success (v-model works by listening for the input event). @Bert Yes, the component performs the patch. However, the object in question is passed to the component via props. So I can delay the emitting of the update on success of the patch request? So the object itself won't be auto-moved to the second list (as described in my question) until after I've received the success response back from the server? I'll have to look into how to do that, didn't know that was possible. Here is an example of a component that does what I mention in the comments above. Vue.component("edit-dates", { props: ["value"], template:` <div> <input v-model="internalDates.date_beginning" type="date"> <input v-model="internalDates.date_ending" type="date"> <br> <button @click="save">Save</button> <div> `, data(){ return { internalDates: Object.assign({}, this.value) } }, watch:{ value(newVal){ this.internalDates = Object.assign({}, newVal)} }, methods:{ save(){ // simulate an ajax patch setTimeout(() => { this.$emit('input', this.internalDates) }, 1000) } } }) This component implements support for v-model. When the value is passed in, a copy of that object is created. Important note: Object.assign does a shallow copy, so if you have a deeper nested object, you will need to use a method for copying the object that works for deeply nested objects. Also, whenever the value is updated, a copy is made. Since the component is working off a copy of the data, the component can choose when to $emit the updated value. In the above example, an ajax call is simulated with setTimeout and the update is only emitted when the time has elapsed. Here is a codepen demonstrating the component. Nice, I'll give this a try and see if it will address my situation. Thanks
common-pile/stackexchange_filtered
What does "while" mean in the following sentence? What does while mean in the following sentence? Is this the same as "while I like blue, Henry likes red"? The Border Defense Cooperation Agreement would be aimed at avoiding armed conflict while the actual lines of the border are agreed to. No, in this case it means "at the same time as" or "during the time that". Your example has more the meaning of "although".
common-pile/stackexchange_filtered