text
stringlengths
70
452k
dataset
stringclasses
2 values
Message relay for JSON data in wso2ESB I am trying to build a simple POC using wso2ESB. I've created a simple pass through proxy service with an Alfresco service http://www.alfresco.com/ The problem is I am not getting the full JSON data. I've read it has something to do with the axis2-JSON and that it causes problems when one has JSONArray in the root. So I've decided to use message relay. WSO2 ESB Unable to convert complete JSON data to XML I've edited the axis2.xml as described in the documentation thus adding the following lines <messageFormatter contentType="application/json" class="org.wso2.carbon.relay.ExpandingMessageFormatter"/> and <messageBuilder contentType="application/xml" class="org.apache.axis2.builder.ApplicationXMLBuilder"/> But after I've restarted the server when I try to use the proxy server through the firefox REST plugin the ESB throws the following exception [2012-07-12 10:02:29,125] WARN - ClientWorker Unexpected response received. HTTP response co de : 405 HTTP status : Method Not Allowed exception : SOAP message MUST NOT contain a Documen t Type Declaration(DTD) [2012-07-12 10:02:29,125] ERROR - NativeWorkerPool Uncaught exception java.lang.ClassCastException: org.apache.axiom.om.impl.llom.OMTextImpl cannot be cast to org. apache.axiom.om.OMElement at org.apache.synapse.util.MessageHelper.cloneSOAPFault(MessageHelper.java:441) at org.apache.synapse.util.MessageHelper.cloneSOAPEnvelope(MessageHelper.java:254) at org.apache.synapse.core.axis2.SOAPUtils.convertSOAP11toSOAP12(SOAPUtils.java:95) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.handleMessage(SynapseCallbac kReceiver.java:323) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.receive(SynapseCallbackRecei ver.java:160) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181) at org.apache.synapse.transport.nhttp.ClientWorker.run(ClientWorker.java:275) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.ja va:173) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886 ) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) What causes this? Is the problem that ESB still tries to convert the JSON object instead of trying to relay it? Is there another workaround in parsing these JSON objects (i.e. adding artificial root to the JSON object?) at the builders you need to set the application/json to use org.wso2.carbon.relay.BinaryRelayBuilder as well.
common-pile/stackexchange_filtered
Slow WMI request on Windows 2008R2 Has anyone got any suggestions to speed up this WMI query? I'm updating a client application every 5 seconds to show the CPU stats. It was much quicker on Windows 2003 but takes at least 5 seconds to return an integer for 4 CPU cores: Private Sub GetProcessorIdleTime(ByVal Server As String) Dim searcher As New ManagementObjectSearcher("\\" & Server & "\root\CIMV2", "SELECT LoadPercentage FROM Win32_Processor") Dim collection As ManagementObjectCollection = searcher.[Get]() For Each row In collection TextBox1.Text = TextBox1.Text & vbCrLf & Convert.ToInt32(row("LoadPercentage")) Next End Sub Or is there a better way to retrive this information remotely? To improve the performance, you must re-use the WMI connection to the remote server, establishing a connection is one of the more expensive tasks when you execute a WQL sentence. In your code you are setting a new WMI remote connection each time. So rewrite your code creating a new method to establish the remote connection and then reuse (share) the ManagementObjectSearcher object in your GetProcessorIdleTime method.
common-pile/stackexchange_filtered
How to avoid negative solutions from sympy.solve? I am having the very same problem asked in this question, but I can't figure out why the solution is not working. In that question, there was an issue in sqrt function that seems to be solved, and now that problem leads to only positive results. But in my problem, I can't eliminate the negative solution in the following code: import sympy v,Vs,Vp = sympy.symbols('v,Vs,Vp',real=True,positive=True) sympy.solve( v - (Vp**2-2*Vs**2)/(2*(Vp**2-Vs**2)), Vs) Which gives me the result [-sqrt(2)*Vp*sqrt((2*v - 1)/(v - 1))/2, sqrt(2)*Vp*sqrt((2*v - 1)/(v - 1))/2] How can I get only the positive result? What am I missing? The response says that anything can be included; thus, you would have to manually filter them out. Have you tried it yet? Yes but, as I said above, the response in that question opened an issue in sympy's github (in sqrt function) that seems to be solved. Today, if you try that command you won't get negative values anymore, not needing to filter the results. But in my problem that doesn't happen. The difference between that question and this one is that your solution has v - 1 in the denominator so the solution is not known to be real or complex (i.e. what if v=1?). The positive solution might not be positive e.g. if v = 0.75 it is imaginary. If you know that v > 1 then you can use a substitution v -> 1 + u where u is declared positive. @OscarBenjamin, thanks! Actually I know that 0<v<0.5. Is there a way to make this assumption on the symbols function? There isn't a good way to assume inequalities in the assumptions system but for your case v -> Rational(1, 2) - u will work. As the comments in the thread already describe, it is not really possible to get what you want in general. There is a trick to assume 0 < v < 1/2. Since this involves a few fractions, intuition says that we should probably make a substitution that involves a fraction too. import sympy Vs,Vp = sympy.symbols('Vs,Vp', positive=True) # A hack to assume 0 < v < 1/2 u = sympy.symbols('u', positive=True) v = 1/(u+2) # Alternatives like atan can be used when there are trig functions sol = sympy.solve( v - (Vp**2-2*Vs**2)/(2*(Vp**2-Vs**2)), Vs) print(sol) # Substitute back by redefining v v = sympy.symbols('v', positive=True) new_sol = [subsol.subs(u, 1/v - 2).simplify() for subsol in sol] print(new_sol) The next best you can do in this case is assume all square roots are positive which is a very brave assumption. import sympy v,Vs,Vp = sympy.symbols('v,Vs,Vp', real=True, positive=True) sol = sympy.solve( v - (Vp**2-2*Vs**2)/(2*(Vp**2-Vs**2)), Vs) # Assume sqrts are positive and sol is an array # Both of these are not true in general # It does not work if we assume the square root can be zero # Or even complex or negative s = sympy.symbols('s', positive=True) # Represents any square root w = sympy.Wild('w') # Represents any argument inside a square root new_sol = [subsol for subsol in sol if subsol.replace(sympy.sqrt(w), s) > 0] print(new_sol) Both code blocks assume sol is an array which is not true in general when it comes to solve.
common-pile/stackexchange_filtered
Sitecore CM and CD in the same server We have a requirement to have the CM and CD in the same server. But while we are trying to access the CD URL as www.xyz.com/sitecore we are landing to the sitecore admin page. Is there a way to deny access to the admin page with CD url. I assume that with "same server" you are talking about the same instance (otherwise you just need to apply the hardering setup). In this case, a possible solution could be to use the IIS rewrite module to set redirects on the folders you want to deny on the CD url. Put a redirect on /sitecore/admin, /sitecore/debug, /sitecore/login, /sitecore/shell/WebService and all their children to any path you want (e.g. your homepage) Edit: as Jose mentioned: this approach does require 2 domain names to make a distinction between CM and CD. Best practice would be to make the CM not publicly available. ps: don't do this for the entire /sitecore folder.. that would break your CD. Needs to assign 2 domains to the site so can be accessed from CM Sitecore will still run all the CM pipelines on the CD URL. So if you put ?sc_mode=edit on the URL for example then you'll have issues. To fix that, you'll need to have another site on the config with enableWebEdit=false etc Go to IIS. Select Admin folder under the Sitecore folder. In Feature View, Double click on Authentication. Select Anonymous Authentication and click Disable. You can also deny access to the sitecore folder in the web.config, but keep in mind that some directories should be accessable: <!-- Deny users access to internal paths --> <location path="sitecore" xdt:Transform="Insert"> <system.web> <authorization> <deny users="*"/> </authorization> </system.web> </location> <location path="sitecore modules" xdt:Transform="Insert"> <system.web> <authorization> <deny users="*"/> </authorization> </system.web> </location> <location path="sitecore/service" xdt:Transform="Insert"> <system.web> <authorization> <allow users="*"/> <!--heartbeat, keepalive, ect. must be accessible--> </authorization> </system.web> </location> <location path="sitecore/shell/Webservice/Service.asmx" xdt:Transform="Insert"> <system.web> <authorization> <allow users="*"/> <!--allow webservice--> </authorization> </system.web> </location> <location path="sitecore modules/Web/Web Forms for Marketers/mvc" xdt:Transform="Insert"> <system.web> <authorization> <allow users="*"/> <!--allow WFFM Assets --> </authorization> </system.web> </location> As you can see we use XML-Transformation to do that on CD-Server config only. Best regards Dirk
common-pile/stackexchange_filtered
Reading out put of previous command in bat command file I am very new to batch programming, I am trying to write a batch file that is a fake virus. I need to obtain the IP address from the previous command IPCONFIG into the variable VarIP. Can you help me? My code: echo off echo Trying to hack your computer ipconfig echo Now hacking your IP ping -t VarIP echo on pause Another Version without "Tokens" for NT : setlocal enabledelayedexpansion for /f "delims=" %%a in ('ipconfig ^| find /i "IPv4 Address"') do (set VarIP=!%%a%!) ping -t %VarIP% It's pretty simple to extract part of the output from any console command by using find to eliminate the lines in the output that you do not want, then using the for command to extract a portion of the line found by find: @echo off setlocal ENABLEDELAYEDEXPANSION for /f "tokens=2 delims=:" %%i in ('ipconfig ^| find /i "IPv4 Address"') do (set VarIP=%%i&set VarIP=!VarIP: =!) ping -t !VarIP! endlocal Hopefully you are just creating a practical joke on a friend and aren't up to anything more nefarious. This is a useful method to get IP info: @echo off for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get IPAddress /value | find "I" "') do echo IPv4 %%~a IPV6 %%~b pause
common-pile/stackexchange_filtered
Turning off hostnamelookup in a shared hosting I have a linux shared hosting account with cpanel for a drupal website. While optimizing the site (with the help of information from tools.pingdom.com), I found considerable waiting time of about 400-500 ms. Somehow, I found out about 'hostnamelookup'. But I am not able to figure out how to turn it off in a shared hosting account (as we cannot change the .conf file of server). Can this be done in .htaccess ?. Thank you. No, it can't be set in htaccess context. So is there any other way of doing it in a shared hosting ? You should ask your hosting provider. Shared hosting usually means that global settings cannot be changed. 400-500 ms lost in that? to resolve your domain name?
common-pile/stackexchange_filtered
Arranged/ordered checkbox for a one-to-many relationship in CoreData In Xcode's data model inspector, when a relationship is selected, there is checkbox a between labels "Arranged" and "Ordered". CoreData works with sets, so what exactly does it mean in this context? iOS 5 and later allows to have ordered to-many relationships. We've been using Core Data for a while and this is a much needed addition (as we have to support iOS 4, we're still stuck with adding a second number column for 'sortPosition'). Try turning it on, create a subclass and see what kind of code it generates for you. I suspect an NSArray, but haven't tried myself yet. It generates properties using NSOrderedSet and also generates some more helper methods to do things like insert items at specific indices - but I'm trying to figure out how to specify the sort descriptors to use when you access it by the property; If you have to make a separate fetch-request then it seems fairly pointless.
common-pile/stackexchange_filtered
Split a list in two and preserve order How do you efficiently split a list in 2, preserving the order of the elements? Here's an example of input and expected output [] should produce ([],[]) [1;] can produce ([1;], []) or ([], [1;]) [1;2;3;4;] should produce ([1; 2;], [3; 4;]) [1;2;3;4;5;] can produce ([1;2;3;], [4;5;]) or ([1;2;], [3;4;5;]) I tried a few things but I'm unsure which is the most efficient... Maybe there is a solution out there that I'm missing completely(calls to C code don't count). My first attempt was to use List's partition function with a ref to 1/2 the length of the list. This works but you walk through the whole list when you only need to cover half. let split_list2 l = let len = ref ((List.length l) / 2) in List.partition (fun _ -> if !len = 0 then false else (len := !len - 1; true)) l My next attempt was to use a accumulator and then reverse it. This only walks through half the list but I call reverse to correct the order of the accumulator. let split_list4 l = let len = List.length l in let rec split_list4_aux ln acc lst = if ln < 1 then (List.rev acc, lst) else match lst with | [] -> failwith "Invalid split" | hd::tl -> split_list4_aux (ln - 1) (hd::acc) tl in split_list4_aux (len / 2) [] l My final attempt used function closures for the accumulator and it works but I have no idea how efficient closures are. let split_list3 l = let len = List.length l in let rec split_list3_aux ln func lst = if ln < 1 then (func [], lst) else match lst with | hd::tl -> split_list3_aux (ln - 1) (fun t -> func (hd::t)) tl | _ -> failwith "Invalid split" in split_list3_aux (len / 2) (fun t -> t) l So is there a standard way to split a list in OCaml(preserving element order) that's most efficient? What do you mean by "efficient"? Space efficient or time efficient? I'd like to see time efficient. You need to traverse the whole list for all of your solutions. The List.length function traverses the whole list. But it's true that your later solutions re-use the tail of the original list rather than constructing a new list. It is difficult to say how fast any given bit of code is going to be just by inspection. Generally it's good enough to think in aysmptotic O(f(n)) terms, then work on slow functions in detail through timing tests (of realistic data). All of your answers look to be O(n), which is the best you can do since you clearly need to know the length of the list to get the answer. Your split_list2 and split_list3 solutions look pretty complicated to me, so I would expect (intuitively) them to be slower. A closure is a fairly complicated data structure containing a function and the environment of accessible variables. So it's problaby not all that fast to construct one. Your split_list4 solution is what I would code up myself. If you really care about timings you should time your solutions on some long lists. Keep in mind that you might get different timings on different systems. Couldn't give up this question. I had to find a way that I could walk through this list one time to create a split with order preserved.. How about this? let split lst = let cnt = ref 0 in let acc = ref ([], []) in let rec split_aux c l = match l with | [] -> cnt := (c / 2) | hd::tl -> ( split_aux (c + 1) tl; let (f, s) = (!acc) in if c < (!cnt) then acc := ((hd::f), s) else acc := (f, hd::s) ) in split_aux 0 lst; !acc Late answer, but offered as an option: solve this by reversing the list and then converting both the original and the reversed to sequences and taking the appropriate number of elements from each sequence. We can then reverse the elements taken from the reversed list and put them in a tuple. Optimization: List.length and List.rev each require a complete traversal of the list. We can use List.fold_left to give us both in just one traversal. let split_in_half lst = let (len, rev) = List.fold_left (fun (l, r) x -> (l+1, x::r)) (0, []) lst in let half_len = float_of_int len /. 2. in let first_half = lst |> List.to_seq |> Seq.take (half_len |> Float.ceil |> int_of_float) |> List.of_seq in let second_half = rev |> List.to_seq |> Seq.take (half_len |> Float.floor |> int_of_float) |> List.of_seq |> List.rev in (first_half, second_half)
common-pile/stackexchange_filtered
CORS: what's the purpose of Simple Request? From Mozilla's documentation, there are three CORS scenarios: Simple requests Preflighted request Request with credentials Simple Requests has some disadvantages, for example, when the client declares withCredentials, even though the server refuses, the HTTP request with the cookie has been sent, which could be an attack. The Preflighted request is much safer, and could cover all kinds of scenarios. Why people invent Simple Requests, even though pre-flighted requests could meet all requirements? Reference What exactly does the Access-Control-Allow-Credentials header do? The simple explanation is that 'Simple requests' came before CORS existed. XMLHTTPRequest only allowed requests to same origin, or requests to different origins if that request did not introduce security issues that did not already exist. For example, it's possible to do a POST request via a HTML <form> to a different origin, but you can't programmatically read the response. So given that this was already possible, it made sense that that restriction also did not exist in XMLHTTPRequest. Years later, when CORS came along it was important that backwards compatibility for those old cross-origin requests was not broken. If suddenly those requests also required CORS headers, it would break scripts that depended on it. I wrote more about this topic, CORS and no-cors here: https://evertpot.com/no-cors/ for additional background.
common-pile/stackexchange_filtered
JQuery Select Multiple Divs with Dropdown Long time browser, first time poster. What I'd like to do is have a user select the number of weeks to display in a dropdown menu, and then reveal that many divs. Right now I have it setup where I can reveal one div or all, but I'd like to do it for the previous divs. Right now I have: <SELECT name="number_of_weeks" id="number_of_weeks"> <OPTION value = "week1">1</OPTION> <OPTION value = "week2">2</OPTION> <OPTION value = "week3">3</OPTION> </SELECT> <div id = "week1" class = "weekmenu"> Week 1 </br> </div> <div id = "week2" class = "weekmenu"> Week 2 </br> </div> <div id = "week3" class = "weekmenu"> Week 3 </br> </div> And for the javascript: $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); $('#'+$(this).val()).show(); }); }); The output should be something like this: If week1 is selected only the week1 div is shown. If week 2 is selected, both the week1 and week2 divs are shown. If week 3 is selected the week1, week2, and week3 divs are shown. I've been banging my head over this...I tried creating some nested divs but it didn't work out quite right. I also tried to give multiple divs their own classes, and then try to show those. JSFiddle: http://jsfiddle.net/meRcr/21/ Any help is appreciated! Welcome to SO, officially. =] Just change the last line of jQuery to: $('#' + $(this).val()).prevUntil('select').addBack().show(); jsFiddle example Full code: $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); $('#' + $(this).val()).prevUntil('select').addBack().show(); }); }); Try this:- $('#' + $(this).val()).prevAll('.weekmenu').andSelf().show(); is the key. .prevAll() will get you all the preceding siblings matching the selector .weekmenu and then include itself too using andSelf() to the collection. $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); $('#' + $(this).val()).prevAll('.weekmenu').andSelf().show(); }); }); Fiddle This also works wonders! I wish I could give two right answers! Maybe this is more correct because it would fit more folk's situations.. Try something like this, I didn't test it but I think it works:) $(document).ready(function () { $('.weekmenu').hide(); $('#week1').show(); $('#number_of_weeks').change(function () { $('.weekmenu').hide(); var weekNumbers = $(this).val(); for(var i = 1; i<= weekNumbers; i++) { $('#week' + i).show(); } }); }); Use a cascading approach. Have a child-parent relationship through data-* attributes. On each div, have its previous divs id in the attribute. data-parentid="2". Then you can just keep chaining your functionality until you get to a div with no parentid. You can change your layout anyway you choose and this relationship will be intact.
common-pile/stackexchange_filtered
Rails ActiveRecord, selecting distinct fields from a joined table and returning all the models I am working on a Rails app with MySQL. I have a tables like this: gifts id, basket_id, orange_id, berry_id berries id, action_id, name These are their models: class Gift < ActiveRecord::Base belongs_to :basket belongs_to :orange belongs_to :berry ... end class Berry < ActiveRecord::Base belongs_to :action has_one :gift ... end class Basket < ActiveRecord::Base has_many :gifts ... end In the Basket model, I have gifts variable that contains all the gifts for this basket, through the association I defined in the Basket model - basically "SELECT * FROM gifts WHERE basket_id = ?", self.id I want to group all the unique berry actions for each orange. Current approach: def get_data data = {} gifts.each |gift| do orange_id = gift.orange_id data[orange_id] ||= { :basket_id => gift.basket_id, :name => gift.orange.name, :actions => Set.new } data[orange_id] << { :action_name => gift.berry.action.name } end return data My approach was to iterate through gifts and save unique berry actions into a Set for each unique orange_id, however this approach is slow if I have thousands of gifts with multiple berry actions for each berry. If there are 2000 gifts and 4 actions, then I am looping 8000 times. Gifts can have the same oranges and baskets, but always different berries. I want to perform this query instead, which will be faster as I will be iterating through unique oranges instead of all the gifts (for each basket there a couple hundred oranges only). SELECT DISTINCT g.basket_id, g.orange_id, g.berry_id, b.action_id FROM gifts AS g JOIN berries AS b ON g.berry_id = b.id Can someone show me how to do this using Rails ActiveRecord methods? I would like to be able to iterate through each row of this query and perform actions on the fields I selected. It would also be great if the associated models can be returned as well, such that I can grab the basket, orange, berry, and action model for each row. Try the following: gifts = Gift.joins(:berry).select(:basket_id, :orange_id, :berry_id, :action_id).uniq.to_a gifts will hold an array of gifts with only the attributes specified in select initializated: puts gifts.first.attributes
common-pile/stackexchange_filtered
When would you prefer a custom/skinned user interface in a desktop application? I'm working on an application whose UI is skin-based, but it looks a little bit old (its graphics were designed more than 5 yeas ago). It's not clear to me whether we should consider a redesign or get rid of the skin and go with the OS default UI (in this case, Windows XP). I would like to know what facts/reasons/questions can be of interest in order to make a decision. Let me start with the some questions I find important: Do other applications in your sector use skinned UIs? Is the usability of the application improved by using a custom skin? I've seen these applications for skinning: Distributor/Customer Branding Feelgood applications Bobify Portability Distributor Branding gives the final user familiar names and looks - e.g. for support we use a remote desktop access tool that is branded with our name and logo. This makes the tool better integrate with our software, and the customer knows "he's dealing with us". It's the difference between "to get support for AceMe Works, run the AceMe Remote Support utility" and "to get support for AceMe Works, run the Fundunga Sambaga Conneculator, and enter AceMe-5647895324 in the Provider field". Distributor Branding is rather simple to achieve from a implementation POV: Don't show your name everywhere Make room for the brander's (advanced) set defaults, and allow to hide settings Something simple like reading the window title and a custom HTML / .png to be displayed from an .ini file is often enough. You can - and are encouraged to - stick to a OS/envirnoment standard UI. In addition, you are often expected to set defaults and limit some options - either from being changed, or being displayed at all. Feelgood Skins - this is what usually receives techie hate. This is the realm of media players etc., often in a commodity market, where establishing an emotional, personal connection between user and product is one of the few competetive edges you can have. I'd avoid it in any other case. Fundamental problem: it's often hard - or a lot of extra work - to provide a "OS default skin" that actually works like an OS default. Might also be considered a "toy" by a commercial customer. The following applications don't need separate skins per se, but still a skinning framework with a fixed skin is a straightforward technical choice: Bobify - you provide a skinnable interface, because you want to be deliberately simpler than the OS default. There are targets even beyond the "kids & special needs" market. One thing could be a process that's normally perceived as complicated, or niche application of a complex, more powerful tool. Fundamental problem: You are locked into Microsoft Bob mode. You create an additional barrier for your users to get used to a "full" interface. Portability - you value consistent UI across platforms more than platform-compatible UI. I'd argue that's rarely a good idea, except maybe in combination with a simplified UI, as above, or a very loosely defined platform (such as the early www). Again, you don't need separate skins Thank you peter, I'm accepting your answer because it tries to formalize the purpose of creating a custom UI and that's very useful for answering my question. There isn't a single skinned application I didn't end up hating. Seriously, the skins I've seen are there purely to make the application look "richer" than a normal Windows application and ends up doing nothing more than suck up memory and CPU in order to look like a pig with lipstick on and eventually fail with paint issues. I loathe skinned applications because all the normal UI I'm used to using has been hidden from me and it takes me longer to figure out where the menu is and which is the default button and whether I might have a pop-up menu available. ditto - but still, if the market demands it.... +1 Most skins are usally gaudy and distracting. They interfere with usability while ruining the carefully-balanced aesthetics that most modern OSes have in their UI. Individual skinnable apps also make it more difficult for users to customize their desktop. Now, instead of selecting/creating a single system theme that's consistently applied everywhere, they have to deal with dozens of separate skins that destroy any cohesion in the UI. Not to mention some of the slowest loading apps on my computer are Logitech and ATI's skinned driver utilities. The issue isn't skinning so much as it is skinning badly or for the wrong reasons. Apple has taken that approach with varying success. If it makes sense for the application, do it. If it adds value, do it. If it's just decoration, definitely skip it. I agree with DA01, this question is about trying to figure out what considerations you should take into account before skinning your application... In any case, thank you for your answer! Google Chrome is fine... The usability of an application shouldn't really be affected by the skin applied. If options are hard to find/use with the default UI skin then you've got problems with your application. If you competitors support custom skins then having the same for your application is probably seen as important for marketing reasons. You don't want your sales hit because you don't tick a box that your competitor's do, even if it's for something that your users might not have considered in the first place. As Lèse majesté points out trying to match your competitors feature for feature is probably not a good idea, but you may have to match some features just to make sure you can get your "foot in the door" with clients. One advantage of just using the default OS UI is that when a new version of the OS comes out your application will just fit right in. It might not use all the latest bells and whistles (Windows Aero) but the basics will be covered in terms of button placement and size, window animations etc. This will go a long way to making your application look professional. In terms of customisation you might want to consider just limiting it to colour schemes - if you are targeting corporations you can then just change the scheme to match their corporate colours, but the overall look and feel is the same for everyone. In "Designing the Obvious", Hoekman argues that trying to match competitors feature-for-feature is a losing proposition. A better approach is to focus on the 20% of the features that 80% of users will use, and make that 20% very good and very intuitive. In most apps, skins/themes probably fall outside of the 20% that most people use. @Lèse majesté - I did say it was for "marketing reasons". I'll clarify the answer. Thank you for your answer, there's a lot of insight in it. One advantage could be to increase interest in the application by creating a user community around UI skinning. There are communities around skinning both WoW and Winamp, which are seen as good examples of custom/skinned user interfaces. The skinning is mainly around app specific controls and layout rather then replacing OS UI. The customization allows users to specifically target the look of the application for their use, eg: WoW UI for specific character class. Thank you for relating both questions. That was the idea in the beginning. Users like skinnable user interfaces because they find them fun. At our small office (4 other people), two employees use custom skins on their Firefox browser. One is a huge Lakers fan, the other is quite an artsy person; the Firefox skins fully reflect that. IMO, skinnable user interfaces are OK up to a point. Some apps cross the line from providing fun skinnable UIs and let users become pseudo UI designers, allowing them to move the location of buttons and various UI elements, relabeling them, and so forth. I wouldn't want to be the tech support person on the other end of the phone/email/forum line. Hey, I'm starting a new project that is doing just that. First to answer your questions: No, other products in our space don't support theming. Not necessarily. Our reasons fit into some of peterchen's answer, but I'll go a little deeper. My company is in a large, but still niche market. Our user interfaces have traditionally fit in the line of business category, which means feature/functionality over attractiveness and usability. In the last decade more competitors have appeared building newer user interfaces that are closer to consumer applications. So, why a themed UI: Appearance sells. I've seen even technical managers be excited about animations and other non-functional features. Customers like demos when their logos or color schemes are shown. Partner branding - Partners, resellers and VARs like their name stamped over as many parts of their solution as possible. We have a multiple products that address multiple markets. Being able to change look and feel gives us the ability to make the bits and pieces fit into existing markets without looking like a horrible bolt-on. In sales speak terms, easier cross selling opportunities. The product can appear to iterate/improve faster through cosmetic changes As for usability, in every rewrite you get a chance at doing it better. Ignoring the items above, most of our day to day users need to go from novice to expert in a few months. Once they achieve that, they need to navigate quickly to find what they need. Old-style green screen or dos interfaces that work quickly and provide rich sets in many cases, might actually be a more usable project. But, few want that including the users themselves. We've been sold on a sexy graphics style world where usability is a term thrown around to explain it, but where usability isn't the focus. I'm not suggesting you can't make an unusable or poorly thought out product, but too many people equate cool and different with usability. Jim, thank you for sharing your personal experience and relate it with peterchen's. If you have a business product you will encounter requirements from customers who want to customize the "skin" according to non functional corporate guidelines. So if it costs less money to customize it that will increase the likehood that the application is choosen (one extra checkmark). One application in particular, Wordpress needs to have skinning as a first class citizen. Other than that, I have never really seen the benefits of Winamp-style skins. Something like twitter or MySpace needs customization, but binary software skins seems old fashioned now. As a user, I like when applications offer skins, but sadly 99% of the time, it's just stretched and pixelized low quality images with flashy colors that break the esthetics of the application. However, an example where a skin adds value is mobile applications offering a "dark theme" version which is especially useful for reading at night (e.g. the dark theme option of Twitterific). I am currently writing a sizable LOB application (WPF). I have chosen from the outset to make the application skinable, thus allowing the user to independantly choose their colour scheme and style. I have built this into the infrastructure now as I think it will be damn hard to retrofit. The reasons why I am adding this to a corporate application are: I have created a boring, corporate style but have given the users the option of choosing a pretty, eye-candy version. Sales is important, even in an internal system. I have created a developers' style which is mainly used to visualise the screen layout. I have the option of creating a large-font style for users the poor eyesight. I have the option of creating a high-contrast colour scheme for users the poor eyesight. I have the option of creating a minimal style for small screen machines In many organisations, there are union rules about readability, disabled access, yada yada yada... I don't know if this will become an issue for my app, but at least I have options. Please don't duplicate your answers word for word just because people are duplicating questions. No probs. I saw the dupe after this and though this one was languishing. My bad.
common-pile/stackexchange_filtered
Unable to retrieve value from Properties file using Spring's @Value, @ConfigurationProperties annotations I am new to Spring Boot and using Spring Annotations. I am trying to build a sample spring boot application in which I get a value for my java property using the properties file. I am trying to use @Component & @ConfigurationProperties parameter. I followed a bunch of tutorials online and this StackOverflow article helped, but my property value is still null Here is my code. Looked through:- unable to read properties using configurationproperties annotation https://www.mkyong.com/spring/spring-propertysources-example/ My SpringBoot Application class import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @EnableAutoConfiguration @SpringBootApplication public class Main { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Main.class, args); TestConf t = context.getBean(TestConf.class); System.out.println(t.toString()); } } TestConf Class import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("pres") public class TestConf { private String firstName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public TestConf() { System.out.println("inside constructor"); System.out.println("first name:" + firstName); } public static void main(String[] args){ TestConf t = new TestConf(); } @Override public String toString() { return "firstName:" + firstName; } } application.properties pres.firstName=JACQUELYN lastly my pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>phil</groupId> <artifactId>springTuit</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Optional, for bootstrap --> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.3.1</version> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.0</version> </plugin> </plugins> </build> </project> What is missing to retrieve the value from application.properties correctly into firstName? Does it matter where my application.properties file lies? Although it is in its traditional spot under src/main/resources and my java files are under src/main/java You have to specify where it is located since you are moving to default location . Spring boot always look for properties file under resources folder . to change you can use this property --spring.config.location="file:/path/to/application.properties" If you check, firstName would only be null on the constructor of TestConf and printing fine on the main method in Main class Also, why do you have a main method in the TestConf class? This seems standard. However, you can try with the combination @Component @PropertySource("classpath:applciation.properties") @ConfigurationProperties to TestConf.Java Be careful, you misspelt "application". So it seemed like the reason I did not get my value was not because of the code, but because the port was in use. I thought should not be an issue, but turned out that once I killed the process using the port and ran my application there, everything worked as expected. So my code was correct to begin with.. Thanks for your answers stackoverflow community Code needs couple of minor changes: @Component @ConfigurationProperties("classpath:application.properties") public class TestConf { @Value("pres.firstName") private String firstName; Won't fix the problems of not being a managed bean and of using unset fields from the constructor. You have two fundamental problems: Your new TestConf() instance isn't a Spring-managed object and thus doesn't get injected at all. Setter (or field) injection inherently means that the values aren't set until after the constructor runs. If you want to use a Spring bean from some task that gets run when you launch your Boot application, use a CommandLineRunner and inject the bean, preferably with constructor injection. you can try with the combination..it will work.... @Component @EnableConfigurationProperties @ConfigurationProperties(prefix = "pres") @Data public class TestConf { private String firstName; ............. } You can use @Value to get a property's value or as you are trying to fetch the configs using a Configuration class, below example might be helpful. A Controller class: @RestController public class ConfigurationController { //@Value("${app.name:Movies}") //private String name; //Alternative of configuration class @Autowired private Configuration configuration; @GetMapping("/config") public MovieConfiguration retrieveConfiguration() { return new MovieConfiguration(configuration.getName()); } A Pojo class public class MovieConfiguration { private String name; public MovieConfiguration(String name) { this.name=name; } public String getName() { return name; } public void setName(String name) { this.name = name; }} A Configuration class @Component @ConfigurationProperties("app") public class Configuration { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }} Properties server.port=8091 app.name=SpaceDrama
common-pile/stackexchange_filtered
django multiple ModelForms with the same model and ForeignKeys I am building a simple question-answer app with Django. My simplified model is: class Question(models.Model): question_text = models.TextField('Question', max_length=256) class AnswerChoice(models.Model): choice_text = models.CharField('Choice', max_length=32) question = models.ForeignKey(Question) is_correct = models.BooleanField(default=False) I have two ModelForms for the two models above (QuestionForm and AnswerChoiceForm). Now, I show a QuestionForm and 4 AnswerChoiceForms on a HTML page for editing a question and adding 4 answer choices for the question. I want to make sure that the user marks exactly one answer as "correct". My view function is: def edit_question(request): if request.method == 'POST': question_form = QuestionForm(request.POST) choice_forms = [AnswerChoiceForm(request.POST, prefix=str(i)) for i in xrange(4)] if all(c.is_valid() for c in choice_forms) and question_form.is_valid(): choices = [c.save(commit=False) for c in choice_forms] question = question_form.save() for c in choices: c.question = question c.save() return HttpResponseRedirect(...) # show the question just added # ... Now, I want to verify that exactly one of the choices out of the 4 is marked correct. I could do this check in the edit_question view function above, but somehow that seems a bit "wrong": I am adding core logic to a view function which I am not completely happy with. Is there a way to do this verification either in my Question or AnswerChoice models, or in the definition of the model forms? I have not provided a complete minimal code above in the hope that the amount of code shown is enough and that it doesn't get too long. If you need to see more code, please ask and I will edit this post. The problem here is that you are not using a formset for the answer forms. You should: not only are they less clumsy than instantiating four forms separately, they have a clean() method that is specifically meant for validation that goes across the child forms, rather than being per form. Something like this: class AnswerFormSet(forms.models.BaseInlineFormSet): def clean(self): correct_count = sum([form.cleaned_data['is_correct'] for form in self.forms]) if correct_count != 1: raise forms.ValidationError('Exactly one answer must be marked as correct') And in the view you would do this: def edit_question(request): AnswerFormset = forms.models.inlineformset_factory( Question, Answer, formset=AnswerFormSet, extra=4, max_num=4) if request.method == 'POST': question = Question() question_form = QuestionForm(request.POST, instance=question) answer_formset = AnswerFormset(request.POST, instance=question) # Check these separately to avoid short-circuiting question_valid = question_form.is_valid() answer_valid = answer_formset.is_valid() if question_valid and answer_valid: question_form.save() # No need to add new question as it was already set as the instance above answer_formset.save() # etc Thank you. This is exactly what I needed, and it's much cleaner. I am assuming return self.cleaned_data is a typo in the clean() method of AnswerFormSet? (Django complains about no such attribute.) Ah yes, you don't need that line, deleted. One option is as under: class Question(models.Model): question_text = models.TextField('Question', max_length=256) def validate_answers(obj): if obj.answerchoice_set.filter(is_correct=True).count()==1 #All well return True else: #delete question and answers if you wish or request for change return False But you should keep in mind that this will check if your answers are valid after everything is saved. And then if you want you may delete your questions or answers. def edit_question(request): #your usual code return (HttpResponseRedirect(...) if question.validate_answers() else HttpResponseRedirect(...)) This works, but one thing I wanted to avoid was to save my model instance to the database in case of errors. Thanks for the answer!
common-pile/stackexchange_filtered
HTML Target limit function to active window So i got a question about the Target function in HTML I got a link <a href="red.html/variable(a,b,c,etc.)" target="red">RED</a> all it does is, it opens a new Tab to red.html/variable, if red.html is already open in a tab it targets this tab and opens the link in the existing tab. fine so far. But i have some People who don't want to loose info they have filled in the red.html/variable A but still want to open red.html/variable B. So i thought well just drag it out of the window and make this tab its own window so it shouldn't target that other window. I thought wrong and it doesn't work like this. Is there a option how to force the Browser to use a function in just the active window (including tabs) but ignore other open windows? Example: Window1: TAB(red, green, blue) open Link"brown" with function mentioned above --> open new tab"brown" Window2: Tab(brown, yellow) <-- tab brown is ignored by links from window1. i do hope i was able to explain my problem and what i have in mind as targeted behaviour. Any help is appreciated. what i've tried: just different Target Options and rel=noopener. Non worked can't you just always open the link in a new tab regardless of which tab already has that url loaded? in that case it would be target="_blank". Anyway the target strategy doesn't take into accout to which window the tabs belong to when looking for matches. Your need may require you to do something really convoluted involving euristics that will guess if such event (moving tab to a new window) ever happened). But it's far from being simple and maybe impossible anyway I may have a suggestion being the furthest thing in my mind to address that problem: you have your page opening those links using unique targets; if you open a link twice, it will be reloaded on the same tab where it was opened the first time; but if you move that tab to a new window, since it's hard to understand such event occurred, you may add a button on the page (and inform the user about it) that when clicked, will change window.name detaching the browser context from the known target name so that clicking again the link on the main page won't reload that tab
common-pile/stackexchange_filtered
Installing MySQL-python raises compiler warnings after Mavericks I had many python modules installed before I upgraded Mavericks and were very disappointed when I noticed that they had been removed. I installed Mavericks, and I installed the command line tools. Then I went on trying to download and compile MySQL-python since I need it for my development. It raises compiler warnings during install and then just freezes. Here are the compiler warnings: Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.4.zip (113kB): 113kB downloaded Running setup.py egg_info for package MySQL-python Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz Extracting in /tmp/tmpYaLRd4 Now working in /tmp/tmpYaLRd4/distribute-0.6.28 Building a Distribute egg in /private/tmp/pip_build_root/MySQL-python /private/tmp/pip_build_root/MySQL-python/distribute-0.6.28-py2.7.egg Installing collected packages: MySQL-python Running setup.py install for MySQL-python building '_mysql' extension cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/local/Cellar/mysql/5.6.10/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.9-intel-2.7/_mysql.o -Os -g -fno-strict-aliasing clang: warning: argument unused during compilation: '-mno-fused-madd' In file included from _mysql.c:44: /usr/local/Cellar/mysql/5.6.10/include/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined #define SIZEOF_SIZE_T SIZEOF_LONG ^ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here # define SIZEOF_SIZE_T 8 ^ In file included from _mysql.c:44: /usr/local/Cellar/mysql/5.6.10/include/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined #define HAVE_WCSCOLL ^ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:906:9: note: previous definition is here #define HAVE_WCSCOLL 1 ^ _mysql.c:287:14: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32] cmd_argc = PySequence_Size(cmd_args); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:317:12: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32] groupc = PySequence_Size(groups); ~ ^~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:470:14: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32] int j, n2=PySequence_Size(fun); ~~ ^~~~~~~~~~~~~~~~~~~~ _mysql.c:1105:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32] len = mysql_real_escape_string(&(self->connection), out, in, size); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:1107:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32] len = mysql_escape_string(out, in, size); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:1146:9: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32] size = PyString_GET_SIZE(s); ~ ^~~~~~~~~~~~~~~~~~~~ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:92:32: note: expanded from macro 'PyString_GET_SIZE' #define PyString_GET_SIZE(op) Py_SIZE(op) ^~~~~~~~~~~ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/object.h:116:56: note: expanded from macro 'Py_SIZE' #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~ _mysql.c:1156:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32] len = mysql_real_escape_string(&(self->connection), out+1, in, size); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:1158:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32] len = mysql_escape_string(out+1, in, size); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:1252:11: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32] if ((n = PyObject_Length(o)) == -1) goto error; ~ ^~~~~~~~~~~~~~~~~~ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/abstract.h:434:25: note: expanded from macro 'PyObject_Length' #define PyObject_Length PyObject_Size ^ _mysql.c:1444:10: warning: implicit conversion loses integer precision: 'size_t' (aka 'unsigned long') to 'int' [-Wshorten-64-to-32] len = strlen(buf); ~ ^~~~~~~~~~~ _mysql.c:1446:10: warning: implicit conversion loses integer precision: 'size_t' (aka 'unsigned long') to 'int' [-Wshorten-64-to-32] len = strlen(buf); ~ ^~~~~~~~~~~ _mysql.c:1482:11: warning: implicit conversion loses integer precision: 'size_t' (aka 'unsigned long') to 'int' [-Wshorten-64-to-32] len = strlen(buf); ~ ^~~~~~~~~~~ _mysql.c:1484:11: warning: implicit conversion loses integer precision: 'size_t' (aka 'unsigned long') to 'int' [-Wshorten-64-to-32] len = strlen(buf); ~ ^~~~~~~~~~~ _mysql.c:1567:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare] if (how < 0 || how >= sizeof(row_converters)) { ~~~ ^ ~ 16 warnings generated. In file included from _mysql.c:44: /usr/local/Cellar/mysql/5.6.10/include/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined #define SIZEOF_SIZE_T SIZEOF_LONG ^ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:56:17: note: previous definition is here # define SIZEOF_SIZE_T 4 ^ In file included from _mysql.c:44: /usr/local/Cellar/mysql/5.6.10/include/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined #define HAVE_WCSCOLL ^ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:906:9: note: previous definition is here #define HAVE_WCSCOLL 1 ^ In file included from _mysql.c:44: /usr/local/Cellar/mysql/5.6.10/include/my_config.h:659:9: warning: 'SIZEOF_TIME_T' macro redefined #define SIZEOF_TIME_T 8 ^ /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:57:17: note: previous definition is here # define SIZEOF_TIME_T 4 ^ _mysql.c:1567:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare] if (how < 0 || how >= sizeof(row_converters)) { ~~~ ^ ~ 4 warnings generated. Seems like it complains on a lot of variables already defined. But I don't know how to solve these problems since I don't really know what's going on. And I don't think trying to edit the source will give me any good answers. I have tried to use both pip and easy_install to install the extension. Both generate warnings and freezes. Please help me :)
common-pile/stackexchange_filtered
mockftp serverfake FakeFtpServer; check if function is called I want to test my function indexFolder(...) that is responsible of retrieving files from a FTP. File has to be more recent than the local version to be download. private void indexFolder(FTPClient ftp, FTPFile[] listFiles, File localFolder, FTPFolderAssetSource ftpFolderAssetSource) { try { for (FTPFile currentFile : listFiles) { if (currentFile.isDirectory()) { if (getAssetSource().getIncludeSubDirectories()) { ftp.changeWorkingDirectory(currentFile.getName()); File localSubFolder = new File(localFolder.getPath() + "\\" + currentFile.getName()); localSubFolder.mkdir(); indexFolder(ftp, ftp.listFiles(), localSubFolder, assetSource); ftpCodeGestion(ftp, ftp.getReplyCode()); ftp.cdup(); ftpCodeGestion(ftp, ftp.getReplyCode()); }// if }// if else { File localFile = new File(localFolder.getPath(), currentFile.getName()); long FTPTimeStamp = currentFile.getTimestamp().getTimeInMillis(); long localTimeStamp = localFile.lastModified(); if (FTPTimeStamp > localTimeStamp) { downloadFromFTP(ftp, currentFile, localFile); indexFile(localFile, localFolder); } }// else }// for } catch (SocketException e) { connectionSuccess = false; connectionRetry(ftp); } catch (Exception e) { e.printStackTrace(); logger.error("Error indexing folder: " + localFolder.getAbsolutePath(), e); } } I want to know if the library import org.mockftpserver.fake.FakeFtpServer; can generate fake FTP file to permit me to count the amount of time the function indexFile(...) is called. with something like verify(ftpFolderTest,times(1)).indexFile(file, localFolder); I suspect you may get more help from the MockFtpServer discussion forum. I strongly recommend that you post both of your questions there.
common-pile/stackexchange_filtered
Why solution of recurrence $N_h = N_{h-1} + N_{h-2} + 1$ equals $N_h = F_{h+2} - 1$ Original question: Why does an AVL tree of height h has a min number of node $= F_{h+2} - 1$, where $F_h$ is the $h$th Fibonacci number? If $N_h$ is the min number of nodes in an AVL tree with height $h$, then a recurrence relation can be written as: $N_h = N_{h-1} + N_{h-2} + 1$, with $N_0 = 0, \ N_1 = 1$ I would like to know why $N_h = F_{h+2} - 1$. Do I have to solve both recurrences explicitly and plug in the numbers, or is there any other way of seeing it, since the form of $N_h = N_{h-1} + N_{h-2} + 1$ is extremely similar to that of the Fibonacci sequence, so I assume there would be another way of doing it directly from from the Fibonacci sequence. Note that $$N_h = N_{h-1} + N_{h-2} + 1$$ can be written as $$N_h+1=(N_{h-1}+1)+(N_{h-2}+1)$$
common-pile/stackexchange_filtered
Linux source, where are sys_umount and sys_mount system calls? Possible Duplicate: Understanding the linux kernel source I am sure that I must be missing something, here. I cannot for the life of me find the source code for these system calls. I can find their numbers, and I can find their prototypes, but I cannot seem to actually find the functions that implement them. In case anyone's interested: the reason that I am trying to find them is so that I can debug a problem with the kernel's floppy driver and/or my floppy drive itself. I can dd to/from it just fine. The drive works in DOS and Windows just fine. But when I mount a disk (any disk, doesn't matter what), the disk is mounted for approximately 1/10 of a second and then automatically unmounted. I am trying to find out why and if there is a way that I can patch my kernel locally to work around it. I know, I know, nobody uses floppies anymore. But I guess I am a nobody. :) Yeah, the question that this is allegedly a duplicate of doesn't actually say anything about these system calls. I did see that question. I did read it. But the answers were basically "uh, they're somewhere, but it's not regular". Additionally, I am looking for the switching points, not the implementations (I don't care about ext3 umount, I want VFS umount). They are were in fs/super.c in Linux 2.4: sys_mount sys_umount In my machine (Linux 2.6.24) they are in fs/namespace.c: sys_mount sys_umount In Linux 2.6.39 (which is latest stable) I could not find sys_mount function but I found compat_sys_mount function in /fs/compat.c. Thanks to Gilles for pointing out obsolete information. They were in fs/super.c in a very old version of the kernel. They're in fs/namespace.c now. LXR is the place to search. @Gilles You are right, but there is no version info in question. So haven't realized that my information is obsolete. Anyway, I have updated my answer with additional references. Awesome! How did you trace them to fs/namespace.c? I guess I was grepping for the wrong thing? @Michael Actually I used Google Code Search and then verify the existance of files and functions in my system.
common-pile/stackexchange_filtered
passing form input to javascript and then updating canvas So what I'm trying to do here is to pass information from a input form of number type to javascript and then re-draw the canvas with the updated variable data. Here's what I've got so far: <!DOCTYPE HTML> <html> <head> <script language = "JavaScript"> var canvas; var context; var _x = 0; function draw(newx) { context.rect(newx,100,100,100) context.strokeStyle = "red" context.stroke() } function sendVal(form) { _x = form.xx.value; context.clearRect(0,0,canvas.width,canvas.height); draw(_x); } window.onload = function() { canvas = document.getElementById("myCanvas"); context = canvas.getContext("2d"); context.rect(_x,100,100,100); context.strokeStyle = "blue"; context.stroke(); }; </script> </head> <body> <FORM NAME="SENDX" ACTION="" METHOD="GET"> Enter X: <INPUT TYPE="number" NAME="xx"> <INPUT TYPE="submit" VALUE="ENTER CO-ORDINATES" onClick="sendVal(this.form)"> </FORM> <canvas id="myCanvas" width="500" height="500"></canvas> </body> </html> As you can see above, I've tried making the canvas's context variable public so that I can access its functions from another part of the javascript, but the canvas never updates itself. How do I fix this? Thanks. I think your problem is not in the JavaScript but the HTML, an input of type "submit" wants to cause a form submit event, you just want an onclick event. Try just using: <input type="button" value="ENTER CO-ORDINATES" onclick="sendVal(this.form)"> Working JSFiddle: http://jsfiddle.net/nwellcome/mJyps/5/ Yeah, I figured that out, there was no way to confirm the data inputted. Thanks though.
common-pile/stackexchange_filtered
Edit attribute values of XML using VB6 I need to update the attribute value of bkp_path using VB6. XML File <ServerDetails> <Param src_path = "D:\Shapes\Rectangle" bkp_path = "D:\Colors\Red"/> </ServerDetails> I'm able to read values from XML file using VB6 Code Dim doc As New MSXML2.DOMDocument Set doc = New MSXML2.DOMDocument Dim success As Boolean 'Load Config.xml success = doc.Load("\Config\config.xml") If success = False Then MsgBox ("Unable to locate the configuration file") Exit Function Else Dim nodeList As MSXML2.IXMLDOMNodeList Set nodeList = doc.selectNodes("/ServerDetails/Param") If Not nodeList Is Nothing Then Dim node As MSXML2.IXMLDOMNode For Each node In nodeList srcpath = node.selectSingleNode("@src_path").Text bkpPath = node.selectSingleNode("@bkp_path").Text Next node End If End If but can't figure out how to update attribute values. This did the trick : node.selectSingleNode("@bkp_path").Text = "D:\Colors\Blue" You need to get a reference to the node object then call setAttribute() to specify the new value: node.setAttribute "bkp_path", "wibble" Your code also reads the values from all the Param nodes but you may want to only use the first or update a specific one. Yes, I'm looking to update a particular attribute not the first one, in this case 'bkp_path'. I've tried this earlier as well, didnt work. I said node (<Param ...>), not the attribute (src_path =). The attributes (using this code) are referenced by name. The code you supplied reads the values from EVERY <Param> node, but I assume you only want to set one of them. Yes, it should read each <Param> and update each bkp_path attribute. Finally, found the solution. This is what I was looking for : node.selectSingleNode("@bkp_path").Text = "D:\Colors\Blue" Anyways thank you for the prompt replies. Which does the same as I suggested... If you've found your answer, please post it as an answer and accept it.
common-pile/stackexchange_filtered
Novalidate isn't working on FOS user registration form I overwrote the FOS UserBundle registration form and added the default options: 'attr'=> array('novalidate'=>'novalidate') as answered here (which seems like the right way to go) but for some strange reason the novalidated is added to a div right after the form instead of the form. FormType: <?php namespace AppBundle\Form\Type; use Symfony\Component\Form\FormBuilderInterface; use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use AppBundle\Services\RolesHelper; class UserType extends BaseType { /** * @var RolesHelper */ private $roles; /** * @param string $class The User class name * @param RolesHelper $roles Array or roles. */ public function __construct($class, RolesHelper $roles) { parent::__construct($class); $this->roles = $roles; } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder->add('firstName') ->add('lastName') ->add('roles', 'choice', array( 'choices' => $this->roles->getRoles(), 'required' => false, 'multiple'=>true )); } /** * {@inheritdoc} */ public function getName() { return 'user_registration'; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { parent::setDefaultOptions($resolver); $resolver->setDefaults(array( 'attr'=> array('novalidate'=>'novalidate'), )); } } This is how my form looks: <form action="/app_dev.php/profile/edit" method="POST" class="fos_user_profile_edit"> <div id="fos_user_profile_form" novalidate="novalidate"> // .... </div> </form> Why would it be adding it to the div after the form instead of the form element. Am I doing something wrong? The novalidate="novalide" on the div is wrong. You need to place this on the form. For example like this using the controller $form = $this->createForm(new TaskType(), $task, array( 'attr' => array( 'novalidate' => 'novalidate' ) )); Or directly in the view {{ form_start(form, {attr: {novalidate: 'novalidate'}}) }} Final result <form action="/app_dev.php/profile/edit" method="POST" class="fos_user_profile_edit" novalidate="novalidate"> <div id="fos_user_profile_form"> // .... </div> </form> EDIT: Best solution via the form (for Symfony <= 2.6) WORKS /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'attr'=> array('novalidate'=>'novalidate'), )); } Best solution via the form (for Symfony >= 2.7) The configureOptions() method was introduced in Symfony 2.7. Previously, the method was called setDefaultOptions(). public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'attr'=> array('novalidate'=>'novalidate'), )); } IMPORTANT: If you're using FOSUserBundle, the configureOptions can't be applied directly on the form tag because this tag is manually called in the bundle views. Example in the registration_content.html.twig : <form action="{{ path('fos_user_resetting_reset', {'token': token}) }}" {{ form_enctype(form) }} method="POST" class="fos_user_resetting_reset"> since this is a form created with FOS UserBundle I can't run the createForm method. Any way I can add the novalidate in my class? Sorry i was editing my post. You can just apply it directly via the view. @zilongqui I would need to overwrite the template file to do this. I would leave that as my last resort. Are you sure there isn't a way I can handle this via setDefaultOptions() or something like that? @albertski +1 you can define the novalidation using setDefaultOptions (for Symfony version under 2.7) and configureOptions (for version >= 2.7) Unfortunately configureOptions() adds the novalidate to the div after the form. I have a feeling that the reason this is happening because of the template. https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/views/Profile/edit_content.html.twig At this time I don't have a view form but am using the FOS's template to display the form: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/views/Profile/edit_content.html.twig I'm wondering if the best way to do this is to copy the template (https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/views/Profile/edit_content.html.twig) to my bundle using these instructions: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_templates.md and adding the novalidate attribute manually: @albertski I tried in Symfony2.6 with setDefaultOptions and it worked. This problem only exist in Symfony2.7, the configureOptions doesn't add our custom attributes (here novalidate) in the form tag. I'm still searching. xd @albertski Sorry i was so silly !! As you mentioned in this doc, the form tag was write manually. So the configureOptions couldn't be applied for this tag. You have to override the FOSUserBundle view. Thanks that was it. Kind of sucks that they did it that way.
common-pile/stackexchange_filtered
haskell profiling says "total time = 0.00 secs", but it's not true I'm trying to profile my program. I compile it like that: ghc -rtsopts -O3 -prof -auto-all Main.hs And run: ./Main +RTS -p And read Main.prof: Fri Jul 15 13:06 2011 Time and Allocation Profiling Report (Final) Main +RTS -p -RTS total time = 0.00 secs (0 ticks @ 20 ms) total alloc = 266,726,496 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc trySub Main 0.0 14.3 ourPalindroms Main 0.0 15.0 isPalindromic Main 0.0 70.7 individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc MAIN MAIN 1 0 0.0 0.0 0.0 100.0 CAF Main 240 10 0.0 0.0 0.0 100.0 asSquareSum Main 253 0 0.0 0.0 0.0 0.0 squares Main 252 2 0.0 0.1 0.0 0.1 maxN Main 248 1 0.0 0.0 0.0 0.0 ourPalindroms Main 247 1 0.0 15.0 0.0 85.7 isPalindromic Main<PHONE_NUMBER> 0.0 70.7 0.0 70.7 main Main 246 1 0.0 0.0 0.0 14.3 asSquareSum Main 250 1998 0.0 0.0 0.0 14.3 trySub Main 251 1998 0.0 14.3 0.0 14.3 CAF GHC.IO.Handle.FD 176 2 0.0 0.0 0.0 0.0 CAF GHC.IO.Encoding.Iconv 137 2 0.0 0.0 0.0 0.0 CAF GHC.Conc.Signal 130 1 0.0 0.0 0.0 0.0 This awesome speed of my program is actually a lie: [.../P125]$ time ./Main +RTS -p ...output... real 0m4.995s user 0m4.977s sys 0m0.010s (Yes, I tried running both with and without time, and profiler keeps telling lies) What can I do? [.../P125]$ ghc --version The Glorious Glasgow Haskell Compilation System, version 7.0.3 The OS Mac OS X 10.6.8. I'm pretty sure I've installed ghc from homebrew No idea what happened, but optimization can interfere with profiling. Try removing the -O3 flag. Tried that, thanks. Nothing changed That's probably a GHC bug, see #5282. It is rumored to go away with -threaded. and it went away indeed! can you please write your comment as an answer so I could accept it? @Peter: On behalf of the Stack Overflow Janitorial Reserve Corps (that is, 10k users) and valya, yes, that is an answer (by virtue of suggesting -threaded). Please do leave it as such, so it will be easier for others to find and so that the question will show up as having an accepted answer. @valya,camccann: Okay. Sorry it took so long. I wanted to be sure that I properly understand the problem before answering. Short answer: The workaround is to compile with -threaded. Details for over-interested souls: The reason is a GHC bug (see #5282): The profiling timer always gets triggered when the run time system wants to perform garbage collection. As at that point the execution is not in Haskell code, the cost gets attributed to the "SYSTEM" cost centre - which is then dropped from the profiling view. The reason -threaded fixes the problem is probably that it makes the profiling timer tick in "real" time instead of the time the process was actually executing. Even though that is a less accurate form of profiling, it seems to decouple the timer enough from the program's execution to not trigger the bug.
common-pile/stackexchange_filtered
Passing advice to mode line I'd like to advise format-mode-line to collapse whitespace across the whole string. The following attempt does not work for me. (advice-add 'format-mode-line :filter-return 'collapse-whitespace) When I evaluate (format-mode-line mode-line-format), the output seems to be what I want, but the appearance of my mode line does not change. Very strange behavior, I find that if I advise the function in other ways, such as adding a character to the end it works as expected but collapsing whitespace does not. What does work for me, if you're seeking another working solution, is to change your mode-line-format to something like this: '((:eval (collapse-whitespace (format-mode-line original-mode-line-format))))
common-pile/stackexchange_filtered
Reading documents in .NET Can I open any file formats with Word interop that Microsoft Word itself supports? My task looks very simple, I need to read text, only text, from any type of documents commonly used (to compare the documents based on content). Is there a way I can do this easier than the above mentioned Word Iterop? Are there any free libraries to do this? Or to open any (.doc, .docx, .pdf, .rtf, openoffice docs, etc.) document types? I'm busy looking, but haven't found too many solutions yet, and I can't afford studying the 800-page specifications of all the formats. P.S.: Handling pdf separately is OK, as well as having libraries for all the types. I'm working on a new framework called Toxy. The goal of it is to extract data/text from various documents like what you mentioned. The first release will be available early next year.(maybe Feb.) You can find some implementation here: https://github.com/tonyqus/toxy. But it's not ready for now.
common-pile/stackexchange_filtered
Next.js App Router server component error handling Given a Server Component (or Server Action) that fetches data, how can I access the full error message for server-side logging purposes? Example: import os from 'os'; import { PHASE_PRODUCTION_BUILD } from 'next/constants'; export const dynamic = 'force-dynamic' async function getDataFromServer(): Promise<string> { if (process.env.NEXT_PHASE !== PHASE_PRODUCTION_BUILD) { throw new Error('Error from server'); } return Promise.resolve(`OS Type: ${os.type()}`); } export default async function Home() { const serverData = await getDataFromServer(); return ( <p>From server: {serverData}</p> ) } Running this in a "production" version (npm run build, npm run start) results in An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error. I do not want to expose the actual error message to clients, but I want to log it to a service server-side. Error boundaries are client-side, so they get the sanitized message. The only way I've found is to wrap every server method in try..catch. I can create a higher-order function to reduce the boilerplate, but is there a way to create a single server-side error handler (without delegating from every catch block)? In order to access the full error message for server-side logging purposes in a Next.js Server Component or Server Action, you can use a try catch. import os from 'os'; import { PHASE_PRODUCTION_BUILD } from 'next/constants'; export const dynamic = 'force-dynamic' async function getDataFromServer(): Promise<string> { if (process.env.NEXT_PHASE !== PHASE_PRODUCTION_BUILD) { throw new Error('Error from server'); } return Promise.resolve(`OS Type: ${os.type()}`); } export default async function Home() { let serverData; try { serverData = await getDataFromServer(); } catch (error) { // Log the full error message server-side console.error('Server error:', error); // You can choose to return a fallback value or rethrow the error if needed serverData = 'Error fetching data'; } return ( <p>From server: {serverData}</p> ); } Right, but I want to do this in one place for all pages / server components. Wrapping every component in a try..catch is messy and error-prone. in order to get all component errors for individual component I think it will be not possible as we need something in order to check for error for the particular component/function like an event
common-pile/stackexchange_filtered
Declare empty array in javascript update My code that works. When page is loaded product= [[],[]]; then the code executed after ajax call: $('#contextreload ul').each(function(i, ul) { product.push([]); }); $('#contextreload ul').each(function(i, ul) { allline=i; $('#reloadajax'+i+' li').each(function(lk, li) { var lilk = $(li).html(); product[i][lk]=lilk; // your code goes here }); // your code goes here }); To use eval(); in ajax response for this, with some changes in php file? /endupdate product[0]=[1,2,3,4]; product[1]=[a,b,x,z]; . . product[10]=[extra,extra,extra,extra]; When I load the page this is executed: product= [[],[],[],[],[],[],[],[],[],[]]; But if I declare this, when I call ajax I can push add data only to this array (10 rows) If I have 11 rows (product[10][0] and product[10][1]), the extra data will not be added. After ajax call I need the extra data : product= [[],[],[],[],[],[],[],[],[],[],**[11]**]; This function is because I want to put data in array after loading ajax data from php file. $('#contextreload ul').each(function(i, ul) { <strike> var product = $(ul).html(); </strike> allline = i; $('#reloadajax'+i+' li').each(function(lk, li) { var lilk = $(li).html(); product[i][lk]=lilk; alert(lilk+lk); // your code goes here }); // your code goes here }); } Why pre-allocate/dimension? Create a basic empty array =[]; then .push to it in the loop as needed I change the data after ajax call. First time I have 2 rows with data. After the call there can be 10 rows. @user3944364 Post the code of your ajax call In the succes of your ajax call use the function push() product.push([]); This adds an array at the last index of product. Like that ,the index 10 is created and you have an extra data. If you want to add a dynamic number of rows, use this code : var number_of_new_row = 11; // 11 for example, you can use any number >= 0 for(; number_of_new_row--;) product.push([]); Another way In your ajax return save the new length of your array product in a global variable. And use it before your loop to reset your array and initialize it with the new length. var lengthArray = 10; // update the value in the callback of your ajax call And your loop : var product = []; for(; lengthArray--;) product.push([]); $('#contextreload ul').each(function(i, ul) { //<strike> var product = $(ul).html(); </strike> allline = i; $('#reloadajax'+i+' li').each(function(lk, li) { var lilk = $(li).html(); product[i][lk]=lilk; alert(lilk+lk); // your code goes here }); // your code goes here }); I want to rewrite the array. I think my function is wrong with this line product[i][lk]=lilk; . Mabe product[i]=[var,var,var,var]; is right. I need to rethink the loop @user3944364 I added another way in my answer. Works $('#contextreload ul').each(function(i, ul) { product.push([]); }); Thanks Note: this line of your code produces a string, not an array. var product = $(ul).html(); //returns string not an array what you need is something like var product_arr = {}; // an object or var product_arr = []; // an array {} defines an object and not an array. [] is more appropriate thats right R3tep. that was what I meant on the 2nd line The following code used to declare empty array in javascript var product_arr = new Array(); //declaring empty array console.log(product_arr); var product = []; was the answer I was looking for personally
common-pile/stackexchange_filtered
Convert collection objects one type to objects another using Stream API and reference methods I use lambda to convert objects one type to objects another Order @JacksonXmlRootElement(localName = "order") public class Order { private String customer; @JacksonXmlProperty(localName = "orderItem") @JacksonXmlElementWrapper(useWrapping = false) private List<OrderItem> orderItems = new ArrayList<>(); public Order() { } OrderDto public class OrderDto { private String customer; private String orderXml; public OrderDto() { } service @Service public class OrderReadServiceImpl implements OrderReadService { private OrderEntityRepository repository; private OrderDtoMapper mapper; private CycleAvoidingMappingContext context; @Autowired public OrderReadServiceImpl(OrderEntityRepository repository, OrderDtoMapper mapper, CycleAvoidingMappingContext context) { this.repository = repository; this.mapper = mapper; this.context = context; } @Override public Iterable<Order> getListOrder() { Iterable<OrderEntity> orderEntities = this.repository.findAll(); Iterable<Order> orders = convertXmlToListObj(orderEntities); return orders; } private Iterable<Order> convertXmlToListObj(Iterable<OrderEntity> entities) { Iterable<OrderDto> dtoList = toListDto(entities); Iterable<Order> orders = convertListToList(dtoList); return orders; } /** * There is convert a collection of objects one type to another type * @param dtoList * @return */ private static Iterable<Order> convertListToList(Iterable<OrderDto> dtoList) { List<OrderDto> list = new ArrayList<>(); dtoList.forEach(list::add); List<Order> collect = list.stream() .map(orderDto -> { Order order = convertXmlToObj(orderDto); return order; }).collect(Collectors.toList()); return collect; } /** * there is got a string that xml. This xml is convert to java object * @param orderDto * @return */ private static Order convertXmlToObj(OrderDto orderDto) { String orderXml = orderDto.getOrderXml(); StringReader reader = new StringReader(orderXml); Order order = JAXB.unmarshal(reader, Order.class); return order; } /** * transform objects of entity type to objects of dto types * @param entities * @return */ private Iterable<OrderDto> toListDto(Iterable<OrderEntity> entities) { return this.mapper.toListDto(entities); } } The resulting list of entities is converted to a dto collection. The collection of the converted dto list is iterated over and retrieved from there xml from the field of each collection element and then the structure of this xml it will be umarshall (that is, the list of xml elements will be converted to the collection of java objects) List<OrderDto> list = new ArrayList<>(); dtoList.forEach(list::add); List<Order> collect = list.stream() .map(orderDto -> { Order order = convertXmlToObj(orderDto); return order; }).collect(Collectors.toList()); return collect; I would desire to do simplest. I want the code to will be yet lesser. Сan you remove the code somewhere, how to reduce it. I mean . Where do I create the 'method references' yet. Who has any ideas how to do this ? You can convert the Iterable to Stream directly, without creating a List: StreamSupport.stream(dtoList.spliterator(), false) Your code can become private static Iterable<Order> convertListToList(Iterable<OrderDto> dtoList) { return StreamSupport.stream(dtoList.spliterator(), false) .map(orderDto -> convertXmlToObj(orderDto)) .collect(Collectors.toList()); } Or with method reference: private static Iterable<Order> convertListToList(Iterable<OrderDto> dtoList) { return StreamSupport.stream(dtoList.spliterator(), false) .map(OrderReadServiceImpl::convertXmlToObj) .collect(Collectors.toList()); } BTW, since your method is named convertListToList(), perhaps it should accept and return Lists instead of Iterables. It is great. Thank you. I get the result into endpoint Rest-service. ( @GetMapping(path = "read", produces = MediaType.APPLICATION_XML_VALUE) public Iterable getList(){}) If you want to solve the problem of mapping objects in general and are not looking exactly for an optimization of your lambda/stream solution, you could give MapStruct a look. Simplified description: It generates mappers with the help of annotations at compile time. I use MapStruct, but for this task I don't know how to apply it
common-pile/stackexchange_filtered
Paypal Express Checkout Mobile Responsive with instant update I'm using the Paypal Express Checkout NVP (Name Value Pair) API. When I add a Callback URL for instant update shipping cost the whole paypal user interface changes to an older version that isn't mobile friendly / responsive. When I try to force the mobile UI with "_mobile-express-checkout" I'm getting an Error-Message that I'm using an outdated version. But I'm using version 204 that is the most up to date version. Is there any chance to get the responsive layout together with instant update for shipping cost? Unfortunately, I gave up on the instant update API years ago because it just makes things more difficult. It isn't worth the benefit to me. Also, the in-context feature for Express Checkout sort takes away the need for instant update, too. Have you looked into that? great to see this. PayPal's UI has been an utter joke for years. It's seriously pathetic and somebody should have been fired over it. https://www.bigcommerce.com/blog/paypal-express-checkout-in-context-one-touch/ Paypal are zero help and documentation yields no clues, and thankfully (/sarcasm) they don't make a distinction between non-responsive and responsive version of the checkout you are served #facepalm. Anyway In our testing of this on multiple clean installs of Magento and it seems that the mobile express checkout doesn't support 'Transfer Shipping Options' so it fallbacks to the old style. It should be easy to reproduce with any other Paypal Express SDK too. We are able to consistently isolate this across multiple environments. Now I need to wash my hands.. eek magento & magento clients..
common-pile/stackexchange_filtered
Get roles of current user in Discord server I'm trying to get the roles of the current user in a specific chat room using Discord's API (using an access_token). I've had a fair look through the docs and can't see how to do this. For example, doing a get request to https://discordapp.com/api/users/@me gives the basic user info as expected. I then tried something along the lines of the following without any luck: <EMAIL_ADDRESS> Here's a snippet of the code I'm using: ....get access token then .then(info => { console.log(info) fetch(`https://discordapp.com/api/users/@me`, { headers: { authorization: `${info.token_type} ${info.access_token}`, }, }).then(response => response.json()) .then(info => { console.log(info) }) }) Any ideas? To clarify, the user logs in with discord and my application receives a user access token which I'm then trying to use to get the roles of the user in a specific discord room. There is GET<EMAIL_ADDRESS>Which will get you a JSON object containing { "avatar": null, "communication_disabled_until": null, "flags": 0, "is_pending": null, "joined_at": "2023-01-11T23:12:34.423000+00:00", "nick": null, "pending": null, "premium_since": null, "roles": [ <PHONE_NUMBER>217623600, <PHONE_NUMBER>246944000 ], "user": { "id":<PHONE_NUMBER>500223000, "username": "your-name", "display_name": null, "avatar": null, "avatar_decoration": null, "discriminator": 4041, "public_flags": 0 }, "mute": null, "deaf": null } To use this with OAuth2, you must request the guilds.members.read OAuth2 scope, which is the one that Discord prompts users for their permissions with Read your member info (nickname, avatar, roles, etc...) for servers you belong to This was added in sometime in late 2021, judging from this PR. From the documentation you can do this using the endpoint: GET /guilds/{guild.id}/members/{user.id} This will return a guild member object that contains the roles of this user. Example guild member object: { "user": {}, "nick": "", "roles": [], "joined_at": "", "deaf": false, "mute": false } Hi, thanks I tried this but got { message: '401: Unauthorized', code: 0 }. I have the guild scope enabled when the user logs in with Discord The documentation notes here that to access certain things, including guild members, "you must first go to your application in the Developer Portal and enable the toggle for the Privileged Intents you wish to use." Maybe that is your issue. Does not work with access_token like OP asked. GET /guilds/{guild.id}/members/{user.id} is not a valid scope for oauth2.
common-pile/stackexchange_filtered
jquery form URL validation custom message I have included jquery file and following HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> HTML: <form action="http://www.google.com" onSubmit="return validate();"> <input type="url" required="true" name="URL" > <input type="submit" value="Submit"> </form> When i submit form with empty field give the message "Please fill out the field". I want to give my custom message. How can i do? Could you show validate function ? Check for the validate() in your files. There you can find Please fill out the field. Change it!! This helps you a lot. also this http://stackoverflow.com/questions/7293153/html5-bubble-messages You can use setCustomValidity: <form action="http://www.google.com" onSubmit="return validate();"> <input type="url" oninvalid="setCustomValidity('custom message ')" onchange="try{setCustomValidity('')}catch(e){}" required="true" /> <input type="submit" value="Submit"> </form> In mozilla this can be achived using: x-moz-errormessage="custom message" In your case there are two cases; blank and custom message. For this particular condition following code will work: <form action="http://www.google.com" onSubmit="return validate();"> <input type="url" oninvalid="setCustomValidity(validity.typeMismatch ? '(custom) wrong url ' : '(custom)Field cannot be blank ')" onchange="try { setCustomValidity('') } catch (e) {}" required="true" /> <input type="submit" value="Submit"> </form> you can write your own code as per your requirement referring to the following page Constraint Validation: Native Client Side Validation for Web Forms Try the following link also , i haven't tried it but it may be of help for you, Custom messages in HTML5 Thanks WisdmLabs, but still one problem. There are two messages will be show. 1. required field (when field will be empty). 2. Invalid URL (when user will enter wrong url). Thanks,
common-pile/stackexchange_filtered
Bind saved Date in Edit Form using Angular 17 I have a form where the date is entered and saved but the date is not binded when I go to edit the form. JSON: "checkOut": { "runDate": "2024-07-05T09:42:00.000Z", } The form is: <input type="datetime-local" [(ngModel)]="checkOut.runDate"> Date is shown by binding like this: {{source.room.checkOut?.runDate | date:"dd MMM, yyyy"}} When I go to edit the form, I want the input field [(ngModel)]="checkOut.runDate" to be pre-filled if the date is already entered. How can I achieve this? Datetime local excepts the input to be like 2024-07-05T09:42:00, So we can transform it to suit the requirement. ngOnInit() { this.checkOut.runDate = this.checkOut?.runDate?.split('.')?.[0]; } Full Code: import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { bootstrapApplication } from '@angular/platform-browser'; import 'zone.js'; @Component({ selector: 'app-root', standalone: true, imports: [FormsModule, CommonModule], template: ` <input type="datetime-local" [(ngModel)]="checkOut.runDate"> <br/> {{checkOut.runDate | date:"long"}} `, }) export class App { checkOut: any = { runDate: '2024-07-05T09:42:00.000Z', }; ngOnInit() { this.checkOut.runDate = this.checkOut?.runDate?.split('.')?.[0]; } } bootstrapApplication(App); Stackblitz Demo Thank you so much. Got it working. What does split('.')?.[0]; do btw? @ElaineByene It converts the date to 2024-07-05T09:42:00 by splitting on the . Then it gets converted into ['2024-07-05T09:42:00', '000Z'] here we access the zeroth element, which is our expected output!
common-pile/stackexchange_filtered
Swift NSUnknownKeyException - setValue:forUndefinedKey I'm very new to swift, and I'm doing the Stanford course on iTunes U. I've been following along fine, but I've encountered an error that I'm unable to understand: 2015-06-29 18:45:35.080 calculator2[9780:4828233] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<calculator2.ViewController 0x7fae561041b0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key enter.' I've uploaded my repo to github here. Any help is very much appreciated. Amar In your Main.storyboard file you have an a referencing outlet set for a button called "Enter" to an IBOutlet variable called enter that seems to long longer exist in your ViewController class. To fix this, declare this variable in ViewController or delete the reference to it from interface builder. @IBOutlet weak var enter: UIButton! Similarly, the IBAction to which your Enter button is connected is enter:, but your IBAction method is called enter (without a colon). You should change it to include a parameter, which maps to the selector name that includes the colon. @IBAction fun enter( sender: AnyObject? ) {} And, it would be better not to use a simple name like enter for either an IBOutlet or an IBAction, and of course not for both. Something like enterButton for the IBOutlet and enterPressed: for the IBAction would be more appropriate and prevent confusion or a naming conflict. If you right click on your ViewController object in interface builder, you can see that Xcode is trying to warn you about these problems with the yellow warning icons:
common-pile/stackexchange_filtered
Interface method reference to a functional interface I am working with Java Spring framework and JWT - Java Web Tokens. I have below class import java.util.function.Function; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import app.com.javainuse.config.JwtTokenUtil; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; public class Test { public static void main(String[] args) { User u=new User("javainuse", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6",new ArrayList<>()); UserDetails ud=u; JwtTokenUtil jwtTokenUtil=new JwtTokenUtil(); String token = jwtTokenUtil.generateToken(ud); Test t=new Test(); System.out.println(t.getClaimFromToken(token, Claims::getSubject)); } public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { final Claims claims = getAllClaimsFromToken(token); System.out.println(claims.toString()); return claimsResolver.apply(claims); } private Claims getAllClaimsFromToken(String token) { return Jwts.parser().setSigningKey("javainuse").parseClaimsJws(token).getBody(); } } I am not able to understand statement containing this Claims::getSubject in main method. It gets passed to a functional interface Named Function<Claims,T> claimresolver. How does a method reference getSubject without implementation able to return subject from claims object in getClaimFromToken method ? When we pass method reference to a Functional Interface we the method must have body wight ? but Claims is an interface and getSubject does not have a body then how does "claimsResolver.apply(claims);" is able to get subject value ? I think this is delegation. The instance of Claims comes from getAllClaimsFromToken(). Therefore, the implementation of Claims also comes from getAllClaimsFromToken() which was called as Jwts.parser().setSigningKey("javainuse").parseClaimsJws(token).getBody() need more explanation on this. Is there any example online ? What is it called in java terms ? Does this answer your question? Difference between method reference Bound Receiver and Unbound Receiver someInstance.getSubject() bakes a cake and returns it to you. Claims::getSubject is a recipe for baking cakes. One does the thing. The other doesn't do anything, it merely is a description of how to do the thing - whatever you hand it to can do the thing, or not, or do it 10 times - or pass the recipe on to somebody else who is then faced with the same choice. They can do whatever they like: Toss the recipe in the garbage (and no cakes ever exist). Bake a cake. Bake 10,000 cakes. Start 100 threads and bake 100 cakes simultaneously. Save the recipe for later and bake some cakes tomorrow. When I write down a recipe for making cake, one of the ingredients I'm going to mention is that you will need fresh water. That means, to bake a cake, I need fresh water. Or perhaps a tap (something that can make fresh water for me). However, to make a cake recipe I do not need fresh water at all. I just need to tell you (the one who will be following my recipe to bake that cake): "You will need to obtain some fresh water. Not my problem how you do that!". In other words, a cake recipe is a recipe that turns fresh water (and some other things) into a cake. It does not explain how to obtain fresh water, nor does a recipe for making cake come wrapped around a bottle of fresh water. In the same vein, Claims::getSubject is a recipe that explains how to turn any instance of a class that implements Claims (i.e. a Claims instance) into a String. It does not come with an instance of Claims nor does it explain how to make an instance of Claims. It merely says: IF you have an instance of Claims, this recipe lets you turn that Claims into a String! Claims::getSubject specifically says: Take your claims, call it c. Run c.getSubject(). Voila, there's your string. Here, you pass that notion (a recipe for turning claims into strings) to the getClaimFromToken method, which apparently knows how to produce an instance of Claims. That's analogous to me handing you a cake recipe today and you showing up with a cake tomorrow. That implies you managed to obtain some fresh water. I do not know how and I don't really need to care - I get to enjoy some cake! NB: Obviously getClaimsFromToken knows how to make an instance that implements Claims from a token, and will then apply your recipe (i.e., call .getSubject() on it). But that's just 'guessing' - the point of APIs is that they promise they do X. You don't need to bother with knowing how it does it, you just need to bother with knowing what it does, and perhaps ascertaining that the library is fit for purpose and it does what its docs say it does. I understand that we have to accept that this is how lambda work in this situation. I saw it for the first time and I was looking for a page which describes this situation. Just like for Integer like classes there is concept called autoboxing we need to accept this thing as it is. Do you know any page which describes this method reference type ? There are method references. There aren't 'method reference types'. Whenever you write a method reference, from the immediately surrounding context, javac must be able to determine which functionalinterface it is an implementation for. If javac cannot, that is a compiler error - because there are no types for functions like this, javac needs to figure out (from context) what type you want and compile accordingly. So in this case Java compiler sees that claims object has a same method signature as Claims::subject and not the apply method because it accepts Claims instance ? No, :: is the syntax for 'make a method reference'. It would never 'apply the method'. It sees Claims::getSubject and translates that to, more or less, class $InlineImplementation implements Function<Claims, String> { @Override public String apply(Claims c) { return c.getSubject(); }} followed by new $InlineImplementation(); which is the value of that expression. You're right that the Claims::getSubject syntax here is passing a method reference to the Function interface, rather than implementing the full lambda expression. The key to how this works is that Claims is an interface that extends the Claims interface from the io.jsonwebtoken library. That io.jsonwebtoken.Claims interface defines various getter methods like getSubject(), getIssuer() etc. without providing implementations. So when we call: Claims::getSubject We are providing a reference to the getSubject() method on the io.jsonwebtoken.Claims interface. Even though the interface doesn't provide an implementation, at runtime the claims object will actually be an instance of some class that implements the io.jsonwebtoken.Claims interface and provides a concrete implementation of getSubject(). When claimsResolver.apply(claims) is called, it will invoke that underlying getSubject() method on the claims instance, which returns the subject value. So in summary: Claims::getSubject provides a reference to the interface method The claims object provides an implementation of that interface So claimsResolver.apply(claims) is able to call the implemented getSubject() method to return the value is there any other example link or concept explanation link you can provide ? There is an example. I found what it is called in java. It is called unbound non-static method references. Here is a link which explains every type method references and the scenario which I was asking to explain. Unbound Non static method references Congratulations for finding out. Four of the five newest questions tagged with method-reference are asking the same question. Not to speak of the hundred other questions already answered in the past decade.
common-pile/stackexchange_filtered
How to create a PowerPoint viewer in Android? I am curious how to create a simple PowerPoint presentation viewer for Android. I am focusing on the Office 2003 and 2007 formats (which means .ppt and .pptx). How do I read .ppt or .pptx files and show them like a picture slideshow on my Android app? Well that's a loaded question. Are you seriously thinking someone will write down the whole process for you? Have you done any research? I'd start by seeing if there are any java libraries for working with .ppt files. Secondly, I'd see if I can use it in Android. Then I'd use the Android SDK to create the app using the said library. Easy. Thanks for the answer. I wasn't expecting a thorough explanation actually. I did a little research and found the Apache POI library, and wasn't quite pleased with its current version as they said it can't read a .pptx file. I will try to use it for a .ppt file though. Thanks! @Gilang - Did you find any suitable library for ppt or pptx viewer ?
common-pile/stackexchange_filtered
Writing a DELETE query for 3 tables I am trying to write a simply query that will delete an event based off its event_id. That event_id could be in 1 of 3 tables in a database however. Leagues Tournaments Trainings Each event_id is generated by a randomizer function so each id is unique. I have tried a few different syntaxs for SQL but none of them will actually delete the event from the DB table. Any suggestions? Here is what I have: if(isset($_POST['delete'])){ $query = "delete from leagues where event_id= '$event_id', delete from tournaments where event_id= '$event_id', delete from trainings where event_id= '$event_id'"; $result = mysqli_query($conn, $query); header('location: index_admin.php'); } else { } I have also tried using the union command, using multiple delete queries, putting a semicolon after each delete command. What else can I try? Just make this three separate delete statements that you run one after the other. The syntax of your query is wrong: you can't just string together three queries separated by commas, but more than that, you don't seem to have initialised $event_id, so your query won't include the ID to delete. @ThorstenKettner you mean like this: $query = "delete from leagues where event_id='$event_id' delete from tournaments where event_id='$event_id' delete from trainings where event_id='$event_id'";? @TangentiallyPerpendicular Sorry I didnt capture the full page, I do have $event_id initialized higher up. The query works when I only target 1 DB table, I just need to be able to target all 3 in one query. I mean this: $query = "delete from leagues where event_id ='$event_id'". Then: $query = "delete from tournaments where event_id ='$event_id'". At last: $query = "delete from trainings where event_id ='$event_id'". if(isset($_POST['delete'])){ $stmt = $pdo->prepare('delete from leagues where event_id = :event_id'); $stmt->execute([ ':event_id' => $event_id]); $res = $stmt->fetch(); header('location: index_admin.php'); }else{ } This is dangerous, susceptible to SQL injection: https://www.php.net/manual/en/security.database.sql-injection.php No reason to execute 3 separate DELETEs. DELETE leagues, tournaments, trainings FROM (SELECT $event_id AS event_id) src -- use parameter instead of immediate insert LEFT JOIN leagues USING (event_id) LEFT JOIN tournaments USING (event_id) LEFT JOIN trainings USING (event_id) Of course you'd not insert the value into the query like above - you'd use prepared statement.
common-pile/stackexchange_filtered
Configuring apache. Reverse proxy and alias In file /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ProxyPass / http://localhost:7000/ </VirtualHost> When I type in the browser the address http://example.com I get a response from the application running on port 7000. What needs to be added in the settings so that when typing http://example.com in the browser, I would receive the contents of the /var/www/html/ directory, and when typing http://example.com/emby/, the response from the application on port 7000? Please share more details. http:\external ip address\ is not a valid address after all As per https://httpd.apache.org/docs/2.4/mod/mod_proxy.html you need to do ProxyPass "/emby" "http://localhost:7000/" ProxyPassReverse "/emby" "http://localhost:7000/" Keep in mind that ProxyPass and ProxyPassReverse do not rewrite any HTML or JS so if you have for example a SPA that loads from / or uses some absolute path, it may stop working. Thanks for the answer. I tried this example from the documentation. Why am I getting the error: Not Found The requested URL was not found on this server. Do you have anything in the logs? How about the logs on the application in the back end (port 7k)? Found a solution to my problem in this answer: httpd - reverse proxy on multiple ports As a result, the setting looks like this: ProxyPass /emby/ http://localhost:7000/ ProxyPassReverse /emby/ http://localhost:7000/ I also created a folder: mkdir /var/www/html/emby
common-pile/stackexchange_filtered
Including multiple fields in a Postgres table index I'm using Postgres 8.4 and I'm performing a search using ILIKE. Since I'm searching in 4 columns (containing text) from that table I was wondering if it's ok to create a single index for all the 4 columns and not an index for each column. Thank you. This is a bit of a complicated topic. In general databases will not optimize a LIKE query unless it is anchored to the beginning. If you are searching across 4 columns, then this is LIKEly not the case. http://www.postgresql.org/docs/8.4/static/indexes-types.html The optimizer can also use a B-tree index for queries involving the pattern matching operators LIKE and ~ if the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar'. However, if your database does not use the C locale you will need to create the index with a special operator class to support indexing of pattern-matching queries; see Section 11.9 below. It is also possible to use B-tree indexes for ILIKE and ~*, but only if the pattern starts with non-alphabetic characters, i.e., characters that are not affected by upper/lower case conversion. You may consider the full text support in postgresql if you are doing natural language queries (like a search engine)... Or wait für 9.1 which will be able to use an index for LIKE and ILIKE: http://www.depesz.com/index.php/2011/02/19/waiting-for-9-1-faster-likeilike/
common-pile/stackexchange_filtered
Python closures def counter(x): def _cnt(): #nonlocal x x = x+1 print(x) return x return _cnt a = counter(0) print(a()) Above code gives the following error UnboundLocalError: local variable 'x' referenced before assignment Why this is not able to create a new object with value 'x+1' in the namespace of _cnt and bind it to x. we will have reference x in both function namespaces As soon as you assign to a name in a given scope, all references to the same name inside the same scope are local. Hence x + 1 cannot be evaluated (as it tries to reference the local x). Hence this works: def f(): x = 42 def g(): print(x) g() f() But this doesn't: def f(): x = 42 def g(): print(x) x = 42 g() f() The first print has this bytecode: 0 LOAD_GLOBAL 0 (print) 3 LOAD_DEREF 0 (x) 6 CALL_FUNCTION 1 9 POP_TOP while the second print has this one: 0 LOAD_GLOBAL 0 (print) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 POP_TOP I think an assignment statement like 'x = x + 1' is executed like this. First expression x + 1 is evaluated (so x is refering to counter's x) and then the return value of the expression is assigned to x (this should create a new reference in _cnt's namespace As you can see in my second example, as soon as you assign to a name, all reference to it become local, no matter if they happen before or after the assignment. @user634615 I added the disassemblies. The LOAD_FAST is what fails. it means the flow of assignment statment differs according to where it is used. That is a bit surprising @user634615: name locality is defined at compile time, not at execution time. Expression execution order has no influence on that. @MartijnPieters then why above code works if x is mutable obect @user634615: Because you are not changing the x name itself. It remains unchanged; it is bound to an object and only that object changes. The scopes of function counter and _cnt are not the same. Even though they're nested, it doesn't matter. So the x in counter does not exist in _cnt. Perhaps pass it as an argument (or use nonlocal, as you seemed to have understood)
common-pile/stackexchange_filtered
JUnit/Mockito test failing for bizarre reason I have a very simple method that I am trying to unit test: public class MyAntTask extends org.apache.tools.ant.Task { public void execute() { fire(); } public void fire() { // Do stuff } } I just want to write a unit test that confirms that calling execute() always invokes fire(), so I wrote this: @Test public void executeCallsFire() { //GIVEN MyAntTask myTask = Mockito.mock(MyAntTask.class); // Configure the mock to throw an exception if the fire() method // is called. Mockito.doThrow(new RuntimeException("fired")).when(myTask).fire(); // WHEN try { // Execute the execute() method. myTask.execute(); // We should never get here; HOWEVER this is the fail() that's // being executed by JUnit and causing the test to fail. Assert.fail(); } catch(Exception exc) { // THEN // The fire() method should have been called. if(!exc.getMessage().equals("fired")) Assert.fail(); } } I guess (and I'm by no means an expert) Mockito normally can't mock methods that return void, but this is a workaround. You basically say "wrap my object with a Mock that will always return a specific RuntimeException whenever a particular method is about to get executed". So, instead of fire() actually executing, Mockito just sees that its about to execute and throws an exception instead. Execution verified? Check. Instead of passing, it fails at the first Assert.fail() just below the call to myTask.execute(). For the life of me, I can't figure out why. Here's the first 10-or-so lines of the enormous stack trace JUnit is giving me for the fail: java.lang.AssertionError at org.junit.Assert.fail(Assert.java:92) at org.junit.Assert.fail(Assert.java:100) at net.myproj.ant.tasks.MyAntTaskUnitTest.executeCallsFire(MyAntTaskUnitTest.java:32) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) Any thoughts here, ye Mockito Gurus of StackOverflow? Thanks in advance! While fgb's answer is perfectly correct, I would wonder why you're bothering to unit test a method that is one line long, and has no logic. There comes a point where unit testing ceases to be an economical use of your time. I have never found a good reason for writing a unit test for a method that's quite as simple as this one. Because myTask is a mock, the real object isn't called at all. To call a real object, use a spy. You can test that a method is called using verify so there's no need for the exceptions. public void executeCallsFire() { MyAntTask myTask = Mockito.spy(new MyAntTask()); myTask.execute(); Mockito.verify(myTask).fire(); } Wanting to mock the object that you're testing doesn't seem right though. It's usually better to design the test so that you're verifying calls to a separate object instead. Agreed, plus Spies as partial mocks are discouraged by the Mockito team. I see here more design issue: why do you need one line method and both of them are public? the mocks are for simulating dependencies and not for the class under test if you'll make fire (quite unclear name) as private. You shouldn't test private behavior of your class
common-pile/stackexchange_filtered
Favorite tags/filters on Android App I login to my SO mobile android app to browse for questions/answers for very specific tags every time. I wish there was an easy way to do that in one click: like a favorite tags or a recent tags menu/button somewhere on the home screen or feeds page. Right now I have to either search for tags myself or open a similar question, click on the tag to go to tag filter view and then retype the filter. I wish this 2 or 3 step process is reduced to a one click menu/option on the home page/menu. Thank you guys. Again, the app is wonderful. @guessimtoolate that question you linked to us for the website. The one I have asked is for the Android app. So this is NOT a duplicate of that. Yeah my bad, sorry. I'd love to have that feature on both versions. If there's a way to "unflag" the question then I would. @guessimtoolate no way to cancel flag and only one close vote, it will expire soon so no big deal. Found a "real" dupe though. :) Oh Ok awesome. I don't mind having the question closed, as long as the feature request went though somewhere.
common-pile/stackexchange_filtered
Why do we have to forbid non-conforming lower and upper type bounds? (it's a repost of my unanswered question from<EMAIL_ADDRESS>about Scala) In the Scala Language Specification, §4.4 Type Parameters, there is a requirement: The most general form of a first-order type parameter is @a1 ... @an ± t >: L <: U. Here, L and U are lower and upper bounds that constrain possible type arguments for the parameter. It is a compile-time error if L does not conform to U. I'm interested in a particular case of this rule, when it applies to type parameters of a generic class definition. IIRC, in early versions of Scala this rule did not exist. One might think this was benign and in worst case could only result in an uninstantiable and uninhabited type (and even could be useful in some cases, when L and U depend on some type parameters and can be simultaneously satisfied with certain substitutions, although statically L does not conform to U). But, as I recall, it was demonstrated that without this rule it was possible to compile certain non-typesafe program, exploiting transitivity of subtyping, that resulted in a ClassCastException at runtime, although no explicit casts were involved. I tried to find or reconstruct such an example, but so far without success. Could you please help me to find such an example, or point me to other reasons why this rule must be required for the language to be typesafe? Thanks!
common-pile/stackexchange_filtered
export 'MdToolbarModule' was not found in '@angular/material' I am using "@angular/material": "^2.0.0-beta.11" in one of my pet project, and the package.json has the reference as follows, "@angular/material": "^2.0.0-beta.11" I have imported the necessary modules as follows, import { MdToolbarModule, MdIconModule, MdGridListModule, MdButtonModule } from '@angular/material'; @NgModule({ declarations: [ ], imports: [ MdToolbarModule, MdIconModule, MdGridListModule, MdButtonModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } but it throws an error export 'MdToolbarModule' was not found in '@angular/material' It is not MdToolbarModule anymore. Now it is called MatToolbarModule So the import should be import { MatToolbarModule} from '@angular/material'; I am aware of that :) ,such a silly mistake, thanks :) Yeah. pressure makes us forget everything for a moment. But instead scratching head for an hour with small mistakes, it is better to ask and fix it quickly. :) haha! its not pressure though! may be i have frequently used old version oh yeah. that's true. XD
common-pile/stackexchange_filtered
Generate a securestring password I currently have some (PowerShell) code that does this - $password = [System.Web.Security.Membership]::GeneratePassword(128,0) I realise that strings are generally considered insecure. So I am curious whether there is a way to generate a random password directly into a secure string? (for a little background, I am trying to find a solution to this post) You ARE generating a "random password". 2) Anything in plaintext is "insecure". As a second step, you need to encrypt the password. 3) UNLESS "generate password" and "encrypt password" are two separate steps ... how is anybody going to be able to use the password???? @paulsm4 I'm trying to avoid the 'anything in plaintext is "insecure"' part of that - by generating a random password directly as a SecureString - i.e. so there is no string step involved at all. Secure strings aren't all that secure to begin with. And as paulsm4 already said: nobody will be able to use the password if you create and encrypt (hash, actually) a random string in one step. How would the intended user know the password? @AnsgarWiechers there are reasons that securestrings exist though. I am aware of the weaknesses of SecureStrings, but by using SecureStrings thoughout an application they do reduce the likelihood of sensitive data leaks. A determined attacker might be able to easily bypass them, but that doesn't mean they shouldn't be used to add a layer of protection where it is appropriate. My point wasn't that you shouldn't use them, but that you should be aware of their weaknesses, so you can make an educated decision when to use them, and when not to use them. From what I can see I'd say using ConvertTo-SecureString -AsPlainText -Force and suppressing PSAvoidUsingConvertToSecureStringWithPlainText should be fine in your scenario. @AnsgarWiechers It is the awareness of the weaknesses that I'm trying to find a solution for - by using -AsPlainText the plain text will be left in memory and possibly swapped to disk (as plaintext) If I create the password as a securestring, it avoids that particular weakness. There may be other issues along the way that could leak that data, but I'll address those as I come to them. It isn't the warning that is bothering me, it is actual insecurity it is warning about. Turning the warning off and saying it should be fine, isn't really the stance I'm looking for
common-pile/stackexchange_filtered
Undefined control sequence \begin{math} I have been working to make my code working in LaTeX but I can't find any fix. I have replaced \textit with \itshape as I have read in another topic that this could trigger the error. It's still not working. \documentclass[11pt, letterpaper]{article} \usepackage[utf8]{inputenc} \usepackage[margin=1.2in]{geometry} \usepackage{mathtools} \begin{document} \begin{enumerate} \item {\itshape The probability that the random variable $X$ takes values ​​in a range $I = (a,b]$ este is given by} \begin{equation} P( a < X \leq b ) = \sum_{a<x_i \leq b} p_i, \tag{14} \end{equation} {\itshape which is equal to the sum of the probabilities $p_i$, corresponding to the possible values $x_i$ for which \begin{math} a<x_i\leg b \end{math}.} \end{enumerate} \end{document} The error displays as follows: ! Undefined control sequence. l.21 ...s $x_i$ for which \begin{math} a<x_i\leg b \end{math}.} ? I’m voting to close this question because the issue is due to a user's typo and the thread is not going to be helpful for other people. TeX is notorious for unhelpful error messages. This isn't too bad, once you know what it means: the "undefined control sequence" is at the end of the line beginning with l.21: \leg. Which should've been \leq haha. Thanks!
common-pile/stackexchange_filtered
403 IAM permission 'dialogflow.intents.list' on 'projects/None/agent' denied import os from fastapi import Request from dotenv import load_dotenv project_id = os.getenv('project_id') import google.cloud.dialogflow_v2 as dialogflow intents_client = dialogflow.IntentsClient() parent = dialogflow.AgentsClient.agent_path(project_id) I am trying to get the "intent list" / "entity list" but dialogflow does not response instead this message was showed "403 IAM permission 'dialogflow.intents.list' on 'projects/None/agent' denied" The problem here is that you can not use the dialogflow api in the local host. You will need to make it live with ngrok and then this will work. It will give all sorts of error on the local host.
common-pile/stackexchange_filtered
How to add serial number in Excel while printing I am printing 6 payment slips in 1 A4 paper from excel, all 6 slips has same information like Name, payment date and etc... while there is a cell called Serial number. I want to print serial number in each 6 cells of the same A4 paper. For example on cells C4, C 10, C14 and C18 I want serial number while i print it should show. I will print 100 A4 paper at once which means I should have at least 600 serial numbers. Please help. Have you considered making a table or list of each item and generate the serial number there? You can then reference the serial number in the other table from your standardized payment slip format using VLOOKUP if you have unique data. You could use a formula like =row() in each of the cells. That will print the row number. Assuming the slips are all in different rows, that will give you a unique number for each slip.
common-pile/stackexchange_filtered
What is the significance of dumping the tablespaces? While recently running drush sql-dump on a server where there were never any error messages, I have started to get: mysqldump: Error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation' when trying to dump tablespaces It still produces a file I can import locally and I don't seem to be having any problems. But I am still curious: What is the significance of dumping the tablespaces when it comes to the average Drupal sysadmin? Environment Drush: Drush Commandline Tool 10.3.2 Drupal: 8.9.13 DB: Server version: 5.7.31-34-log Percona Server (GPL), Release '34', Revision '2e68637' Acquia Cloud hosted Can you please add the versions of Drush, Drupal and mysql to your post? Tablespaces are used to define the physical file location of one (or more) tables - chances are if you were using them for something beyond the default innodb space, you'd know about it. It's likely safe to ignore. The error will have started when MySQL was updated to 5.7.something, they introduced a breaking change in a minor version because it addressed a security flaw, and world + dog was greeted with this error message. There's a way around it: drush sql:dump --extra-dump=--no-tablespaces or, if using drush 8: drush sql:dump --extra=--no-tablespaces 5.7.31 was the version that introduced this breaking change. The drush issue for this is https://github.com/drush-ops/drush/issues/4489 And this also happens with mysql 8.0.21+ Drush 10: --extra-dump is correct: https://www.drush.org/latest/commands/sql_dump/
common-pile/stackexchange_filtered
Setup PHPStorm to debug symlinked WordPress plugin I'm using Herbert framework to develop a WordPress plugin. It recommends to set up a separate folder on a disk and symlink it to the "/wp-content/plugins/" directory. I created a project in PHPStorm with a original plugin directory. Then I added "wp-includes" folder as external library to get all the Wordpress. I also brought up a wordpress integration this way: Now this is how I tried to configure the server to get this plugin debugged. That isn't working. Can you guys please help me to debug it? Just a note to your last image: you have provided a path for project files ... but have not done it to the include path entry .. why? It's either all or none at all ("use path mappings" is unchecked).
common-pile/stackexchange_filtered
Let c be an integer which is not divisible by 3. Then the equation $x^3 − x = c$ has no integer solutions. I am trying to show the following. Let $c$ be an integer which is not divisible by $3$. Then the equation $x^3 − x = c$ has no integer solutions. My approach is to notice that if 3 does not divide c, then $c \equiv 1$ (mod 3) or $c \equiv 2$ (mod 3). Case #1: We have $x^3 - x = (x+1)(x-1)(x) = c = 3k + 1$ for some $k \in \mathbb{Z}$. I'm unsure where to go from here though. Case #2: We have $x^3 - x = (x+1)(x-1)(x) = c = 3k + 2$ for some $k \in \mathbb{Z}$. I'm also unsure where to go from here though. Any hints would be appreciated. I think the point is that $(x-1), x, \text{ and } (x+1)$ are three consecutive integers, so one of them must be divisible by 3. Note that no matter which integer $x$ is, $x^3-x=(x-1)x(x+1)$ is divisible by $3$. So basically, study the left-hand side, not the right-hand side of the equation $x^3-x=c$. Look at the equation modulo 3. There are only 3 residue classes to check. The remainder is either $0$, $1$, or $2$. In all casses, you get $0$ (mod 3). $x=0$: $\ \ 0^3-0\equiv 0$ (mod 3) $x=1$: $\ \ 1^3-1\equiv 0$ (mod 3) $x=2$: $\ \ 2^3-2=6\equiv 0$ (mod 3) Thus there can be no integer solutions because the remainders on the left side and the right side do not agree. This is of course because $3 \nmid c$ implies the right side is not $0$ (mod 3), $x^3-x=(x-1)(x)(x+1)$ is a product of three consecutive integers, so it is divisible by $3$, whereas $c$ isn't. More generally, by Fermat's little theorem $x^p-x=c$ with $p\nmid c$ has no integer solutions ($p$ is prime). In three consecutive integer numbers one is divisible by three. Then their product ...what property has the product? If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. Note that $2 \equiv -1 \pmod{3}$, thus we can choose $\{-1,0,1\}$ as a system of representatives for the equivalence classes modulo $3$. Since $0^3 = 0$ and $1^3 = 1$ (even in $\Bbb{Z}$), this immediately implies that $$ x^3 \equiv x \pmod{3} $$ for every $x \in \Bbb{Z}$, i.e. that $3 \mid x^3 - x$. ??????????????? @letsmakemuffinstogether Could you please be more precise in telling me which part of my answer you don't understand? From your question it looks like you are familiar with modular arithmetic. Is it not the case? Apologies. To be specific, I don't understand how you go from knowing that $2 \equiv -1$ (mod 3) to knowing that $x^3 \equiv x$ (mod 3) in a single step. I can't see how that works. @letsmakemuffinstogether That's because the only classes modulo $3$ are $-1,0,1$, but we already know that $0^n = 0$ and $1^n = 1$ (even in $\Bbb{Z}$!) for every $n > 0$.
common-pile/stackexchange_filtered
Manipulating URIs in Python Consider the following piece of code: >>> from pathlib import Path >>> >>> str(Path("gs://a/b/c")) 'gs:/a/b/c' As you can see, the double slash is stripped from the path. I'd like to manipulate this URI, but I would like to preserve the gs:// prefix with its two slashes. Question 1: Is pathlib the right tool for the job? Question 2: If not, are there any other tools like it that provide functions like Path's .stem, .name and .parent? I can't write a full answer right now, but no, pathlib is not the right tool for the job. URIs aren't paths. You can try this : >>> from urllib.parse import urlparse >>> urlparse("gs://a/b/c").geturl() 'gs://a/b/c' Have you heard of cloudpathlib? Its AnyPath class can be a drop-in replacement for pathlib.Path: >>> from cloudpathlib import AnyPath as Path >>> local = Path("/home/william/") >>> type(local) pathlib.PosixPath >>> str(local) '/home/william' >>> cloud = Path("gs://a/b/c") >>> type(cloud) cloudpathlib.gs.gspath.GSPath >>> str(cloud) 'gs://a/b/c' installable with pip (pip install cloudpathlib[s3,gs,azure]) or on conda-forge, i think. disclaimer: i'm not a contributor to this library, and i have no idea how or whether it's maintained
common-pile/stackexchange_filtered
Official "securing your pi" guide recommends blocking port 30 from <IP_ADDRESS> - why? The official "securing your pi" guide from the Raspberry Pi foundation recommends installing the "uncomplicated firewall" (ufw) and adding a rule to deny access to port 30 from <IP_ADDRESS>: sudo ufw deny from <IP_ADDRESS> port 30 The guide doesn't give any justification for this recommendation and my googling hasn't turned up anyone else recommending blocking this port or anything about risky protocols that communicate on port 30. The only info I have found is that it looks like some splinter cell games communicate over port 30 and that <IP_ADDRESS> is often a default address for routers. What the intent is of this rule and what protection is afforded by implementing it? There is no such recommendation - it is an example In the preface of Securing your Raspberry Pi the author says: This documentation will describe some ways of improving the security of your Raspberry Pi. This is followed by a conglomeration of options. I would name it "best practice list": Change your default password Changing your username Make sudo require a password Ensure you have the latest security fixes Improving SSH security Improving username/password security Using key-based authentication Install a firewall Installing fail2ban It may or may not be sensible to implement them: What level of security you need depends on how you wish to use your Raspberry Pi. The specific code your question is about (sudo ufw deny from <IP_ADDRESS> port 30) is only one general example for how to "Deny access to port 30 from IP address <IP_ADDRESS>". Like @Milliways already commented, this is not a (mandatory) recommendation. You will not necessarily end up with an insecure device if you do not block port 30 for the given IPv4 address. If you need to block a different IPv4 address and maybe a different port number, now you know how to do it using ufw: sudo ufw deny from [placeholder_for_IPv4_address] port [placeholder_for_port_number] The documentation could be more clear about this and point out, that this code is just an example. If you want, use the link in the documenations footer and help to improve it: View/Edit this page on GitHub. The documentation could be more clear about this and point out, that this code is just an example it actually does exactly that. Just above the lines OP comments on it says but here are some examples of more sophisticated commands
common-pile/stackexchange_filtered
how to update empty value with bind parameters in php mysqli I am creating message delete script in PHP MYSQLI. I have added zero value to update column. my script is working but I want to add zero value with bind parameters. Here is my source code <?php require_once "config.php"; if (isset($_GET['to_id'])) { $id = $_GET['to_id']; $session_id = $_SESSION['userid']; } $stmt = $con->prepare("UPDATE pm SET from_delete = '0' WHERE id = ? AND from_id = ?"); $stmt->bind_param("ss", $id, $session_id); if ($stmt->execute()) { echo"deleted successfully"; } else { echo "Failed to delete<br/>"; } ?> Just add another placeholder ? and bind value to it: $stmt = $con->prepare("UPDATE pm SET from_delete = ? WHERE id = ? AND from_id = ?"); $zero = '0'; $stmt->bind_param("sss", $zero, $id, $session_id); I added your script but showing like this message-Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\demo\npm\delete.php on line 26 Updated the code. I forgot that arguments should be passed by reference to bind_param. Zero has also a value.
common-pile/stackexchange_filtered
Does there exist a function $f:\mathbb{R} \to \mathbb{R}$ which is 'strongly discontinuous' at some point? A function $f:\mathbb{R} \to \mathbb{R}$ is discontinuous at $x_0 \in \mathbb{R}$ if there exists a sequence $a_n$ such that $a_n \to x_0$ but $f(a_n) \not \to f(x_0)$. I thought of a way of strengthening this by saying that a function $f:\mathbb{R} \to \mathbb{R}$ is strongly discontinuous at $x_0 \in \mathbb{R}$ if for every injective sequence $a_n \to x_0$, $f(a_n)$ diverges. But I can't think of an example of a function with this property. Does such a function exist? $f(x) = 1/x$ with $f(0)=0$? By injective sequence do you mean a sequence all of whose terms are distinct? @Z.Xie Ah, of course. That works. Is there an example where each sequence $f(a_n)$ doesn't converge at all (i.e., not even to infinity), or alternatively an example where $f$ is bounded? If bounded we could always apply Bolzano Weierstrass @Z.Xie Right, perfect. Thanks. Maybe I'm misinterpreting this, but doesn't $f(x)=1/x$ and $x_0 = 0$ work? Any sequence tending towards zero will correspondingly tend towards infinity. This answers the Q as it is stated. In the comments the proposer asks whether it is possible for all $x_0\in \Bbb R,$ which is a different Q, to which I have given an answer.....+1 The Q as written has been answered by ASKASK. The A to the Q in the proposer's comments, which is whether it can hold for every $x_0\in \Bbb R$, is NO. For $n\in \Bbb N$ let $S(n)=\{y\in \Bbb R: |f(y)|>n\}.$ Suppose that for all $x\in \Bbb R$ and for every $(a_n)_n$ sequence in $\Bbb R\setminus \{x\}$ converging to $x,$ the sequence $(f(a_n))_n$ does not converge. Then for $x\in \Bbb R$ and $n\in \Bbb N$ there must exist $r_{x,n}>0$ such that $$A(x,n)=(-r_{x,n}+x,\;r_{x,n}+x)\setminus \{x\} \subset S(n).$$ Otherwise $\forall s\in \Bbb N \;\exists a_s\; (0<|a_s-x|<1/s \land |f(a_s)|\leq n)$ but then $(f(a_s))_s$ has a convergent sub-sequence. Let $U(n)=\cup_{x\in \Bbb R}A(x,n).$ Then $U(n)$ is open and dense. The Baire Category Theorem implies that $\cap_{n\in \Bbb N}U(n)\ne \emptyset.$ But if $z\in U(n)$ for every $n$ then $z\in S(n)$ for every $n,$ so $|f(z)|>n$ for every $n\in \Bbb N,$ which is absurd.
common-pile/stackexchange_filtered
how can i get docs with unique sender in mongodb? I'm implementing a chat system using mongodb. Currently have a chat collection which looks like the json. When showing the conversation list to my user, I want to fetch the last text from each of the conversations. means for each sender-receiver pair, I want to fetch exactly one document. How can build the query for this? using node 12.16.1 and mongoose 5.8.9 { "_id":"6184bd15b3f9ad1e34e0e7ea"}, "sender": "6184bd15b3f9ad1e34e0d7ea"}, "reciever": "618d4cec8904317075520d36"}, "text":"hello" }, { "_id":"6184bd15b3f9ad1e34e0e7ea"}, "sender": "618d4cec8904317075520d36"}, "reciever": "6184bd15b3f9ad1e34e0d7ea"}, "text":"hello" }, { "_id":"6184bd15b3f9ad1e34e0e7ea"}, "sender": "618d4cec8904317075520338"}, "reciever": "6184bd15b3f9ad1e34e0d7ea"}, "text":"hello" }, ] Please provide sample data as json @mohammadNaimi please check i have updated the question
common-pile/stackexchange_filtered
Coredata performance: is there a penalty for loading many individual entities? I'm working on an app that will include a set of points drawn from CLLocationManager and draw them on a map. I'll never really have a need for each point as an individual entity, they only have meaning in the context of the path. Instead of creating a model representing the points, I could just store the path as a big JSON (or other more efficient string format) and thereby read only the single entity when it's time to pull the data out. It seems to me this could save overhead, is that true? This is something that would need some testing. Finding the path directly which contains the points is probably a faster way then fetching all the points which correspond to a certain path but the part with writing them into strings seems a bit off. Parsing those strings will be slow. (JSON being a string). For saving the points into paths I would suggest either to also add the point entity which is then linked through reference to the path. An alternative would be to use transformable data; Your point will be represented by 2 or 3 double values which could be put directly into a buffer (NSData for instance). The length of the data saved then defines the number of points as data.length/(sizeof(double)*dimensions). This would be extremely easily done in ObjectiveC while in Swift you may lose some hair when working with raw data and unsafe pointers. It really depends on what you are implementing but if you plan to have very many paths in the database you can still expect a large delay when fetching the data. You might want to consider creating sectors. Each sector would be represented with the same data as the region (MKCoordinateRegion) where on database initialize you would iterate to create sectors for the whole earth. Then when you are inserting paths you check what regions the path intersects with and assign the path to those regions (many-to-many relation). Now when you show the map you check what regions are visible and fetch only those regions and then extract paths from them.
common-pile/stackexchange_filtered
Async, callbacks, and closures After having spent a month or two trying to learn JavaScript, especially functional programming, async, and closures, I finally get it. But I don't know if I'm writing elegant code... Specifically, I'm not sure if I'm creating too many closures, because I don't entirely grasp when contexts remain and when they're marked for garbage collection. You can probably tell from the example that I'm using node.js -- basically, this is just a piece of test code that connects to a database, gets 20,000 records asynchronously with individual SELECT queries (I'm just doing some profiling, don't worry), and manipulates the data. At the end, it tells me how long it took and closes the MySQL connection. In order to get a final timestamp and close the connection, I needed something like the async library to keep track of all the various asynchronous functions that are being spawned. It takes all my queries as an array of functions (using a factory called makeQuery()) and then runs a callback to do the cleanup. Questions: Am I creating a huge amount of contexts by creating and returning the function doQuery() which uses the argument id in the makeQuery() function, thereby causing 20,000 contexts to persist until async.parallel() is run? Is the factory function makeQuery() a good and tidy way to create this array of doQuery() functions? Can you suggest any better way to do it? var mysql = require('mysql'); var radix64 = require('./lib/radix64'); var async = require('async'); var client = mysql.createClient({user: 'root', password: '12345678'}); client.query('USE nodetest'); var startTime = (new Date()).getTime(); // poor man's profiling var queries = []; // this will be fed to async.parallel() later var makeQuery = function makeQuery (id) { // factory function to create the queries return function doQuery (cb) { client.query('SELECT * FROM urls WHERE id='+id, function logResults (e, results, fields) { results = results[0]; results.key = radix64.fromNumber(results.id); // yep, I'm converting the // number into base-64 notation cb(); // if I wanted to do something useful at the end, I would have // called cb(results) instead, which compiles an array of results // to be accessed by the final callback } ); }; }; for (i = 1001; i <= 20000; i ++) { // build the list of tasks to be done in parallel queries.push(makeQuery(i)); } // run those tasks async.parallel(queries, function finished () { // clean up and get the elapsed time console.log('done'); client.end(); console.log(((new Date()).getTime() - startTime) / 1000); }); For those of you unfamiliar with async, it's a userland module built for node.js and the browser. Each function in the array that gets passed to async.parallel() is obliged to take a callback and then run that callback once it's done, in order to let async.parallel() know it's done. @Raynos yes. Oops. Just a test server running on <IP_ADDRESS>, but still... @Raynos would you be able to delete your comment, to hide the evidence? I removed the password in my code sample. There's a change log on the question, you know. oh yeah, you're right. Dang. var makeQuery = function makeQuery (id) { There is no need to make makeQuery a local variable, just use a function declaration. results = results[0]; results.key = radix64.fromNumber(results.id); Your just augmenting the object, your not doing anything with it. Other then that, your not creating new functions in a loop, your using a function constructor. This correct. Your running all 19000 queries in parallel rather then in waterfall, which is also correct. Edit: Question 1: You need to create 20000 contexts. Because there are 20000 values of i. Worrying about there being 20000 functions is a micro optimisation. v8 optimizes the hell out of your code. It actually splits your functions into a hidden class seperate from the closure context, and in my memory you simply have 20000 values of i and one value for the function. Just to remind you of rule 1. Never underestimate V8 Question 2: makeQuery as a factory is the correct pattern to use. The only other optimisation you can do is to write a real SQL query rather then 20000 dummy ones. But I'll ignore that because it's a dummy example. Re: having makeQuery a local variable, I guess you're right... I've just been too Crockfordised, that's all :) And in regards to augmenting results and then totally throwing it away, I know... just doing a speed test, so I don't want to actually use it. Thanks for the confirmation that using a constructor is correct... Also, I updated my question with actual explicit questions! My big concern is whether the constructor function is creating 20,000 contexts on account of the closure in which the returned function needs the id argument. Oh, and whether that's a problem at all. Yep, it's a dummy example. Trying to simulate the real-world use case, in which 20,000 people might indeed hit the server at once with their tiny little queries. Glad to know V8 won't mind about all my contexts. So when you say it splits that returned function out into its own, do you know if it would still do that if it were an anonymous function? Another Crockford-instilled anxiety. @Pauld'Aoust functions are functions. There's no difference Oh, okay. Crockford mentioned something about naming your functions so that you get 20,000 references to one function rather than 20,000 anonymous functions in the heap. Perhaps V8 doesn't do it that way, or else I didn't understand him correctly. At any rate, I guess it's good practice to name your callbacks so you get something to look at in your stack traces. @Pauld'Aoust the point is you have one named function nameQuery and 20000 anonymous functions (the functions returned from the nameQuery). When in doubt, go with restricting the closure context to the enclosing function scope: function makeLog(cb) { return function (e, results, fields) { // logResults results = results[0]; results.key = radix64.fromNumber(results.id); // yep, I'm converting the // number into base-64 notation cb(); // if I wanted to do something useful at the end, I would have // called cb(results) instead, which compiles an array of results // to be accessed by the final callback }; } function makeQuery(id, aClient) { // factory function to create the queries return function (cb) { // doQuery aClient.query('SELECT * FROM urls WHERE id=' + id, makeLog(cb)); }; } for (i = 1001; i <= 20000; i++) { // build the list of tasks to be done in parallel queries.push(makeQuery(i, client)); } Otherwise, you can as well get rid of the factories altogether: for (i = 1001; i <= 20000; i++) { // build the list of tasks to be done in parallel queries.push(function (cb) { // doQuery client.query('SELECT * FROM urls WHERE id=' + i, function (e, results, fields) { // logResults results = results[0]; results.key = radix64.fromNumber(results.id); // yep, I'm converting the // number into base-64 notation cb(); // if I wanted to do something useful at the end, I would have // called cb(results) instead, which compiles an array of results // to be accessed by the final callback }); }); }
common-pile/stackexchange_filtered
Swfitui Object not update when NavigationLink All Something is wired when use swiftui. object is not update in closure whick assign on second view when navigate back. code like this: NavigationLink(destination: DiscountsView(selectFunc: { (discount: DessertDiscount) in self.collection.discount = DiscountEntity(discount: discount) self.testDesc = discount.name }) ) { Text("优惠方案:\(self.collection.discount.name)") .font(ViewApperance.shared.font) .foregroundColor(ViewApperance.shared.fontColor) } ) The data Of collection not update, but testDesc update work, is anyone know what happen in this case, and what is the priciple of Object update in Swift? There might be several reasons. Would show minimal complete reproducible example of complete scenario to avoid guessing? thanks for the answer. i figure out the reason,the data will be replace when navigate back. the onAppear method of first view will request the data repeat, as result of the data will be replace. but there is an another issue, is there a way to distinguish lifecycle of view ,just like viewdidload、viewwillappear etc. in appkit?
common-pile/stackexchange_filtered
Does this proof work to prove that the greatest area of a triangle inside a circle is when the triangle is equilateral? Does this proof work to prove that the greatest area of a triangle inside a circle is when the triangle is equilateral? I gather it doesn't because most of the proofs I've seen use derivatives etc. If so why doesn't it work? Consider a triangle $ABC$ inscribed inside a circle $\Gamma$. Assume WLOG one of the sided is fixed then one can easily see that the other two sides being equal maximizes the area of the triangle (it has the greatest height). Now consider one of the two equal sides - using that side as a base we can see from the same argument as before that the triangle must in fact be equilateral to maximize the area (this triangle has the greatest height as before). Thanks in advance. Yes, I think this can work...yet it still looks a little shaky, doesn't it? I mean, you could try something some basic analytic geometry and, perhaps, some calculus to make it more formal...? Whoops! I was making my own assumptions about the problem. As @ChristianBlatter points out, you have proven that a non-equilateral triangle's area can be improved by your process (and that an equilateral triangle's cannot), but consider your process: starting with a triangle with side lengths $(a,b,c)$ and "base" $a$, you improve the area by constructing $(a,d,d)$; then, you improve that area (relative to the "first" base $d$) to get $(e,d,e)$. It could be that $d\neq e$, so you can keep trying, ever-increasing the area, but where's the guarantee that the process ends (or even converges)? Let us some analytic geometry using your idea: suppose our circle is $\,x^2+y^2=R^2\;$ , and we're going to fix, as you did, one of our sides as being parallel to the $\,x-$axis for simplicity, so that its end points are $\,A=(a,b)\;,\;\;B=(-a,b)\;,\;\;a>0\;,\;a^2+b^2=R^2\;,\;\;b\le 0\;$ . Let the other vertex be $\,C=(0,R)\;$ since, as you remarked, for the above two points of the triangle, the maximal height is obtained when the other two sides are equal, which means the third vertex is on the sides perpendicular bisector, which is easy to see is the $\,y-$axis. Thus, the area of the triangle depends on the distance $\,R-b=R-\sqrt{R^2-a^2}\,$ and on the horizonal side length's $\,2a\;$ : $$f(a):=a\left(R-\sqrt{R^2-a^2}\right)\implies f'(a)=R-\sqrt{R^2-a^2}+\frac{a^2}{\sqrt{R^2-a^2}}\stackrel ?=0\iff$$ $$R\sqrt{R^2-a^2}-R^2+a^2+a^2=0\implies(2a^2-R^2)^2=R^2(R^2-a^2)\implies$$ $$R^4-4R^2a^2+4a^4=R^4-R^2a^2\implies a^2\left(4a^2-3R^2\right)=0\implies$$ $$\implies a=\frac{\sqrt3}2R$$ so that the slope of the line $$CA\,\;,\;\;A=\left(\frac{\sqrt3}2R\,,\,-\frac12R\right)\;,\;C=(0,R)\;\,\;\;\text{is}$$ $$-\frac{\frac32R}{\frac{\sqrt3}2R}=-\sqrt3=\tan\frac{-\pi}3$$ and we're done... You have proven that as long as the three sides are not all equal the triangle does not have maximal area. If you assume without proof that a maximal triangle exists you are done. But note that the following could still be true: There is no maximal triangle at all, and someone comes up with some method enlarging even an equilateral triangle. In order to prove that there is in fact a maximal triangle one can use a compactness argument: The area of the triangle with vertices $re^{i\phi_k}$ $\>(1\leq k\leq3)$ is a continuous function on $[0,2\pi]^3$; therefore it assumes a maximum for certain choices of the $\phi_k$. A completely elementary proof that the equilateral triangle has maximal area is not so easy. You can find one (in German) here, pp. 60/61: http://www.math.ethz.ch/~blatter/SolutionsI.pdf
common-pile/stackexchange_filtered
Input is avilable only in turbo debugger I am tasked to right a program to check if two numbers are Amicable numbers, there is supposed to be an input by the user of 2 in size of 4 byte numbers, the program works perfectly in turbo debugger but it seems when I try to run the program as it is with dosbox it wont let me register the second input by the user, I am using one proc for the number input and another proc to find all the dividers of said number. ; Lab assignment 7 - Amicable Numbers .MODEL SMALL .STACK 100h .DATA ENTERkey DB 13 TWO DD 2 TEN DD 10 SUM DD ? NUM1 DD ? SUMNUM1 DD ? NUM2 DD ? SUMNUM2 DD ? NotAmicableMessage DB 13,10,'Not Amicable Numbers',13,10,'$' AmicableMessage DB 13,10,'Amicable Numbers',13,10,'$' .386 .CODE ; int getNum(); getNum PROC NEAR PUSH EBX PUSH CX PUSH DX MOV EBX, 0 MOV EAX, 0 MOV CX, 10 LOOPINPUT: MOV AH, 1 INT 21h CMP AL, ENTERkey JE FINISH SUB AL ,'0' MOV AH, 0 XOR EAX, EBX XOR EBX, EAX XOR EAX, EBX MUL TEN XOR EAX, EBX XOR EBX, EAX XOR EAX, EBX ADD EBX, EAX LOOP LOOPINPUT FINISH: MOV EAX, EBX POP DX POP CX POP EBX RET ENDP ; int Pnum(int EAX); Pnum PROC NEAR PUSH BP MOV BP, SP MOV SUM, 0 MOV EAX, [BP+4] PUSH EBX PUSH ECX PUSH EDX MOV BP, SP MOV EBX, EAX DIV TWO MOV ECX, EAX CMP ECX, 0 JE DONE LOOPNUM: MOV EDX, 0 MOV EAX, EBX DIV ECX CMP EDX, 0 JNE CONTINUE ADD SUM, ECX CONTINUE: DEC ECX CMP ECX, 0 JNE LOOPNUM MOV EAX, SUM DONE: POP EDX POP ECX POP EBX POP BP RET ENDP MAIN: MOV AX, @DATA MOV DS, AX CALL getNum ; Number 1 PUSH EAX MOV NUM1, EAX CALL Pnum MOV SUMNUM1, EAX CALL getNum PUSH EAX MOV NUM2, EAX CALL Pnum MOV SUMNUM2, EAX CMP NUM1, EAX JNE notAMICABLE MOV EAX, SUMNUM1 CMP NUM2, EAX JNE notAMICABLE MOV DX, OFFSET AmicableMessage MOV AH, 9 INT 21h JMP SOF notAMICABLE: MOV DX, OFFSET NotAmicableMessage MOV AH, 9 INT 21h SOF: MOV AH, 4ch INT 21h END MAIN Here is the first input and once I press enter I cannot enter the second number Again, the input works fine once I run the program in TD mode Looks like you don't zero EDX before the first div. Also, don't use DIV to divide by 2 in the first place. Computers use binary; you can just right shift with shr eax,1. Under a better OS, #DE exceptions would reliably result in a message from the OS, not silent failure. Also, under multi-tasking OS like Linux or Windows, debuggers can be fully non-intrusive so you wouldn't have this Heisenbug situation where it only appears not under the debugger. Thank you it is fixed now! Regarding " shr eax,1" I'll consider doing so in the future Also, around MUL, is that an XOR-swap?? Use xchg eax, ebx like a normal person. XOR-swap is basically never useful. Or better, since you're using 386 instructions (32-bit operand-size) anyway, use imul ebx, ebx, 10. Or use LEA to multiply by 10 and add a digit in 2 instructions even more efficiently. NASM Assembly convert input to integer?
common-pile/stackexchange_filtered
How can I run git filter-branch on the root commit? I'm trying to clean up a private project so I can publish it - removing miscellaneous files from the history, etc. I'm trying to remove a Makefile with git filter-branch. Here's the command line I'm using: $ git filter-branch -f --index-filter 'git update-index --remove Makefile' 08a7d1..HEAD However, when I run git log -- Makefile, it shows the Makefile being added in the root commit, then being removed in the commit immediately following the root commit. How can I get git filter-branch to run on the root commit as well? The problem is that the starting commit in the commit range you specified (08a7d1..HEAD) isn't inclusive. So basically it's saying "everything that happened after 08a7d1, all the way up to HEAD." Passing the commit range to git filter-branch is optional. If you omit it, it will be run on all commits, all the way back to and including the root. So: $ git filter-branch -f --index-filter 'git update-index --remove Makefile' That should do the trick. I had to change ONLY the root commit, for such change the solution I came up was using a (linux) IF statement inside the filter # Change ca1215d5bfc9928ef72c92f10dd53d3bc67c6274 for your own root commit ID git filter-branch --env-filter ' if [ $GIT_COMMIT = ca1215d5bfc9928ef72c92f10dd53d3bc67c6274 ] then # GIT Changes here fi' nice tip! just want to note that if statement isn't a "Linux" statement. it's a Unix shell construct and will work on pretty much any operating system that vaguely looks like a Unix, including Linux, the *BSDs and macOS.
common-pile/stackexchange_filtered
Retrieve URL with non-english character I want to open app from SMS (url schemes). For example, If someone send me text "myapp://abcd" I can open this url with safari and open application with abcd value by [url host]. But, the problem is if it is not english? For example "myapp://สวัสดี" (in thai) or "myapp://おはよう" (in japanese) and i open application with xn--l3c1bib8a0a instead of "สวัสดี". - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test" message:[url host] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; return YES; } Thanks in advance. The SMS character set is 7-bit and a bit special, so it looks like your service provider is translating international urls to their punycode (http://en.wikipedia.org/wiki/Punycode) equivalent... Thank you for very much for very fast answer but I still quite blind for what should I do next? Thankyou very much, Because of your answer I use keyword punycode and found NSURL+IDN which create by Jorge Bernal solve my problem.
common-pile/stackexchange_filtered
Scroll to bottom for Table View after Reload Data I am trying to scroll my table view to bottom after adding comments and replies. Comments are sections and replies are rows for that particular section but table view doesn't scroll at the exact bottom of the content after API call for adding comment, I have tried every possible solution available on net. Kindly suggest any solution for the same Could you share some code for better explanation? What have you tried before? Try using scrollToRow method This can be done with simple TableView scroll to bottom using IndexPath tblView.scrollToRow(at: IndexPath(row: 8, section: 0), at: .bottom, animated: true) Unfortunately there are no rows for the last section So are you showing comments? I am showing comments which are sections of UITableView What do you have in section? Header? Yes UITableViewHeaderFooterView whose height is dynamic From Jayraj Vala answer You've calculate the contentSize of the tableView to scroll at any particular point Use below code to scroll to bottom of tableView. func scrollToBottom() { let point = CGPoint(x: 0, y: self.tableView.contentSize.height + self.tableView.contentInset.bottom - self.tableView.frame.height) if point.y >= 0{ self.tableView.setContentOffset(point, animated: animate) } } Use described func() when you want to scroll tableView. May I also add that you should call this after you call your reloadData() function as otherwise it will have the incorrect contentSize calculations Thanks very much for the help, but I have tried above code which doesn't solve my issue As an extension for UITableView: extension UITableView { func scrollToBottom(withAnimation animated: Bool = true) { let rowCount = self.numberOfRows(inSection: self.numberOfSections - 1) - 1 // This ensures we don't scroll to the bottom if there is no content guard rowCount > 0 else { return } let point = CGPoint(x: 0, y: self.contentSize.height + self.contentInset.bottom - self.bounds.height) // This ensures we don't scroll to the bottom if all the content is small enough to be displayed without a scroll guard point.y >= 0 else { return } self.setContentOffset(point, animated: animated) } } Be sure to call this after tableView.reloadData() otherwise the table view contentSize used will be incorrect. Unfortunately there are no rows for the last section. I want to navigate to last section @UserTech Just remove the rowCount check then. The point and scrolling code will work Yes I have tried the code `let point = CGPoint(x: 0, y: self.contentSize.height + self.contentInset.bottom - self.bounds.height) // This ensures we don't scroll to the bottom if all the content is small enough to be displayed without a scroll guard point.y >= 0 else { return } self.setContentOffset(point, animated: animated)` but unfortunately it doesn't work for me @UserTech instead of self.setContentOffset(point, animated: animated) can you try self.contentOffset = point?. Also try calling self.layoutIfNeeded() after too if it still doesn't work.
common-pile/stackexchange_filtered
Login to .NET app (MVC, EF) when application starts. No login form used Thanks in advance. I'm developing an app for my company. Thing is, my boss asked me to do an automatic login, once the application starts. He does not want a traditional login form. For this purpose, I've coded a custom module for login. My issue is: I just can't figure out which Global.asax event should be used in order to trigger my custom login module(Or even if it's in Global.asax). I'm new developing with .NET , so apology if this scenario sounds trivial for all you. I'm currently doing this. But I think it's wrong since Session_Start gets called twice sometimes. protected void Session_Start() { try { User appUser=CustomLoginUtils.DoLogin(); mapSessionData(appUser); } catch (Exception e) { Response.Redirect("~/Error/Index?ErrorMessage="+e.Message); } } Can you post some of your code? @eglease I've added my code. Thanks for helping! You should not be using ASP.NET WebForms for new projects. You need to stop immediately, cut your losses, and restart with ASP.NET Core, otherwise you'll find yourself in a dead-end that's impossible to migrate to .NET 6. WebForms is over 20 years old now and hasn't seen any significant updates since 2008, and is really on its last-legs now. @Dai yes well, I can't use .Net Core. Thanks for the help. @AgustinMoragues Why can't you use .NET Core or .NET 6? Also, how does your "automatic login" functionality work, exactly? How are you authenticating the remote user and/or client software? (and Session_Start is not where you should be putting AuthX code - that needs to go in a custom IHttpModule that should be configured to run early in the request lifecycle, which means needing to tweak your web.config). @Dai ok , I'll investigate that. My automatic login just hits the AD of my company checking whether the user exists. Nothing strange. @AgustinMoragues That sounds like Windows Authentication, in which case you don't need to do anything, just configure Windows Auth in IIS (and disable Anonymous Auth) and that's it. No code required. (Also, if you're only checking to see if the user exists, you aren't actually authenticating the user, which means your system is insecure: - how do you know the request doesn't have forged headers or determine if they're a malicious user or not?) Let us continue this discussion in chat.
common-pile/stackexchange_filtered
Radar signal processing - Difference between range gate/range bin In learning about radar signal processing, I see two different terms that sometimes seem to refer to the same thing, but sometimes different things: Range gate Range bin Usually, I interpret both to simply mean "time sample", but sometimes I see range gating used to describe just taking a few samples around the estimated target range during a tracking phase. Is there a more nuanced definition that I should be aware of? Pri minus the pd is the Normal listening time. I thought the number of range bins was integer part of the inverse of the dutycycle. So is there a fraction of time between the range bins that is the "range gate"? If we wanted to add a nuance, the "gate" is the actual switching on of the receiver for the duration of observing the reflected signal (which can be as narrow as a single sample, which even a single sample for analog to digital conversions is an integrated observation over a sample time), while the range bin is which "gate" you are in. (Imagine a receiver that can have several gates covering the full possible range of the target). This originated from pulsed radar systems which is what my description above would apply to but can be shown to be equally applicable to other radar methods such as FMCW where an ambiguity in position can occur based on the repetition rate of the waveform. For tracking, I believe this is where the term "Early-Late Gate" originated: In this use the gate is subdivided into an early half and late half (or can be described as separate gates, one slightly earlier and the other slightly later in vicinity of known target location), and the central portion of the gate position is adjusted earlier or later based on the difference between the early and late gate. Here too we are "gating" the received signal to limit our observation to a narrow time interval (or even one sample).
common-pile/stackexchange_filtered
DirectFB cross-compiled for iMX.53 - crash on startup Trying to get a working directfb for use in an embedded system based on an i.MX53 processor (which is an ARM Cortex-A8 core) running Linux <IP_ADDRESS> (as supplied by Freescale). I have installed a cross compiler on my i686 debian host system. The cross compiler came from the embedian.org archive, and is the gcc-4.3-arm-linux-gnueabi package (arm-linux-gnueabi-gcc (Debian 4.3.2-1.1) 4.3.2). This is supplied with glibc 2.7. This is a different version from the version on my target system, which is glibc 2.11, although my reading suggests that they should be compatible. After much experimentation with the libraries already existing on the system image, I have managed to successfully compile directfb 1.6.2. This was complicated by the fact that I do not have working pkg-config info for the already-installed libraries, but I eventually managed to persuade it to compile using the following configure command line: TOP=`realpath ../..` PKG_CONFIG_PATH=${TOP}/ext/libpng-1.5.13/ \ LIBPNG_CFLAGS=-I${TOP}/include \ LIBPNG_LDFLAGS="-L${TOP}/libs -lpng15 -lz" \ FREETYPE_CFLAGS=-I${TOP}/include \ FREETYPE_LIBS="-L${TOP}/libs -lfreetype" \ LIBS="-lgcc_s -lgcc -ldl -lstdc++ -lz" \ CFLAGS="-march=armv7-a" \ CXXFLAGS="-march=armv7-a" \ ./configure CC=arm-linux-gnueabi-gcc CPPFLAGS=-I${TOP}/include LDFLAGS=-L${TOP}/lib \ --build=i686-linux --host=arm-linux-gnueabi \ --enable-static --disable-shared \ --disable-freetype --enable-fbdev --disable-x11 \ --with-gfxdrivers=none --with-inputdrivers=none This successfully builds, and I can compile and link a sample application based on the simple tutorial application at http://directfb.org/docs/DirectFB_Tutorials/simple.html -- unfortunately, when run on the target system, the application crashes with SIGSEGV. So too do some of the tools included with directfb, e.g. dfbinfo. Here is a stack trace of my test application crashing (when run with command line arg "--dfb:fbdev=/dev/fb0"): #0 direct_map_lookup (map=0x0, key=0xdfd70) at map.c:298 #1 0x000b2d9c in direct_config_set (name=0xdfd70 "fbdev", value=0xdfd76 "/dev/fb0") at conf.c:542 #2 0x0009edc0 in dfb_config_set (name=0xdfd70 "fbdev", value=0xdfd76 "/dev/fb0") at conf.c:2024 #3 0x000a2dcc in parse_args (args=0x7ea80d53 "fbdev=/dev/fb0") at conf.c:297 #4 0x000a305c in dfb_config_init (argc=0x7ea80968, argv=0x7ea80964) at conf.c:2159 #5 0x0000cd58 in Display::Display () #6 0x0000ba94 in main () For reference, the only directfb-related code to execute in the application prior to the crash is directly copied from the tutorial code: Display::Display(int argc, char ** argv) { DFBSurfaceDescription dsc; DFBCHECK (DirectFBInit (&argc, &argv)); // ... crash occurs during execution of the line above } This is called directly from my main function, passing the original unmodified argc and argv. I have installed the directfb libraries on the target system in /usr/local/lib and binaries in /usr/local/bin, and created /usr/local/share/directfb-1.6.2 (containing cursor.dat and decker.dgiff) as well as /etc/fb.modes as suggested in the documentation. Any suggestions as to what I've done wrong? Reading source codes for conf.c and maps.c from git.directfb.org and checking your stack... #0 direct_map_lookup (map=0x0, key=0xdfd70) at map.c:298 #1 0x000b2d9c in direct_config_set (name=0xdfd70 "fbdev", value=0xdfd76 "/dev/fb0") at conf.c:542 map is null. Which should assert at map.c:295 but looks like that's disabled but instead crashes at 298 hash = map->hash( map, key, map->ctx ); Previous call is in conf.c:542, ConfigOption *option = direct_map_lookup( config_options, name ); which means config_options was null. Searching in that file only place it gets assigned to a file is __D_conf_init(). I don't know anything about directfb, but it looks like you need to call __D_conf_init directly or indirectly. Thanks. This put me on the right track -- it appears that __D_conf_init is set up to be automatically called when libdirectfb.so is dynamically linked to the application. But I was statically linking it. Static linking is apparently supported, but you have to take special steps, and the script that used to perform those steps is apparently no longer distributed. Switch to dynamic linking, and it all worked fine.
common-pile/stackexchange_filtered
How to store CodeIgniter session data if data length likely to exceed BLOB size? I have a fairly elaborate multi-page query form. Actually, my site has several for querying different data sets. As these query parameters span multiple page requests, I rely on sessions to store the accumulated query parameters. I'm concerned that the data stored in session, when serialized, might exceed the storage capacity of the MySQL BLOB storage capacity (65,535 bytes) of the data column specified by the CodeIgniter session documentation: CREATE TABLE IF NOT EXISTS `ci_sessions` ( `id` varchar(128) NOT NULL, `ip_address` varchar(45) NOT NULL, `timestamp` int(10) unsigned DEFAULT 0 NOT NULL, `data` blob NOT NULL, KEY `ci_sessions_timestamp` (`timestamp`) ); How can I store my user-entered query parameters and be sure that they will be preserved for a given user? I considered using file-based-caching to cache this data with a key generated from the session ID: // controller method public function my_page() { // blah blah check POST for incoming query params and validate them $validated_query_params = $this->input->post(); // session library is auto-loaded // but apparently new session id generated every five mins by default? $cache_key = "query_params_for_sess_id" . $this->session->session_id; $this->load->driver('cache'); // cache for an hour $this->cache->file->save($cache_key, $validated_query_params, 3600); } However, I worry that the session ID might change when a new session ID gets generated for a given user. Apparently this happens by default every five minutes as CodeIgniter generates new session IDs to enhance security. Can anyone suggested a tried-and-true (and efficient!) means of storing session data that exceeds the 64K blob size? You could use MEDIUMBLOB, which supports up to 16MB, or LONGBLOB which supports up to 4GB. See https://dev.mysql.com/doc/refman/8.0/en/string-type-overview.html Also, if you declare your blob with a length like BLOB(2000000) (whatever is the length you need), it will automatically promote it to a data type that can hold that length of data. For example, BLOB(2000000) will implicitly become MEDIUMBLOB. mysql> create table t ( b blob(2000000) ); mysql> show create table t\G *************************** 1. row *************************** Table: tt Create Table: CREATE TABLE `tt` ( `b` mediumblob ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 Two things give me reservations about this approach: 1) my db server is a separate machine, and quite busy. This means the large-ish data would be transiting db connection over the network with every page request. 2) Might there be any speed concerns with MEDIUMBLOB? I understand from other posts that disk storage appears to be efficient, without too much overhead, but is there any speed difference or other issues I should be worried about? I also appreciate your tip to use BLOB(2000000) -- would this impose an upper limit to the amount of data stored? Or would MySQL just create a MEDIUMBLOB column which truncates at 16MB? It just makes a mediumblob, the minimum data type needed to store at least 2M bytes. The mediumblob still allows its regular max length, up to 16MB.
common-pile/stackexchange_filtered
Purpose of divide-by-2 (or CLK/2) on a video pixel clock generator ICs I've been looking into some video clock generator chips and almost all of them have a divide-by-2 or CLK/2 output pin (in addition to the normal CLK out). What would be the purpose or application for such a pin? I would think a multiplier would be more handy, especially for up-scaling video designs. Sample from Datasheet: Another chip sample: It looks like there's a couple of reasons. From the MC44145 datasheet: First off is to adjust the clock to a better range for the VCO that drives the pixel clock PLL so that the VCO control voltage stays within a usable range. The other reason is to provide a square wave with a 50% duty cycle for the pixel genetator.
common-pile/stackexchange_filtered
Expected number of attemps to succeed Suppose there are five levels $\{1,2,3,4,5\}$. Let $P_s(i)$ denote the probability of success on level $i$ and $P_f(i) = 1 - P_s(i)$ the probability of failure on level $i$. If you succeed on level $i$ you proceed to level $i + 1$; if you fail you go down to level $i - 1$ (unless you are at level $1$, in which case you stay) I am trying to figure out the expected number of attempts I would need to get from level $4$ to $5$. I know that the result should be some kind of recursion but all I could come up with was $E_{5} = 1 \cdot P_s(4) + E_{4} \cdot P_f(4)$ where $E_{i+1}$ is the expected number of attempts to get to level $i+1$ from level $i$, and $E_{4} = 1 \cdot P_s(3) + E_{3} \cdot P_f(3)$ and so on. I know this isn't correct because the expected number of attempts should increase as $P_s(4)$ goes down Any help on how to figure this out would be appreciated I take it that the probabilities of success/failure at each step are known (except you can't fail at step $1$) On this assumption and simplifying notation, denoting the probability of success/failure at each step $i$ as $p_i, (1-p_i)$, and letting $S1, S2,$ etc represent being at step $1,2$ etc, we get the following step by step equations. $S4= 1 + (1-p_4)(S3) \tag1$ $S3= 1 + p_3(S4) + (1-p_3)(S2) \tag2$ $S2= 1 + p_2(S3) + (1-p_2)(S1) \tag3$ $S1= 1 + p_1(S2) + (1-p_1)(S1) \tag4$ Solve the system of linear equations for $S4$
common-pile/stackexchange_filtered
Kasparov said human+computer beats just computer. What does human bring to the table in such teams? Its seems to me nowadays computers simply play better, i.e. they consistently choose better moves. Where does human factor come into play, how can a human help engine to beat another engine? Or was Kasparov simply wrong? Edit: here's the podcast, most of it is politics, chess part is near the very end https://www.samharris.org/podcast/item/the-putin-question My guess is that a computer thinks logically, and just calculates the best move coming, but a human person would be able to "see" any "possibility" of a tactic being pulled off... Positional understanding I seem to remember matches human+computer vs human+computer, but did anybody actually try human + computer vs computer only? @bof december 2016, I edited in the link Some good answers. Let me add the following article, which illustrates one legal chess position in which the human mind is better than any computer. While such positions seem very contrived and artificial, although legal, their study might lead to an answer to your question. http://www.telegraph.co.uk/science/2017/03/14/can-solve-chess-problem-holds-key-human-consciousness/ My guess is Kasparov is still hurt by his loss to Deep Blue and wants to find some way humans can still be relevant to chess ;) Experienced human correspondence chess players with a strong chess engine definitely play better chess than just the engine itself. If you think about it, the human player could always simply follow the engine moves without any thinking. However, you're not going to win the world correspondence title if you don't do your own analysis. You have an engine, but your opponent also have an engine! You just can't win a game unless you guide the engine. A strong International Correspondence Chess Grandmaster know how to analyze a chess position with a chess engine. They can make a move on a board, and evaluate the new positions again with the engine. There is no way the engine by itself can beat this human+engine perfect combination - tactics + long-term strategic thinking. Human can make some moves on the board, that simplifies the search process (searching at depth x is not equivalent to x+1) Human understands drawn endgames. They can guide the engine not to choose a line that wins a pawn but draw 50 moves later in a rook ending Human can try the engine lines, play some training games, test the new positions etc. Chess engines can't do that by itself! This has been tested in 2014. A strong version of Stockfish (ELO 3200) was pitted against Nakamura (2800) with an early version of Rybka (3000) to help him. The Rybkamura team lost. https://www.chess.com/news/view/stockfish-outlasts-nakamura-3634 This is evidence against Kasparov's claim. The match shows that Nakamura + Rybka was weaker than Stockfish, but how does it prove that Nakamura + Rybka was not stronger than unaided Rybka? @bof, no it doesn't. That's why I used "evidence", not "proof" Keep in mind that Elo isn't an absolute number. It makes little sense listing the Elo of an engine that got its rating playing other engines alongside a human's Elo that they got playing primarily top humans. To see this, imagine if there were some ultra genius 6 year old. Maybe, he plays at the level of a decent IM, but his rating, against other young children, might be 3500 Elo. Despite this tremendous number, he would lose more often than win against adult grandmasters. Basically, Elo comparisons can only be done if the two players got their ratings against the same population. The general thought is that computers still have problems with calculating long-term plans and positional considerations correctly. There are many examples of modern computers getting "confused" in closed positions where long-term planning is worth more than brute force thinking. Many have a contempt factor which forces them to make a poor move rather than accept a draw against a weaker opponent. Nakamura has exploited this algorithm in many famous games. For positional considerations, the reason for this weakness is the rarity of possibilities. Except for some lines in the Ruy Lopez, Alekhine, and the Caro-Kann, capturing toward the center is the norm. There are exceptions where capturing away from the center is better, mostly for attacking purposes. Programming in the exceptions would cause an increase in the size of the program and slow down the speed. However the computer does search far enough ahead the this is becoming less of a concern. Are you missing a "not" in your first sentence? Corrected first sentence. If you follow engine tournaments, you'll find that although computers are very strong, there are still times when they do the most stupid of things. Here's an example from the most recent TCEC superfinal between Stockfish and AllieStein. [FEN "2b1r3/6r1/p2p1k1p/Pp1PpP1P/1Pp2pP1/2P2P2/1K2R1B1/3R4 w - - 23 149"] [White "Stockfish"] [Black "AllieStein"] Try analyzing the position yourself before looking at what the engines say. What would you give this position? If you said 0.00, I completely agree with you. After all, White can't make progress - all the pawns are firmly wedged. The only thing White can do is play g5, but that's just going to lose several pawns. Meanwhile Black is just as stuck. White can easily defend the pawn on d5. The only pawn break Black has is ...e4, but that will actually lose the game by not just throwing a pawn, but also opening lines for White to make inroads. However, if you look at the engine evals, Stockfish gave +0.90, and AllieStein gave -0.50. If you look at the charts of how the evals vary, you'll see they're straight horizontal lines (at least Stockfish's is - AllieStein, being a neural network engine, has a less consistent but still mostly horizontal eval). This is what computer chess viewers derogatorily call "horizone". The engines aren't smart enough to realize they're not making progress. They will happily shuffle until the 50-move rule helps them realize that it's a draw. This kind of fortress situation is quite common, but can be avoided. If you're a human piloting Stockfish, you can see this fortress come up several moves before, realize that Stockfish is heading into a horizone, and choose a different move that keeps some winning chances in the position. But that's not all humans can contribute! As it turns out, AllieStein spotted an ingenious way to make progress. Check out what happened 15 moves later. By this time, Stockfish had realized it wasn't making progress, and its eval had dropped to +0.38. Meanwhile AllieStein's eval had increased to -0.79. And then there happened ... [FEN "2b3r1/8/p2p3p/Pp1PpPrP/1Pp1RpP1/2P2Pk1/2K5/3R1B2 w - - 53 164"] [White "Stockfish"] [Black "AllieStein"] 1. Ree1 Kxf3 What kind of fanatic plays 164...Kxf3? Is AllieStein insane? Who the hell ventures into enemy territory with a lone king to grab pawns anyway? Black can't even back off through g5 because the square is currently blocked. If you're a human piloting AllieStein, you'd immediately realize this is a pivotal moment. Either AllieStein is seeing something profound, or it's making a huge blunder. Before actually making the move, you'd try out variations to see what might happen. You might not be strong enough to tell yourself, but AllieStein is sufficiently powerful to tell that within a few moves Black's so-called advantage has cratered. After 164...Kxf3 165. Be2+, Black is dangerously close to being checkmated. 165...Ke3 166. Rf1 threatens Rf3+, Re1 and Bd1 checkmate. Black is forced to take desperate measures like ...Bxf5, after which his position collapses. AllieStein on its own didn't see this, and lost this game. But human + AllieStein is likely to have avoided this. This is just an example of the more obvious ways a human can contribute. Correspondence players will be able to say more, since they get familiar with their engine's strengths & weaknesses, and feed their engine ideas on how to get to their strongest positions while avoiding the opponent's. From what I've gathered talking to correspondence players, the odds are that they will draw against someone playing only engine moves (since chess is a draw after all), but they won't lose either, and they will score wins. That's where humans can contribute.
common-pile/stackexchange_filtered
copy 1d char* array as a row into 2d char* array (memcpy C behaviour in loop) in the code below, I want to be able to input using stdin bash commands separated by new lines, and execute them sequentially using forks and execvp. right now, my code takes the line, tokenises it (for argument's sake) and then appends it to a char* array called cmd. I then want to add this to cmdList as a row. However, every time I try with memcpy, it doesn't output my expected behaviour, and I was hoping that someone could help explain and point me in the right direction thanks. Full codebase is below. currently as it is, I am testing using ./sequence < cmdfile, where command file contains these lines. sequence.c currently outputs only the date. cmdfile whoami cal 4 2020 echo The time is: date sequence.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <sysexits.h> #define MAX_ARGS 10 #define MAX_LINE 256 #define MAX_COMMANDS 100 int main() { int cmdSize; char line[MAX_LINE]; char* cmdList[MAX_COMMANDS][MAX_ARGS + 1]; //read 100 lines for(int i = 0; i < MAX_COMMANDS; i++) { cmdSize = 0; //reset cmdSize every iter fgets(line, MAX_LINE, stdin); //read line from stdin if(line[0] == 10) { break; } line[strcspn(line,"\n")] = 0; //strip \n from back of lines so that the commands are clean char* token = strtok(line, " "); char* cmd[11] = {}; while(token) { cmd[cmdSize] = token; //cmdList[i][cmdSize] = token; cmdSize++; token = strtok(NULL, " "); }//tokenise and add to cmd arr memcpy(cmdList[i], cmd, sizeof(cmd)); } printf("%s, ", cmdList[0][0]); printf("%s, ", cmdList[1][0]); printf("%s, ", cmdList[2][0]); //start of forks, broken right now for (int i = 0; i<cmdSize; i++) { //forks int fid; fid = fork(); if (fid < 0) { perror("fork error"); exit(EXIT_FAILURE); } else if (fid == 0) { execvp(cmdList[i][0], cmdList[i]); //execute on child perror("Exec error"); exit(EXIT_FAILURE); return 0; } else { wait(NULL); // wait until child is finished } } return 0; } tried appending to the 2d array using a loop, did not work, same behaviour Please provide a [mre] (ideally with hardcoded input) to demonstrate what you observe, but also describe what exactly you do observe and what exactly you do expect and explicitly what difference you see. Try for [ask] and consider taking the [tour] please. Don't use magic numbers. If by the value 10 in line[0] == 10 mean the ASCII value for newline, use the actual characters '\n' instead. The problem is that all the calls to strtok will always give you pointers into the one single line array. And each iteration of the outer for loop will "reset" the contents of the line array, so all the pointers you store in cmdList will be to different places in the line array which will always have the contents of the last successful call to fgets You need to to actually copy the strings, and not the pointers. Or use dynamic allocation with e.g. strdup (or your own implementation if your system doesn't have it). cmd[cmdSize] = token; is a shallow copy. It only copies the pointers, and not the underlying data. You need to actually copy the underlying data, else you'd end up with all the pointers pointing inside a single line array, which will have the contents of the most recent fgets() call. As you're already assuming POSIX support, it is simple: cmd[cmdSize] = strdup(token); if (!cmd[cmdSize]) { /* Memory allocation failed. Handle error here. */ } Also note that char* cmd[11] = {}; is not valid before C2X, unless you're using GNU extensions. And instead of comparing the ASCII code, use the actual character: #if 0 if(line[0] == 10) { break; } #else if (line[0] == '\n') { break; } Hi, using c99 it compiles. However if char* cmd[11] = {}; is not valid, what would an alternative be? Thank you in advance! Did you compile with std=c99 -pedantic-errors? The alternative is char *cmd[11] = {0}. For me, GCC outputs: "error: ISO C forbids empty initializer braces before C2X."
common-pile/stackexchange_filtered
Using node or draw circle in tikz-3dplot I am exploring the tikz-3dplot package for drawing objects in 3d and experienced a problem. I simply want to draw a circle and reference some of the points later, but I found there is a difference when using the draw command and using the node command: \documentclass[tikz]{standalone} \usepackage{tikz} \usepackage{tikz-3dplot} \begin{document} \tdplotsetmaincoords{70}{110} \begin{tikzpicture}[tdplot_main_coords] \draw[thick,->] (0,0,0) -- (1,0,0) node[anchor=north east]{$x$}; \draw[thick,->] (0,0,0) -- (0,1,0) node[anchor=north west]{$y$}; \draw[thick,->] (0,0,0) -- (0,0,1) node[anchor=south]{$z$}; \coordinate (O) at (0,0,0); \tdplotsetcoord{P}{1}{70}{40} \draw[-stealth,color=blue] (O) -- (P); \node[draw, circle, radius=0.2] (cir) at (P) {}; \draw[red] (P) circle [radius=0.2]; \draw (cir.south) -- (cir.north); \end{tikzpicture}% \end{document} Why is the difference? I would like to use node as I can reference, for example, the south and north points for later use, probably projection. But using node doesn't provide the right shape (I want the red circle to be drawn with node so I can reference it). I don't understand why the node is not using the tdplot_main_coords coordinate system. Thanks. node almost always draws on the 2d canvas; it is not aware of the 3d coordinate system provided by tdplot_main_coords. If you want to refer to a particular point on a circle just hard-code the coordinate. @marmot I wonder how .south etc works in that case.
common-pile/stackexchange_filtered
Algebra Question: order of calculation I watched an instructor write this question 3(x-7)=6, he then solved the Parentheses to get 3x-21=6, but here is where I was lost, he then added 21 on each side to get 3x=27, then divided each side by 3 to get x=9. Now, I always thought you you did everything in this order: Parentheses, Exponents, multiply/divide, then add/ subtract...but when I do this to this question, I got x-21=2, then x=23...can someone explain why he added/subtracted, before multiplied/divided, when trying to find the value of 'x'? nvm, I see what I did wrong...I forgot to divide the 21 :/ The order you are referring to has nothing to do with what you are doing here. When modifying equations or, if you prefer, when simplifying/solving equations you must do the same operation on both sides - always. Dividing the initial equation $3(x-7) = 6$ by $3$ on both sides could be considered an even faster way of solving for the $x$. Consider also the (silly) example $a(x-1) -1 = -1$ where adding $1$ on both sides as the first operation gives the solution immediately. You always follow the order of operations when evaluating an expression. When solving an equation (i.e. or unraveling an evaluation of an expression) we need to reverse the order of operations. To solve the equation $3(x - 7) = 6$, we must isolate $x$. There are various options. Method 1: Your instructor's method. \begin{align*} 3(x - 7) & = 6\\ 3x - 21 & = 6 && \text{apply the distributive law}\\ 3x & = 27 && \text{add $21$ to each side of the equation}\\ x & = 9 && \text{divide each side of the equation by $3$} \end{align*} Method 2: A corrected version of your attempt. \begin{align*} 3(x - 7) & = 6\\ 3x - 21 & = 6 && \text{apply the distributive law}\\ x - 7 & = 2 && \text{divide each side of the equation by $3$}\\ x & = 9 && \text{add $9$ to each side of the equation} \end{align*} As you realized, you failed to divide $21$ by $3$. Method 3: A simpler method that eliminates the need to apply the distributive law. \begin{align*} 3(x - 7) & = 6\\ x - 7 & = 2 && \text{divide each side of the equation by $3$}\\ x & = 9 && \text{add $7$ to each side of the equation} \end{align*} If you compare methods 2 and 3, you can see that applying the distributive law first introduces an extra step and, with it, extra opportunities to make an error. Notice that $$\frac{3x - 21}{3} = \frac{3(x - 7)}{3} = x - 7$$ Note that division by $3$ is multiplication by $1/3$. With this in mind, we see that the reason you had to divide $21$ by $3$ is the distributive law $a(b - c) = ab - ac$. $$\frac{3x - 21}{3} = \frac{1}{3}(3x - 21) = \frac{1}{3}(3x) - \frac{1}{3}(21) = x - 7$$ with $a = 1/3$, $b = 3x$, and $c = 21$. Finally, we apply the order of operations to evaluate numerical expressions. Check: If $x = 9$, then \begin{align*} 3(x - 7) & = 3(9 - 7) && \text{substitute $9$ for $x$}\\ & = 3(2) && \text{perform the operation in parentheses}\\ & = 6 && \text{multiply} \end{align*} so the solution $x = 9$ is correct.
common-pile/stackexchange_filtered
Keepalived configuration for a budget cluster of 2 web server nodes on Linode I am on a low budget - so I am running just 2 identical Linodes (Ubuntu 18.x). I don't plan to use Nodebalancer, since I need only one server to be up at a time. I have been able to successfully configure gluster and galera. Now it is time for keepalived. This is the configuration I came up with. Could someone please validate to confirm this is correct? Is it correct to use public ip of the two Linodes under unicast_peer and unicast_server_ip? Also I am not sure what to define in virtual_ipaddress MASTER: ! Configuration File for keepalived global_defs { notification_email { } router_id LVS_DBCLUSTER } vrrp_script chk_nginx { script "pidof nginx" interval 2 } vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 101 track_interface { eth0 } track_script { chk_nginx } authentication { auth_type PASS auth_pass example_password } unicast_src_ip <master-server-public-ip, sharing enabled> unicast_peer { <secondary-server-public-ip> } virtual_ipaddress { <i am not sure what IP comes here> } notify_master "/bin/echo 'now master' > /tmp/keepalived.state" notify_backup "/bin/echo 'now backup' > /tmp/keepalived.state" notify_fault "/bin/echo 'now fault' > /tmp/keepalived.state" } SLAVE: ! Configuration File for keepalived global_defs { notification_email { } router_id LVS_DBCLUSTER } vrrp_script chk_nginx { script "pidof nginx" interval 2 } vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 101 track_interface { eth0 } track_script { chk_nginx } authentication { auth_type PASS auth_pass example_password } unicast_src_ip <secondary-server-public-ip, sharing NOT enabled> unicast_peer { <master-server-public-ip> } virtual_ipaddress { <i am not sure what IP comes here> } notify_master "/bin/echo 'now master' > /tmp/keepalived.state" notify_backup "/bin/echo 'now backup' > /tmp/keepalived.state" notify_fault "/bin/echo 'now fault' > /tmp/keepalived.state" } I did a trial and error on this and finally both my servers became inaccessible among each. So I had to rebuild the servers. I would like a keepalived + linode expert to suggest.
common-pile/stackexchange_filtered
Find source of failed mysql logins I've been seeing the following log entry in /var/log/mysqld.log and am trying to pinpoint the source of the request: 130313 10:10:48 [Warning] Access denied for user 'admin'@'localhost' (using password: YES) This started on Monday evening right on 8pm and continued until last night at 23:59:57, once every minute (roughly). I thought that was the end of it until it started back up again this morning at 10:00:03, again, every minute. I am running CentOS 5.9 X64 with Plesk 11 and Atomicorp's ASL security system. I have went through all Cron tasks, none start at 8pm nor 10am and the only hourly ones are run through PHP and don't use admin as the login. I have also, one by one, disabled services to try to figure it out, the following didn't make a difference when off: httpd xinetd sshd psmon named crond couriercpd postfix I have also enabled verbose logging with mySQL using the General Query Log, but it doesn't show anything of use. Can anyone suggest a way of tracking down the source of these attempted logins? Or even to show the password the system is trying to connect with? That way, I can figure out if it is friend or foe. Thanks Apparently, since the source of the connection is made through a socket, neither mySQL or any Linux Kernel can identify the source. I'm now working with Atomicorp (www.atomicorp.com) as they are developing a kernel patch which will allow this to be traced in the future.
common-pile/stackexchange_filtered
PIC microcontroller: actual behaviour differs from simulator I was encountering some quite strange differences in the behaviours of my PIC16F628a microcontroller compared to the MPLAP built-in simulator. After a long search, it turned out to be different due to the free cells' default values. In the simulator, when accessing a memory location that has not been initialized, the W register is loaded with 0x00, whereas in the actual device, some other value may be loaded (I don't remember if it was 0xFF or 0x7F). Is there a way to either make all unused bytes 0x00 on the device or to change the default value of the simulator to the PIC's uninitialized default value? (It might also be that my question shows that I didn't understand some fundamental principles about PICs... In this case I would be grateful if someone would teach me. ;-) ) If you are programming in C, that would be a C question. It has very clear definitions, when the memory is initialized, to which values and when it is not. Oh, sorry. I missed that one. I am programming in Assembler. Even in this case, your program should not rely on default memory content. You should initialize it explicitly (unless it is some flash memory, which is known to have specific values when "erased".) I know that. I guess that I have some kind of "memory leak" in my program. But it is difficult to find if the program always runs fine in the simulator but does not on the actual device. Device does not allow debugging. So it would be great if I could fully simulate the device - including the empty memory locations. write a small program to do a memory dump to the serial port .... run it several times to see if the memory content is random .... copy the data to the simulator memory if that is possible You can always fill the simulator memory with nonzero values before running your code. For example, make sure every location contains 0x55 -- if you see this value appearing in any of your CPU registers during the simulation, that means that you forgot to initialize the corresponding memory. My standard 16F PIC-family startup code specifically initializes all lower-bank data memory to 0x00. This is a hangover from when I was first learning to program PIC microcontrollers but I consider this to be good programming practice and the code stays in all of my projects. The code required to do this zeroing of the data memory is different for each PIC variant. But it's a simple loop and occupies very little code space. The newer 16F PICs have much more data memory than the legacy parts that I still work with. I zero-out only the first one or two lowest banks of data memory. Add a comment if you would like me to post the code that I use for the various PICs that I use. All that said: I consider it to be bad programming practice to make a decision based upon a reading a data location that has not been initialized to some specific value by your program. This is a common cause of programming errors. @Eugene: awesome mind reading! I was in the process of editing my answer to say exactly that! You are absolutely sure! But I'm not reading the uninitialized memory by intention. I guess there's a loop which reads too much memory in certain cases or it reads memory from the wrong bank or so... But your suggestion to initialize all the memory at the very beginning is probably the best solution here... I suppose it may not be possible to consistently emulate uninitialized memory content in the simulator, since the said content may change from part to part, or even for the same part under different conditions like supply voltage or temperature.
common-pile/stackexchange_filtered
generating a set of sets that appear in every set I have an array of arrays of things typedef std::vector<thing> group; std::vector<group> groups; things could be compared like so int comparison(thing a, thing b); where the return value is 0, 1 or 2 0 means that the things are not alike 1 means that they are alike and a is more specific or equal to b 2 means that they are alike and b is more specific or equal to a and I am looking for a function that would return me a group that contains all things that appear in every group. std::getgroup(groups.begin(), groups.end(), myComparisonFunction); the problem is I have no idea what this function may be called, if it does even exist, or what the closest thing to it would be. You mean a function to return every thing of std::vector<std::vector<thing>> into a single std::vector<thing>? so if a thing appears inside all the groups then it will be added to the group that getgroup returns 2 downvotes so far, i don't mind but if you are downvoting because the question is confusing please say something because i can and will edit it I haven't downvoted yet, but I suspect that not showing any code of what you tried so far is a big part of it. Why is a group a vector rather than an unordered_set ? i used set in the title because i was trying to make the title concise but that may have been an error - you should be able to use any iterable container @ChatterOne the problem is I was looking for a function in the standard library that did something like this or a response like 'this doesn't exist' Again - Why is a group a vector rather than an unordered_set ? In my opinion you should at least add the code which describes the thing element. I think the function you want to create depends on that. Eventually, what you want is an intersection. Luckily, there is std::set_intersection which almost does what you need. Here's a simple example on std::vector<std::vector<int>>. You can easily change it to work with your thing: #include <iostream> #include <vector> #include <algorithm> std::vector<int> getGroup(const std::vector<std::vector<int>>& groups) { std::vector<int> group; std::vector<int> temp = groups[0]; std::sort(temp.begin(), temp.end()); for ( unsigned i = 1; i < groups.size(); ++i ) { group = std::vector<int>(); std::vector<int> temp2 = groups[i]; std::sort(temp2.begin(), temp2.end()); std::set_intersection(temp2.begin(), temp2.end(), temp.begin(), temp.end(), std::back_inserter(group)); temp = group; } return group; } int main() { std::vector<std::vector<int>> groups = { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 2, 3, 5, 6, 7, 8, 10}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 3, 4, 5, 6, 9, 10}, {1, 2, 6, 7, 8, 9, 10}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} }; for ( auto g : getGroup(groups) ) std::cout << g << "\n"; return 0; } This will print: 1 6 10 std::set_intersection expects that its argument ranges are sorted. The problem is say thing a has value of apple and thing b has value of fruit and both are in separate groups. Then I want to be given a group with apple in it, since it is a fruit and an apple so it appears in both groups. Not sure how to do this in the comparison function @xskxzr Sorry, totally forgot that detail :P I just fixed it.
common-pile/stackexchange_filtered
Subcategories not displaying in select menu I have been messing around with subcategories and created a database new categories for testing purposes. Table newcategories category_id (int) AUTO name (varchar) NOT NULL parent (int) NULL category_desc (text) NULL sort_order (int) NOT NULL I entered some categories and subcategories into the db but I have been having issues when trying to display main categories with corresponding sub categories in a select menu. <?php // // // query database to return all existing main categories $selectMainCat='SELECT * FROM newcategories WHERE parent is NULL ORDER BY sort_order ASC'; $smc=$conn->query($selectMainCat); while($rowsmc = $smc->fetch_assoc()) { $parent_id = $rowsmc['category_id']; ?> <optgroup label="<?php echo "{$rowsmc['name']}";?>"> <option value="<?php echo"{$rowsmc['category_id']}"; ?>" <?php if (isset($catID) && $catID=="{$rowsmc['category_id']}") echo "selected"; ?> > <?php echo "{$rowsmc['name']}";?></option> <?php // // // query database to return all sub categories $selectSubCat='SELECT * FROM newcategories WHERE parent = "$parent_id" '; $ssc=$conn->query($selectSubCat); while($rowssc = $ssc->fetch_assoc()){ ?> <option value="<?php echo"{$rowssc['category_id']}"; ?>" <?php if (isset($catID) && $catID=="{$rowssc['category_id']}") echo "selected"; ?> > <?php echo "{$rowssc['name']}";?></option> <?php } ?> </optgroup> <?php } ?> Below is what I have entered into the db category_id name parent category_desc sort_order 1 Fruits NULL NULL 1 2 Vegetables NULL NULL 2 3 Apple 1 NULL 1 4 Arugula 2 NULL 1 5 Cabbage 2 NULL 2 6 Honeycrisp 3 NULL 1 7 Braeburn 3 NULL 2 HTML OUTPUT <select class="form-control m-b" name="catID" id="catID"> <option value="" disabled selected> Select Main Category</option> <option value="" disabled></option> <optgroup label="Fruits"> <option value="1" >Fruits</option> </optgroup> <optgroup label="Vegetables"> <option value="2" >Vegetables</option> </optgroup> </select> How can we be sure that you have set the subcategories up correctly in the database WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST or $_GET data directly into a query, it can be very harmful if someone seeks to exploit your mistake. Have you looked a the page source in your browser to see if this mess has caused some duff HTML to be generated, because I would say it probably has @tadman I am not using $_POST or $_GET @RiggsFolly not to concerned about the html output at this moment. Well you should be as it looks like you might be outputing ??something for subcategories?? but if the HTML is invalid it is likely not showing up in the page You can see my html output above. @user3354780 At some point you're taking in user data. $parent_id should not be in the query, that should be a placeholder. That will also fix the problem where you're literally inserting "$parent_id". The problem you have here is the value is not being interpolated correctly since you're using the non-interpolating quotes. This can be fixed by doing the query correctly using placeholder values: $ssc = $conn->prepare('SELECT * FROM newcategories WHERE parent=?'); $ssc->bind_param('i', $parent_id); $result = $ssc->execute(); while ($rowssc = $result->fetch_assoc()) { ... } It's extremely risky to put data of any kind directly in a query, especially something that comes directly from the user via $_GET, $_POST or $_REQUEST. Even $_COOKIE and $_SESSION can be trouble since these may contain values previously supplied by a user, or which a user has some degree of control over.
common-pile/stackexchange_filtered
Who can I complain to about MS Product activation service Ok, I'm fuming after having to deal with a MS Support Rep to do a product activation; and now I need to complain to someone. Has anyone found an actual phone number or e-mail address at Microsoft I can complain too? All I can find is their support pages and the feed back forms for specific support pages. I figure if that PC-bimbo on the Windows 7 ad can convince MS to build Windows 7 for her, they must be able to straighten out their support people for me :-/ This is a) not sysadmin related b) not a real question c) should be CW a) When I'm having problems activating the OS on a server, it is SA related b) definitely real, c) It would be CW only if I was looking for discussion... I was looking for a fact. Is it the fact that you had to deal with somebody to do the activation, or something that happened over the course of the call that has you fuming? If the former, I'm sorry but the answer is "live with it". If the latter, the person's manager will soon catch them giving bad customer service (yes, MS do care about customer service) and the inevitable consequences will follow. Either way, voting to close. "We're Microsoft. We don't have to care." Wasn't that Bell's line? I think the parallels are pretty clear... Call back into the Activation number, and punch in a bunch of bogus numbers to get to a person (or just sit there and ignore the prompts). When a person comes on the line, tell them that you have an issue you need to speak with a supervisor about. Unfortunately without the name of the person there's probably not much they can do, but you can vent to them, and they can and will send it up the chain. The only way to make your complaints really heard is the get involved in the MS blogging and beta testing community. I truly believe this is the only real way of getting your voice heard by the actual developers of the software. Calling/Email "Bob" in Mumbai isn't going to go anywhere. Actually, it's "Bob" in Mumbai that is the problem. And his boss likely also lives there... You can try one of their Customer Service Solution Centers: http://support.microsoft.com/contactus/cu_inventory?ws=mscom But it's probably analogous to shouting into the wind or relieving yourself in the ocean. been there... no phone number or e-mail. Unlikely to get anything changed. If you talk to an unhelpful support person, best thing is simply to hang up and try someone else. If they mention it then you can always say that you were cut off.
common-pile/stackexchange_filtered
How to open separate command prompt consoles for two seperate CreateProcess() API calls I've a caller.EXE from within which I do 2 calls of "CreateProcess() APIs like this. Both the CReateProcess() APIs are trying to launch console application EXEs. Caller.cpp (Caller.EXE) has teh following code in it:: ................... .................. CReateProcess( Callee_1) // For launching a console EXE which starts running in the same CMD prompt window where I've the main "CAller.EXE" running. .............. <Few lines of C++ logic> ........ CReateProcess(Callee_2) // For launching another console EXE . Now the problem is that I want the 2nd CreateProcess(Callee_2) call to actually launch a different command prompt but what is happening here is that the 2nd CreateProcess(Callee_2) call is not launching anotehr CMD prompt. The same CMD prompt is execiting the Callee_1 in it. I see that in my Caller code CreateProcess() is successful for both the times. I want the 2nd CreateProcess(Callee_2) call to actually launch a different command prompt. How do I achieve that? I think I should give it as part of the input parameters to CreatyeProcess(Callee_2) call. how is this tagged c? It's not really clear to me what you want to accomplish, do you want to actually launch cmd.exe? Or do you just want the system to open a window for you for the standard output of the new process? Both the CReateProcess() APIs calls are trying to launch console application EXEs. Hence I want 2 different CMD consoels open where bothe "Callee_1 & Callee_2" would dump their console outputs in 2 separate CMD prompts (Consoles). I'm not very knowledgeable about Windows or MSDN, but as far as I remember, CReateProcess( Callee_1) which should actually be CreateProcess(), taken one parameter DWORD fdwCreate , where, CREATE_NEW_CONSOLE can be used to specify that the new process should have a new console, instead of inheriting the parent's console. Maybe this link is helpful to you. I observe inconsistent behavior with CREATE_NEW_CONSOLE. If I use it in 1st CreateProcess(Callee_1) it does create a new console but it doesn't in the 2nd CreateProcess(CAllee_2) call ? Is there any limit on the no: of consoles that can be opened ? @codeLover as I told, i'm not much knowledgeable in this, so I'm not sure, but this might help you.
common-pile/stackexchange_filtered
Hangman game image javascript only How do I implement these images each time player failed to guess a letter and where should I put it at? When player failed to guess 1 letter, hangman 1 will display, then followed with hangman 2 then hangman 3 and so on? Here is my code. images is in the console.log /* hangman 1 console.log(" _|_\n| |_____\n| |\n|_________|"); hangman 2 console.log(" _____\n | |\n |\n |\n _|_\n| |_____\n| |\n|_________|\n"); hangman 3 console.log(" _____\n | |\n | o\n | | \n _|_ \ \n| |_____\n| |\n|_________|\n"); hangman 4 console.log(" _____\n | |\n | o\n | /|\\ \n _|_ \ \n| |_____\n| |\n|_________|\n"); hangman 5 console.log(" _____\n | |\n | o\n | /|\\ \n _|_ / \\ \n| |_____\n| |\n|_________|\n"); */ // Show player their progress | .join returned answer as a string while (remainingLetters > 0 && lives > 0) { (answerArray.join("")); guess = readline.question(name + "'s guess (Enter 9 for lifelines or 0 to pass): "); guess = guess.toUpperCase(); //if guess is more than 1 letter or no letter, alert player to guess 1 letter only if (guess.length !== 1) { console.log("Please enter 1 letter only."); } //if valid guess else { if (guesses.includes(guess)) { console.log("\nYou have already made this guess, please try another letter!\n"); } else { guesses.push(guess); correctGuess = 0; for (var j = 0; j < Word.length; j++) { if (Word[j] == guess) { answerArray[j] = guess; remainingLetters--; correctGuess = 1; } } if (correctGuess == 1) { console.log("\nGood job! " + guess + " is one of the letters!\n"); console.log(JSON.stringify(answerArray) + "\n"); console.log(JSON.stringify(alphabets) + "\n"); } else { lives -= 1; console.log("\nSorry. " + guess + " is not a part of the word.\n"); console.log(JSON.stringify(answerArray) + "\n"); console.log(JSON.stringify(alphabets) + "\n"); console.log("You have " + lives + " lives remaining.\n"); } } } if (remainingLetters == 0) { console.log("Congratulation! You managed to guess the word!\n"); break; } if (lives == 0) { console.log("Game Over... You failed to guess the word. The word is " + Word + ".\n") } } where should I put it at? you could have some element something like div. What I would suggest is storing your various graphics in an array, and storing an index to which is the current graphics - start at zero. Every time the user gets a wrong answer, you console.log the current index and then increment the index: console.log(graphicsArray[graphicsIndex++]); There is a demo of this below, using a button press to simulate a wrong answer. try it out. var graphicsArray = []; graphicsArray.push(" _|_\n| |_____\n| |\n|_________|"); graphicsArray.push(" _____\n | |\n |\n |\n _|_\n| |_____\n| |\n|_________|\n"); graphicsArray.push(" _____\n | |\n | o\n | | \n _|_ \ \n| |_____\n| |\n|_________|\n"); graphicsArray.push(" _____\n | |\n | o\n | /|\\ \n _|_ \ \n| |_____\n| |\n|_________|\n"); graphicsArray.push(" _____\n | |\n | o\n | /|\\ \n _|_ / \\ \n| |_____\n| |\n|_________|\n"); var graphicsIndex = 0; document.querySelector("#demo").onclick = () => { console.log(graphicsArray[graphicsIndex++]); } <button id="demo">press me</button> You would do this in the part of your code which decrements the number of lives. // ... // if (correctGuess == 1) { console.log("\nGood job! " + guess + " is one of the letters!\n"); console.log(JSON.stringify(answerArray) + "\n"); console.log(JSON.stringify(alphabets) + "\n"); } else { lives -= 1; console.log("\nSorry. " + guess + " is not a part of the word.\n"); console.log(JSON.stringify(answerArray) + "\n"); console.log(JSON.stringify(alphabets) + "\n"); console.log("You have " + lives + " lives remaining.\n"); console.log(graphicsArray[graphicsIndex++]); } // ... // I am using javascript only, there won't be html included. @Heheh know that. I was just demonstrating using html. Read the last line of this answer. I have made the answer even clearer yep it works! Thank you so much! Sorry, didn't see your answer at the last line before commenting. Use a Generator ! To better understand what a generator is you can go here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* /* This function generates your images */ function* hangmanGenerator() { yield console.log(" _|_\n| |_____\n| |\n|_________|"); yield console.log(" _____\n | |\n |\n |\n _|_\n| |_____\n| |\n|_________|\n"); yield console.log(" _____\n | |\n | o\n | | \n _|_ \ \n| |_____\n| |\n|_________|\n"); yield console.log(" _____\n | |\n | o\n | /|\\ \n _|_ \ \n| |_____\n| |\n|_________|\n"); yield console.log(" _____\n | |\n | o\n | /|\\ \n _|_ / \\ \n| |_____\n| |\n|_________|\n"); } /* This is the istance of your image generator */ const generator = hangmanGenerator(); /* This is how you get the images out of your generator */ generator.next().value /* Hangman 1*/ generator.next().value /* Hangman 2*/ generator.next().value /* Hangman 3*/ generator.next().value /* Hangman 4*/ generator.next().value /* Hangman 5*/ generator.next().value /* No value because you're out of yields -> game over */ Your code should look like this: //Your code... //The function definition can go wherever you want in your code as long as it's before the while loop function* hangmanGenerator() { yield console.log(" _|_\n| |_____\n| |\n|_________|"); yield console.log(" _____\n | |\n |\n |\n _|_\n| |_____\n| |\n|_________|\n"); yield console.log(" _____\n | |\n | o\n | | \n _|_ \ \n| |_____\n| |\n|_________|\n"); yield console.log(" _____\n | |\n | o\n | /|\\ \n _|_ \ \n| |_____\n| |\n|_________|\n"); yield console.log(" _____\n | |\n | o\n | /|\\ \n _|_ / \\ \n| |_____\n| |\n|_________|\n"); } //As the generator definition you can istanciate the generator object wherever you need //as long as it's visible in the while loop const generator = hangmanGenerator(); // Show player their progress | .join returned answer as a string while (remainingLetters > 0 && lives > 0) { (answerArray.join("")); guess = readline.question(name + "'s guess (Enter 9 for lifelines or 0 to pass): "); guess = guess.toUpperCase(); //if guess is more than 1 letter or no letter, alert player to guess 1 letter only if (guess.length !== 1) { console.log("Please enter 1 letter only."); } //if valid guess else { if (guesses.includes(guess)) { console.log("\nYou have already made this guess, please try another letter!\n"); } else { guesses.push(guess); correctGuess = 0; for (var j = 0; j < Word.length; j++) { if (Word[j] == guess) { answerArray[j] = guess; remainingLetters--; correctGuess = 1; } } if (correctGuess == 1) { console.log("\nGood job! " + guess + " is one of the letters!\n"); console.log(JSON.stringify(answerArray) + "\n"); console.log(JSON.stringify(alphabets) + "\n"); } else { lives -= 1; console.log("\nSorry. " + guess + " is not a part of the word.\n"); console.log(JSON.stringify(answerArray) + "\n"); console.log(JSON.stringify(alphabets) + "\n"); console.log("You have " + lives + " lives remaining.\n"); //HERE you show the hangman in the console generator.next().value; } } } if (remainingLetters == 0) { console.log("Congratulation! You managed to guess the word!\n"); break; } if (lives == 0) { console.log("Game Over... You failed to guess the word. The word is " + Word + ".\n") } } Not really useful, as it adds little value and is incompatible with older browsers (especially IE). What do you mean with "adds little value" ? For the compatibility only IE and opera mini are not supporting generators (specific compatibility wasn't a question requirement anyway): https://caniuse.com/#feat=es6-generators The proposed solution with a generator has no apparent advantage over a simple array, as proposed by Jamiec, but some disadvantages. There are good uses cases for generators, this isn't one. Well...using a generator would allow to have a simpler sintax, forget about any one-usecase-only array index and out-of-bounds checks, but i understand that there are way more interesting scenarios in which generators may be a lot more helpful. Thank you for the comment anyway ! Have a good day !
common-pile/stackexchange_filtered
Multiple background images casuses error in Safari I'm trying to style the body element with two images. background: url(bg2.png) repeat-x, url(bg1.png) repeat; The problem is that Safari generates an error in the console, complaining about how it can't find the image file which is the last to be specified in the code above. The background images still display correct. Any thoughts on why this is accouring? Did you try putting both url first (same line), and in a different line the other properties? I could be wrong, but multiple backgrounds follow a certain syntax, don´t they? Yeah, the syntax is a bit wonky but Chrome doesn't complain about the code. Just thought if there's a bug or some work around for Safari. I can´t find any comments on safari bugs for multiple backgrounds... it´s been supported by it for a while http://caniuse.com/multibackgrounds Perhaps you need to specify the position, try background: url(bg2.png) top left repeat-x, url(bg1.png) top left repeat; To answer the question above, your syntax is incorrect. body{ background-image: url("../img/logo.jpg"), url("../img/background.png"); background-repeat:no-repeat, repeat-y; background-position: right 30px, right top; background-attachment:fixed, scroll; background-color:#ffffff; color:#000000; } Note: the first image will have the highest stacking order. Now for my question related to multiple background images. Checking my error logs, I've noticed errors for the above background images. I tried to fix this by using absolute URLs to no avail. I can only assume these 404s are caused by older versions of IE. Anyone else using multiple background images notice this in their error logs? Have you tried it using background-image instead of background? background-image and background-repeat, that is. I broke background shortkut into background-image, background-repeat and background-position and it resolved my issue across versions of Safari.
common-pile/stackexchange_filtered
Tumblr theming - show preview image for "link" post type? When you add a "link" type post to Tumblr: ...your admin shows a small thumbnail of any image associated with that link: However, this doesn't show on the frontend of the site: Is there any way to pull this image through? If you use pytumblr when you call the create_link method you can add the parameter thumbnail={image-url} Tumblr Link Theme Operator and Thumbnail Tumblr recently added some new theme operators to allow for link thumbnails. I presume this works the same as video thumbnails work and may only be available if the linked site creates the thumbnail. {block:Link} {block:Thumbnail} <img src="{Thumbnail}" alt="{Name}"> {/block:Thumbnail} {/block:Link} Reference: http://www.tumblr.com/docs/en/custom_themes#link-posts Great thanks! Just to note, there's a missing " after the image source. Other than that works fine. @JazzHands My pleasure! Updated the answer with the missing ". Thanks! I just noticed that on my tumblr blog and fixed it. Only took 4 years :) This is how it's done: Click on your blogs name on the dashboard above or in the bloglist on the right hand side. Click on Customize on the right hand side (or just go to the template you chose) Once you're in there you can change the HTML on top on the left hand side, right under the templates name and icon There you look for the {block:Link} and before the description you add: {block:Thumbnail} <img src="{Thumbnail}" alt="{Name}"> {/block:Thumbnail}`
common-pile/stackexchange_filtered
How to use a loop on a named range I am getting a Run-time error '424' with my For . . . Next loop. I have created a time sheet for my work where I only need to enter start and finish times. Then, depending on the day of the week it calculates which hours are worked as Monday to Friday (MF), Saturday-Sunday (SS) or a public holiday (PH). There is a column at the start with a check box for each employee to indicate if they worked as a supervisor or not. (This is important to set pay rates and also charge rates when invoicing. Supervisors are charged a flat rate for every day except public holidays.) The check boxes are linked to the cell underneath them to show true/false depending on whether checked or not. I am trying to total up the type of hours worked on each day of the week. The column with the check boxes in is a named range (ChargeSuper) on the worksheet. What I need to do for each employee is see if the checkbox is true or false and then add up the times for all employees on each day of the week. But I am getting a runtime error at the start of the loop. This is what I have written so far: Dim ChargeSuper As Range Dim MyCell As Range ' Dim SupHrs As Single Dim SupPH As Single Dim StdMF As Single Dim StdSS As Single Dim StdPH As Single ' For i = 1 To 7 ' Set hours to 0 SupHrs = 0 SupPH = 0 StdMF = 0 StdSS = 0 StdPH = 0 r = 2 + i ' For Each MyCell In ChargeSuper If MyCell = False Then StdMF = StdMF + MyCell.Offset(r, 1).Value StdSS = StdSS + MyCell.Offset(r, 2).Value StdPH = StdPH + MyCell.Offset(r, 3).Value Else SupHrs = SupHrs + MyCell.Offset(r, 1).Value SupHrs = SupHrs + MyCell.Offset(r, 2).Value SupPH = SupPH + MyCell.Offset(r, 3).Value End If Next MyCell The error occurs at the line "For Each MyCell in ChargeSuper". What I want is for it to check each cell with the check box. If it is not checked (False) then add the hours as standard staff. If it is checked then add them as a supervisor. I have not written VBA for a long time, but this is above what I knew back then too. Any input would be appreciated. You need to set that named range, You only declared that, but not set. You Dim ChargeSuper as Range but you never Set it to any value.
common-pile/stackexchange_filtered
Can Socket.io emits arrive out of order? What if volatile? I've been looking around for a definitive answer to this but I seem to keep finding contradictory answers (ex this and this). Basically, if I socket.emit('game_update', {n: 1}); from a node.js server and then, 20 ms later, socket.emit('game_update', {n: 2}); from the same server, is there any way that the n:2 message arrives before the n:1 message? In other words, does the n:1 message "block" the receiving of the n:2 message if the n:1 message somehow got lost on the way? What if they were volatile emits? My understanding is that the n:1 message wouldn't block the n:2 message -- if the n:1 message got dropped, the n:2 message would still be received whenever it arrived. Background: I'm building a node.js game server and want to better understand how my game updates are traveling. I'm using volatile emit right now and I would like to increase the server's tick rate, but I want to make sure that independent game updates wouldn't block each other. I would rather the client receive an update every 30 ms with a few dropped updates scattered here and there than have the client receive an update, receive nothing for 200 ms, and then receive 6 more updates all at once. Disclaimer: I'm not completely familiar with the internals of socket.io. is there any way that the n:2 message arrives before the n:1 message? It depends on the transport that you're using. For the polling transport, I think it's fair to say that it's perfectly possible for messages to arrive out-of-order, because each message can arrive over a different connection. With the websocket transport, which maintains a persistent connection, the message order is reasonably guaranteed. What if they were volatile emits? With volatile emits, all bets are off, it's fire-and-forget. I think that in normal situations, the server will wait (and queue up messages) for a client to be ready to receive messages, unless those messages are volatile, in which case the server will just drop them. From what you're saying, I think that volatile emits are what you want, although once a websocket connection has been established I don't think you'll see the described scenario ("receive an update, receive nothing for 200 ms, and then receive 6 more updates all at once") is likely to happen. Perhaps only when the connection gets lost and is re-established. The answer is yes it can possibly arrive later, but it is highly unlikely given that sockets are by nature persistent connections and reliability of order is all but guaranteed. According to the Socket.io documentation messages will be discarded in the case that the client is not connected. This doesn't necessarily fit with your use case, however within the documentation itself it describes Volatile events as an interesting example if you need to send the position of a character. // server-side io.on("connection", (socket) => { console.log("connect"); socket.on("ping", (count) => { console.log(count); }); }); // client-side let count = 0; setInterval(() => { socket.volatile.emit("ping", ++count); }, 1000); If you restart the server, you will see in the console: connect 1 2 3 4 # the server is restarted, the client automatically reconnects connect 9 10 11 Without the volatile flag, you would see: connect 1 2 3 4 # the server is restarted, the client automatically reconnects and sends its buffered events connect 5 6 7 8 9 10 11 Note: The documentation explicitly states that this will happen during a server restart, meaning that your connection to the client likely has to be lost in order for the volatile emits to be dropped. I would say a good practice would be to write your emits as volatile just in case you do get a dropped client, however this will depend heavily on your game requirements. As for the goal, I would recommend that you use client side prediction using some sort of dynamic time system or deltatime based on the client and server keeping a sync clock to help alleviate some of the problems you can incur. Here's an example of how you can do that, though I'm not a fan of the creators syntax, it can be easily adapted to your needs. Hope this helps anyone who hits this topic. Socket.io - Volatile events Client Side Prediction
common-pile/stackexchange_filtered
How to assign Property of Radio button to a Checkbox I want to assign the property of a Radio button to the checkbox, for example if i change the value of radio button the same should be effected to the checkbox.Below is the code what i have $(this).children('TD').find('input:radio').change(function() { $(this).parents('TD').find('input:checkbox').prop(?) }); Pleases someone help me Just use the prop value of this: $(this).children('TD').find('input:radio').change(function() { $(this).parents('TD').find('input:checkbox').prop('checked',this.checked) }); Note that it won't uncheck the box when you select the radio button off, as it won't call the change event on the old button. "Just use the prop value of this:" In jQuery 1.6.0 or higher only. In 1.5.x and earlier, it's attr. And $(this).prop('checked') is a very long-winded way to write this.checked. ;-) @T.J. Crowder As he used prop in his question, I would presume he is using a jQuery version which actually supports it. As for using directly node.checked, yes, it certainly is faster, but then you may want to make sure the element actually exists as well, because otherwise you are gonna end up with errors when modifying the DOM element which may or may not exist. If you are willing to traverse the DOM in a matter as he did while being sure that the elements he use actually exist, then why not. EDIT, sorry missed half of your answer, that only applies for the first bit in your answer. If you literally mean value, as in the value attribute, then you can either assign to the element's own value property or use jQuery to do it via val(). But I assume you actually mean the checked state, not the value, in which case you can either assign directly to the checked property of the element, or use attr(). Example: If you know the checkbox will be there, just set its checked property directly: $(this).children('TD').find('input:radio').change(function() { $(this).parents('TD').find('input:checkbox')[0]. checked = this.checked; // note this ---^^^ We're looking at the raw element }); Or if you prefer to do it "the jQuery" way or there's any possibility the checkbox won't be there, like this: $(this).children('TD').find('input:radio').change(function() { $(this).parents('TD').find('input:checkbox').attr("checked", this.checked); }); Using attr to set the checked state works in jQuery 1.5.x and below, and in jQuery 1.6.1 and above; in 1.6.1 or above you could use prop instead. For about two weeks (jQuery 1.6.0), you would have had to use the new prop function, but they rethought that. :-)
common-pile/stackexchange_filtered
Dataset Locate number within range I have this dataset with the following data : Winner Name Coupon Start Coupon End Joshua 00001 00010 Mark 00011 00020 Stephen 00021 00024 Ina 00025 00025 I can easily using Locate to find for example the winner for coupon 00011 which is Mark, but how to find the winner for Coupon between (ie 00023 or 00007) using dataset.locate function you want to get 3 names if it's a range of coupons? couponstart <= 00007 and 00023 <= couponstart you can use https://docwiki.embarcadero.com/Libraries/en/Data.DB.TDataSet.Filter and https://docwiki.embarcadero.com/Libraries/en/Data.DB.TDataSet.Filtered and iterate through your dataset if I understand your question correctly substitute couponstart with couponend ofc how to locate the number between couponstart and couponend, i tried both locate and filter but the result is none. onfilterrecord i tried : Accept := couponstartfield >= 23 AND couponendfield <= 23; with no result. Try your filter like this. For finding 7, (7 >= CouponStart) AND (7 <= CouponEnd) it's the same for 23 (23 >= CouponStart) AND (23 <= CouponEnd) thanks its working now, tried couponstart<=7 and couponend>=7 didn't work. and it actually work with 7 >=couponstart and 7<=couponend, look similar but the result is different. I've added an answer, if you could be so kind as to accept. You can't use Locate to find multiple values in they way that you've asked. You can use a filter, an SQL query, or perhaps even SetRange. This answer will focus on using TDataset's filter, which can be used as part of an SQL query. You have to focus your filter with the Winning Ticket. If the winning ticket is 7, then your filter should be: (7 >= CouponStart) AND (7 <= CouponEnd) Same for a winning ticket of 23 (23 >= CouponStart) AND (23 <= CouponEnd)
common-pile/stackexchange_filtered
Play Framework compilation error when passing List object from controller to view I have a function in a controller that returns a list of User model records - I am using the PlayStartApp template: public Result getAllUsers() { List<User> users = User.find.all(); return ok(searchusers.render(form(Login.class, users))); } This function works correctly and returns a List object. I also have a view (html page) set with this to pass the object to the view: @(loginForm: Form[Application.Login], userList: java.util.List[User]) When I compile in activator on the command line, I receive this error message: [PlayStartApp] $ compile [info] Compiling 1 Scala source and 1 Java source to C:\WebDev\git\PlayAuthentic ate\target\scala-2.10\classes... [error] C:\WebDev\git\PlayAuthenticate\app\controllers\Application.java:209: met hod render in class views.html.searchusers cannot be applied to given types; [error] required: play.data.Form<controllers.Application.Login>,java.util.List <models.User> [error] found: play.data.Form<controllers.Application.Login> [error] reason: actual and formal argument lists differ in length [error] searchusers.render [error] C:\WebDev\git\PlayAuthenticate\app\controllers\Application.java:215: no suitable method found for form(java.lang.Class<controllers.Application.Login>,ja va.util.List<models.User>) [error] method play.data.Form.<T>form(java.lang.Class<T>,java.lang.Class<?>) is not applicable [error] (cannot infer type-variable(s) T [error] (argument mismatch; java.util.List<models.User> cannot be conver ted to java.lang.Class<?>)) [error] method play.data.Form.<T>form(java.lang.String,java.lang.Class<T>,ja va.lang.Class<?>) is not applicable [error] (cannot infer type-variable(s) T [error] (actual and formal argument lists differ in length)) [error] method play.data.Form.<T>form(java.lang.String,java.lang.Class<T>) i s not applicable [error] (cannot infer type-variable(s) T [error] (argument mismatch; java.lang.Class<controllers.Application.Logi n> cannot be converted to java.lang.String)) [error] method play.data.Form.<T>form(java.lang.Class<T>) is not applicable [error] (cannot infer type-variable(s) T [error] (actual and formal argument lists differ in length)) [error] form [info] Some messages have been simplified; recompile with -Xdiags:verbose to get full output [error] (compile:compileIncremental) javac returned nonzero exit code I reviewed this post, but I am still having the same issue: Play Framework 2.2.1 - Compilation error: "method render in class index cannot be applied to given types;" Any help would be great! EDIT: I removed the Login form. Code is now: public Result getAllUsers() { List<User> users = User.find.all(); return ok(searchusers.render(users)); } My view now has: @(userList: List[User]) @main(null) { <ul> @for(user <- userList) { <EMAIL_ADDRESS>} </ul> } I am receiving this when compiling: [error] C:\WebDev\git\PlayAuthenticate\app\controllers\Application.java:209: no instance(s) of type variable(s) T exist so that play.data.Form<T> conforms to java.util.List<models.User> Looks like you are using the wrong view file Change this line ok(searchusers.render(form(Login.class, users))) to ok(searchusers.render(form(Login.class), users)) For clarity sake Form[Application.Login] loginForm = form(Login.class) ok(searchusers.render(loginForm, users)) You have to pass form as first argument and users as second argument, but you are trying to pass Login.class and users to form which is wrong. I corrected the parentheses issue, but I still receive this message: [error] C:\WebDev\git\PlayAuthenticate\app\controllers\Application.java:209: met hod render in class views.html.searchusers cannot be applied to given types; [error] required: play.data.Form<controllers.Application.Login>,java.util.List <models.User> [error] found: play.data.Form<controllers.Application.Login> [error] reason: actual and formal argument lists differ in length [error] searchusers.render @Dan ... again the same issue . use it like this searchusers.render(form(Login.class), users) @Dan you are not passing required number of arguments to render @Dan use this `Form[Application.Login] loginForm = form(Login.class) ok(searchusers.render(loginForm, users)) ` my code is this: return ok(searchusers.render(form(Login.class), users)); I have 2 parameters being passed from the controller to the view. For "render" - how many parameters do I need to pass? I thought that had to match both the controller and the view. I updated my code to: public Result getAllUsers() { List<User> users = User.find.all(); Form<Application.Login> loginForm = form(Login.class); return ok(searchusers.render(loginForm, users)); } but still get the same error @Dan try to do sbt clean and then do sbt compile @Dan clean and build the project agaiin I edited my original post, please take a look when you get the chance @Dan what is the name of the view file searchusers.scala.html @Dan did you try to clean and compile the project I cleaned, compiled, closed and re-opened the command prompt and Eclipse... Cleaned and Refreshed in Eclipse, started activator, cleaned and compiled again, but still get the message...
common-pile/stackexchange_filtered
i want to check if the specified condition is true at least one time for the given number of bars starting from the current one in PineScript condition = (ta.barssince(high > sma20 or high > sma50 or high > sma200) <= 3) and (ta.barssince(close < sma20 or close < sma50 or close < sma200) <= 3) // Plotting for visualization plotshape(condition, color=color.green, style=shape.triangleup, location=location.abovebar, size=size.small) Is this one correct or not? You can use math.sum() to count the number of times where a condition was true within the given lookback period. cond = (close > open) lookback = 5 cond_cnt = math.sum(cond ? 1 : 0, lookback) Can i look lookhead also?
common-pile/stackexchange_filtered
Intersection between two finite planes I have two planes defined by three points each. These planes are "finite", meaning that the three points define their limits. These planes may or may not intersect, if so, the intersection is a finite line. What's the smartest way to find the two end points of this intersection line? Example: planea = {(369.4956, 467.6504, 60.5147), (372.1940, 467.9910, 50.6351), (297.3370, 665.9444, 47.6697)} planeb = {(198.1879, 626.4104, 59.6933), (199.4659, 620.8089, 38.2796), (398.9405, 661.8527, 62.6248)} enter image description here It seems that your "finite" planes are better described as triangles in 3D, together with the points "inside" each triangle (the convex combinations of a triangle's vertices). StackOverflow has this 2009 Question with activity from subsequent years, "Triangle Triangle Intersection in 3D Space". The same problems are discussed in various GameDev.SE posts like this one. Is it impossible for the two triangle to be coplanar? Yes, they may be planar and "far away" (no intersection), but if they intersect, they are not in the same plane. So I always expect a line segment as the intersection, and I need to have the two points of this segment as well. Here's a tedious way - perhaps not the "smartest" but probably quite fast enough in any programming language. It's all standard linear algebra (geometry in three dimensions). First find the (equation of) the line of intersection of the planes determined by the two triangles. Then find the (at most four) points where that line meets the edges of the triangles. Two of those points will be the end points of the segment you seek. At any stage of the calculation you may be able to conclude that the two triangles don't meet at all. Makes sense! Thank you very much for your help. @RafaelMarch You're welcome. But do follow up on hardmath's comments. Absolutely, I'll need to follow up in order to compute the intersection between triangles.
common-pile/stackexchange_filtered
How does the Orion communicate with Earth? Early renders of the Orion spacecraft show a deployed high-gain antenna dish like on the Apollo CSM. The Orion that actually materialised has no such thing. What does it use instead? The Orion module (capsule + service module) has six antennae, four on the capsule and two on the service module. You can't see them because they're inside either the heat shield on the Orion module or inside the faring that protects the service module. They are flat (or nearly so), but that does not mean they are omnidirectional antennae. They are instead phased array antennae. There are key advantages to a phased array antenna compared to a dish antenna: No moving parts. A highly directional dish antenna either needs the spacecraft to change its orientation (which can interfere with operations and costs propellant) or it needs a drive motor (which can fail) so the dish points at the Earth. A phased array antenna does not need to do either but can still be highly direction. The aiming is instead done with electronics that differentially delay the signal from / to different parts of the antenna. Quick response. This is a side benefit from having no moving parts. Reorienting a spacecraft or a drive motor that controls an antenna is a slow process. Changing the phasing is extremely quick. Hidden from view (and more importantly, protected from debris and sunlight). A big dish antenna has to stick out from the spacecraft. The Orion antennae are flat and are protected. Could planetary spacecraft use phase array antennas instead of large dishes? @Andykins Yes. That was exactly what the MESSENGER probe to Mercury used.
common-pile/stackexchange_filtered
Plasma physics conference coffee break, MIT campus. Mrs. Lisa Guzman The dispersion relation clearly shows fast mode has the highest phase velocity, but I'm questioning whether that plus branch truly represents the dominant energy transport mechanism in solar wind interactions. Susan Montgomery You're right to probe that assumption. The fast magnetosonic mode does carry the plus branch, but consider this - when we observe perpendicular propagation to the background field, the fast mode becomes purely compressive while Alfvén modes vanish entirely. Mrs. Lisa Guzman That's the key distinction I was missing. So at ninety degrees to the field, we're left with just fast and slow magnetosonic modes. But what happens during mode conversion at null points? The simulations show fast modes generating slow modes after interaction. Susan Montgomery Exactly. The incoming fast wavefront deforms due to magnetic topology, then slow modes emerge propagating along separatrices. It's not just velocity that matters - it's how the wave energy redistributes spatially. Mrs. Lisa Guzman Which brings us back to the fundamental question: is the fast mode's dominance in phase velocity misleading us about its actual role in energy dissipation? The $v_A$ and $v_s$ terms in that square root expression suggest the story's more complex.
sci-datasets/scilogues
Dividing points into zones I have a bunch of points that I'd like to assign zones to in a grid. My points are from -100:100 along the x-axis and -42.5:42.5 along the y-axis. I want to create an overall 10x7 grid, which means the individual boxes are 20x12.143. Below is a re-prex example of the data and with gridlines indicating how I want the data divvied up. x <- seq(-100, 100, length.out = 50) y <- seq(-42.5, 42.5, length.out = 50) points <- merge(x, y) points %>% ggplot() + geom_point(aes(x, y), color = "lightblue") + theme_minimal() + #start of grid points geom_segment(aes(x = -100, xend = -100, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -80, xend = -80, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -60, xend = -60, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -40, xend = -40, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -20, xend = -20, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 0, xend = 0, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 80, xend = 80, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 60, xend = 60, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 40, xend = 40, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 20, xend = 20, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 100, xend = 100, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -100, xend = 100, y = -30.357, yend = -30.357)) + geom_segment(aes(x = -100, xend = 100, y = -18.214, yend = -18.214)) + geom_segment(aes(x = -100, xend = 100, y = -6.071, yend = -6.071)) + geom_segment(aes(x = -100, xend = 100, y = 30.357, yend = 30.357)) + geom_segment(aes(x = -100, xend = 100, y = 18.214, yend = 18.214)) + geom_segment(aes(x = -100, xend = 100, y = 6.071, yend = 6.071)) + geom_segment(aes(x = -100, xend = 100, y = -42.5, yend = -42.5)) + geom_segment(aes(x = -100, xend = 100, y = 42.5, yend = 42.5)) What I'd like to do is assign each of those points in each zone a unique zone ID (like Zone 1 through Zone 70). I can probably write a massive ifelse function, but that's easy to mess up. I feel like there should be an easier way to do this, but I can't figure it out. Any help is appreciated! for the future reader - this way of creating a regular grid is very inefficient. Check https://stackoverflow.com/questions/33989595/overlay-grid-rather-than-draw-on-top-of-it for other options to create a regular grid. There are 4 steps to take, first you define two sequences along the x and y axes for the grid. Second, you make a matrix that can be indexed by the seq_along() of the x and y sequences and returns an ID. xbreaks <- seq(-100, 100, length.out = 10) ybreaks <- seq(-42.5, 42.5, length.out = 8) id <- matrix(seq_len(length(xbreaks) * length(ybreaks)), length(xbreaks), length(ybreaks)) Subsequently we can use findInterval() to match the points to a position in the grid in the x and y direction. This position can then be used to index the id matrix defined above. # Make points x <- seq(-100, 100, length.out = 50) y <- seq(-42.5, 42.5, length.out = 50) points <- merge(x, y) # Match points to grid location xi <- findInterval(points$x, xbreaks) yi <- findInterval(points$y, ybreaks) # Subset with 2-column matrix points$id <- id[cbind(xi, yi)] And this is what the IDs look like. library(ggplot2) ggplot(points) + geom_point(aes(x, y, colour = as.factor(id))) + theme_minimal() + #start of grid points geom_segment(aes(x = -100, xend = -100, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -80, xend = -80, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -60, xend = -60, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -40, xend = -40, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -20, xend = -20, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 0, xend = 0, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 80, xend = 80, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 60, xend = 60, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 40, xend = 40, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 20, xend = 20, y = -42.5, yend = 42.5)) + geom_segment(aes(x = 100, xend = 100, y = -42.5, yend = 42.5)) + geom_segment(aes(x = -100, xend = 100, y = -30.357, yend = -30.357)) + geom_segment(aes(x = -100, xend = 100, y = -18.214, yend = -18.214)) + geom_segment(aes(x = -100, xend = 100, y = -6.071, yend = -6.071)) + geom_segment(aes(x = -100, xend = 100, y = 30.357, yend = 30.357)) + geom_segment(aes(x = -100, xend = 100, y = 18.214, yend = 18.214)) + geom_segment(aes(x = -100, xend = 100, y = 6.071, yend = 6.071)) + geom_segment(aes(x = -100, xend = 100, y = -42.5, yend = -42.5)) + geom_segment(aes(x = -100, xend = 100, y = 42.5, yend = 42.5)) Created on 2021-02-19 by the reprex package (v1.0.0) teunbrand this works really well! My next step is looking at how often there's a value in one zone then another, like going from zone 1 to zone 13. Using the count and spread functions, I can get how many times each zone followed the one in question, but is there an easy way to get the % of which zone followed? Other than manually mutating the 80 zones and their %? This vaguely reminds me of the cumsum() function, but I'm afraid I don't fully understand what you mean. Could you give an example calculation?
common-pile/stackexchange_filtered
Is possible to install WSO2 Identity server features on WSO2 App Server? I have tried several options to install IS on App Server and using different repositories but it always complains about some packages. What is the easy way to get the correct dependencies and repositories? This is an example of the errors: Cannot complete the install because of a conflicting dependency. Software being installed: STS Feature 4.2.1 (org.wso2.carbon.sts.feature.group 4.2.1) Software currently installed: WSO2 Carbon - Carbon Feature 4.4.1 (org.wso2.carbon.core.feature.group 4.4.1) Only one of the following can be installed at once: WSO2 Carbon - Carbon Feature 4.4.1 (org.wso2.carbon.core.feature.jar 4.4.1) WSO2 Carbon - Carbon Feature 4.2.0 (org.wso2.carbon.core.feature.jar 4.2.0) what is the wso2IS and wso2AS version that you use? What version of IS and what version of App Server are you running? I have never tried to implement the scenario you are but I could see you getting that type of error if the version of App Server you are running is on Carbon 4.4 and the version of IS is still on Carbon 4.2. The current 5.0 release of IS runs on Carbon 4.2 but I think the 5.1 release of IS runs on Carbon 4.4 and should be available before long. Joe I tried several versions, for the App server 5.2.0, 5.2.1, 5.3.0. In all of them I tried to install the IS feature version 5.
common-pile/stackexchange_filtered
Launch activity when user taps on a notification from the lockscreen I want to be able to tap on a notification when the device is locked and launch an activity without unlocking the device. I added some flags to the activity in the onCreate() method that allow the activity to be displayed when the device is locked: Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); This is the code that creates the notification: Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new Notification.Builder(this) .setContentIntent(pendingIntent) .setContentTitle("Title") .setSmallIcon(android.R.drawable.ic_menu_more) .build(); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(1, notification); I also added showOnLockScreen="true" to the manifest: <activity android:name=".MainActivity" android:label="@string/app_name" android:showOnLockScreen="true" <EMAIL_ADDRESS> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> Things that are working: The activity is shown when the device is locked (for example, if I leave the activity on foreground and lock the phone the activity remains on foreground without the need of unlocking the phone) If I tap the notification when the phone is locked, it asks me to unlock it and then the activity is shown I want to be able to do the same but without unlocking the device. What am I missing? Try this!!! private NotificationCompat.Builder mBuilder; Intent notifyIntent = new Intent(getApplicationContext(), MainActivity.class); notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notifyIntent, 0); mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(getNotificationIcon()) .setContent(remoteViews) .setContentIntent(pendingIntent) .setOnlyAlertOnce(true) .setOngoing(true); this is method get notification icon on device 5.0 and lower private int getNotificationIcon() { boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP); return useWhiteIcon ? R.drawable.notification_icon : R.mipmap.ic_launcher; } Remove code below in onCreate Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); The remoteViews variable is not declared (nor assigned). I tried the rest of your set up and it's not fixing my issue. Are you sure this code allows an activity to be launched from a notification on the lockscreen without unlocking the device? notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
common-pile/stackexchange_filtered
Text-To-Speech in background audio task I have a Background Audio Task in a WP8.1 project which uses the BackgroundMediaPlayer to play audio. In my foreground app I have articles (online articles) which can be listened to. This is done via TTS (SpeechSynthesizer). I have tried two things to implement this feature: Creating a SpeechSynthesisStream in the task and use it with BackgroundMediaPlayer.Current.SetStreamSource(IRandomAccessStream stream). Always hitting memory exceptions with this method when the text is longer than a few hundred chars. Creating the stream in the foreground app and save it to a .wav file. This works with longer texts as in the first method but creates really large files and takes inacceptable long to generate and increases memory by a few hundred MB. Code for the 2nd implementation: string content = "......."; // create stream from synthesizer SpeechSynthesizer synth = new SpeechSynthesizer(); SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(content); // get inputstream and size of stream ulong size = stream.Size; IInputStream inputStream = stream.GetInputStreamAt(0); stream.Dispose(); DataReader dataReader = new DataReader(inputStream); await dataReader.LoadAsync((uint)size); byte[] buffer = new byte[(int)size]; dataReader.ReadBytes(buffer); inputStream.Dispose(); dataReader.Dispose(); // open folder and file IStorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Audio", CreationCollisionOption.OpenIfExists); IStorageFile file = await folder.CreateFileAsync("audio.wav", Windows.Storage.CreationCollisionOption.ReplaceExisting); // write file await Windows.Storage.FileIO.WriteBytesAsync(file, buffer); Any ideas how to implement this feature in a "memory-friendly" and fast way (without using online services)?
common-pile/stackexchange_filtered
Magento2 - How to add custom login/register step on the checkout I wish to add a custom login register step step on the checkout. This step should be visible only to the non-logged-in users. How can I achieve this? You will have to create a custom module in order to achieve this functionality. Refer the below link from the documentation : https://devdocs.magento.com/guides/v2.4/howdoi/checkout/checkout_new_step.html Also it is already answered at this stackexchange link : https://magento.stackexchange.com/questions/169969/magento2-add-login-form-in-checkout-page
common-pile/stackexchange_filtered
ASP.NET MVC the user account created in ASP.NET configuration unusable I'm new to asp.net MVC. I'm using VWD Express 2012,ASP.NET MVC 4 Web Application template, Razor engine to develop my web application. This is the problem I'm having: After enable and created role(Administrator) and user account in Project -ASP.NET configuration. I couldn't log in with the account I just created. The error message is "The user name or password provided is incorrect." However in the tutorial, MvcMusicStore(http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-7) I followed their steps and successfully created Administrator account. Therefore, I couldn't find out what caused that problem. But the account I created by Ctrl + F5 - "Register" on the top left is able to log in. Thanks for your time reading this post. Any hints or website links are appreciated. Did you by any chance deploy your application to a server and then created the account on your local PC? Does ASP.NET Development Server counts? Cuz I'm in the testing phase so I only use Ctrl+F5 to run the application and monitor the changes I made. I mean I only run it locally if that's what you were asking. No, if it's local you should be OK. The only thing I can imagine is that your ASP.NET configuration tool is writing the data to a different database then the one your application is reading from. Could you check your web.config and your application to make sure they both are targetting the same DB? Sure, I'll do it right away, thanks for the hints:) BTW how many can I have in the web.config? Cuz I added one other than the defaultConnection. Can this be the cause of my problem? Yes, that's possible. Just to check, delete all but one ConnectionString and try the same thing again (adding a user in the config-tool and then logging into the app with that one) Fort testing that I created a new project, using ASP.NET 4 Web Application, Internet Application template. Then go to PROJECT - ASP.NET Configuration, created one role and an user account that assigned with that role. After that I close the Configuration tab, and run the application. Clicked "Log in" and trying to log in with the username I just created. It is said "The user name or password provided is incorrect." I checked the Data Connections in the Database Explorer there are two connections are created inside "aspnet-UerTesting-20130924215458.mdf" and "DefaultConnection (UerTesting)". Both of them contents the same 5 tables "UserProfile", "webpages_Membership", "webpages_OAuthMembership", "webpages_Roles" and "webpages_UsersInRoles". When I check them with "show table data", they are all empty. However, when I go to ASP.NET Configuration the Role and user account I created earlier are still there. So where is the role and user account data in Configuration are stored? I'm confused. After reading the comments, I can see what's happening. Your MVC app is using the SimpleMembershipProvider. This provider is not compatible with the configuration tool. The config tool uses different tables and is thus not compatible. You can do one of two things in this case: - don't use the configuration tool but use a script, or maybe create your own admin pages. - Disable simple membership so that MVC uses the old membership system As for the database, you'll notice that after using the config tool, the tool creates a .MDF-file under the App_Data directory, that's where your user is stored that you created with the tool Thank you so much. After reading your answer I start to understand what is happening. About your first suggestion, writing my own script, if you got some useful links(tutorial) that might helps me learning how to do it? I'll also do my own research. Thanks again:)
common-pile/stackexchange_filtered
Angular 18.0.5 not seeing the interceptor Angular is not aknowledging the interceptor. So basically I executed ng generate interceptor JwtInterceptor and setup set it up to add the token to the header : import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; import { catchError, throwError } from 'rxjs'; export const jwtInterceptorInterceptor: HttpInterceptorFn = (req, next) => { console.log('Interceptor invoked'); let token: string | null = localStorage.getItem("access_token"); console.log("Token from localStorage:", token); if (token) { const clonedRequest = req.clone({ headers: req.headers.set( 'x-auth-token',token ) }); return next(clonedRequest).pipe( catchError((err: any) => { if (err instanceof HttpErrorResponse) { if (err.status === 401) { console.error('Unauthorized request:', err); } else { console.error('HTTP error:', err); } } else { console.error('An error occurred:', err); } return throwError(() => err); }) ); } else { console.log("no token") return next(req); } }; Then added the interceptor in the provider : export const appConfig: ApplicationConfig = { providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient( withInterceptors([jwtInterceptorInterceptor]), ),] }; also tried the Di pattern in app.config.ts : export const appConfig: ApplicationConfig = { providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(withInterceptorsFromDi()), { provide: HTTP_INTERCEPTORS, useValue: jwtInterceptorInterceptor, multi: true },] }; And i even put the provider inside the component as well which shouldn't be done as it might double trigger it or cause a conflict i'm assuming : @Component({ selector: 'app-profile', standalone: true, imports: [ReactiveFormsModule], templateUrl: './profile.component.html', styleUrl: './profile.component.css', providers: [ { provide: HTTP_INTERCEPTORS, useValue: jwtInterceptorInterceptor, multi: true } ], }) I tried getting rid of all the interceptor's code and leaving only the loggings but still the interceptor is not being hit at all in any scenario : Note This is the reference that seemed to me the most accurate to follow : text I'm a week years old on angluar. I went throught all stackoverflow issues could you share a stackblitz with the minimal reproducible code for debugging, I think you are not bootstraping the application properly like mixing standalone and modular you're not wrong if i understood you correctly, either way I solved it (read last answer). the app.config.ts was the wrong wrapper in which the intercepted should be callled, instead i called it in bootstrapApplication() in main.ts and it worked : bootstrapApplication(AppComponent, { providers: [ provideProtractorTestingSupport(), provideRouter(routes), provideAnimations(), provideHttpClient(withInterceptors([jwtInterceptorInterceptor])), ], }).catch((err) => console.error(err));
common-pile/stackexchange_filtered
how to center a div horizontally, vertically, and maintain 1:1 aspect ratio? I wish to have a canvas inside of a div which is centered and regardless of its scale, maintains a 1:1 aspect ratio. By creating a containing div with the following style rules, I am able to get the child element (the canvas) to be centered vertically and horizontally. display: "flex", alignItems: "center", justifyContent: "center", However, after much googling, I'm unable to find a way of enforcing an aspect ratio. There is some odd way of using top-padding, but it doesn't seem to work in the case of flex box. I may decide to change the relative size of the canvas in its containing div, but I'd like it to remain centered and presever a 1:1 aspect ratio. What css rules can meet those constraints? You will need to use max-width and max-height. .container { position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 100%; height: 100%; background-color:#429bf4; } .image { position: absolute; max-width: 100%; max-height: 100%; top: 50%; left: 50%; transform: translate(-50%, -50%); } body { width: 100%; height: 100%; position: absolute; margin: 0; } <div class='container'> <img class='image' src='http://via.placeholder.com/300x300'> </div> Flex Example .main { width: 200px; } .aspect1-1 { width:100%; padding-top:100%; position: relative; } .aspect1-1 div { position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color:#429bf4; display:flex; justify-content:center; align-items:center; } <div class="main"> <div class="aspect1-1"> <div> <img src="http://placehold.it/100x100"> </div> </div> </div> If your main div is full screen, you can use vmin. You need to set the canvas flex-grow and flex-shrink to 0 so the size will not be responsive, set min-width to 0 to narrow past the implied width of the canvas (300px), define the width with flex-basis and the height with height (same as flex-basis for a 1:1 ratio): flex: 0 0 100vmin; min-width: 0; height: 100vmin; body { margin: 0; } .outerdiv { display: flex; justify-content: center; align-items: center; } canvas.center { flex: 0 0 100vmin; min-width: 0; height: 100vmin; background-color: tomato; } <div class="outerdiv"> <canvas class="center"></canvas> </div> And if you want a margin, use calc() with two times the margin: flex: 0 0 calc(100vmin - 10em); min-width: 0; height: calc(100vmin - 10em); margin: 5em; body { margin: 0; } .outerdiv { display: flex; justify-content: center; align-items: center; } canvas.center { flex: 0 0 calc(100vmin - 10em); min-width: 0; height: calc(100vmin - 10em); background-color: tomato; margin: 5em; } <div class="outerdiv"> <canvas class="center"></canvas> </div> is there a way to achieve aspect ratio that doesn't rely on viewport relative sizes?
common-pile/stackexchange_filtered