text
stringlengths
15
59.8k
meta
dict
Q: How to repeat an html element n number of times using javascript I'm trying to print an element, in my case an hr tag some number of times according to the length of a word. This code is for a hangman game I'm trying to recreate. I have looked up similar questions and its not quite what I'm lookin for. This is my javascript code so far. var words = ['Quaffle', 'Bludger', 'Golden Snitch', 'Time-Turner', 'Pensieve', 'Mirror of Erised']; function getRandomWord(){ var randomIndex = words[Math.floor(Math.random()* words.length)]; alert(randomIndex); } function printDashes(){ var dashes = document.getElementById("dash") } getRandomWord() printDashes() I'm not sure what to add after retrieving the element. Can someone guide me on how to go about this? A: You can also create div's so you can enter letters when the user inputs a character. I've attached an example below. UPDATE: Added example code to update the dashes with letters based on word var elem = document.getElementById('container'); var guess = document.getElementById('guess'); var word = "Hello"; // draw empty dashes var drawDashes = function(numberOfDashes) { for (var i = 0; i < numberOfDashes; i++) { var el = document.createElement('div'); el.classList = 'dash'; // we draw an empty character inside so that the element // doesn't adjust height when we update the dash later with a // letter inside el.innerHTML = '&nbsp;'; elem.appendChild(el); } } // update dash with a letter based on index var updateDash = function(index, letter) { elem.children[index].innerHTML = letter; } guess.addEventListener('keyup', function(evt) { // split the word up into characters var splitWord = word.split(''); // check to see if the letter entered matches any of the // words characters for (var i = 0; i < splitWord.length; i++ ) { // it is important we convert them to lowercase or // else we might get a mismatch because of case-sensitivity if (evt.key.toLowerCase() === splitWord[i].toLowerCase()) { // update dash with letter based on index updateDash(i, evt.key.toLowerCase()); } } // clear out the value this.value = ''; }); drawDashes(word.length); body { font-family: sans-serif; } .dash { height: 50px; width: 50px; margin: 0 10px; display: inline-block; border-bottom: 2px solid black; font-size: 32px; font-weight: bold; text-align: center; } #guess { height: 50px; width: 50px; padding: 0; font-size: 32px; text-align: center; } <div id="container"></div> <h4>Type a letter</h4> <input id="guess" type="text"/> A: Say your word is in some variable named myWord. Get the length of the word by doing: var myWordLen = myWord.length; Then you can create HTML elements using Javascript createElement method and appending child elements, information etc as needed. But since you want as many elements as the length of a word, use a loop. Eg: for(var i=0; i < myWordLen; i++) { var tr1 = document.createElement("hr"); var someEle = document.getElementById("someID"); someEle.appendChild(tr1); } A: What about this way? myElement.innerHTML = `<...>`.repeat(words.length)
{ "language": "en", "url": "https://stackoverflow.com/questions/53766542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML content encoded, started with '' sign I have received an email and the body is formed in HTML format. However, I was wondering how can I decode the encoded content as following: <a href=3Dhttp://&#65296;&#65294;&#65351;&#65351;&#47;&#68;&#70;&#116;&#50;&#85;> Could anyone tell me how to decode the string? The transfer encoding is Qouted-printable, and the charset is big5. However, I tried to decode the content with qp-decoder and nothing works. Thanks. A: Try the link below: http://toolswebtop.com/text/process/decode/BIG-5 I tried your link and got 3Dhttp://οΌοΌŽο½‡ο½‡/DFt2U
{ "language": "en", "url": "https://stackoverflow.com/questions/25615053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get my templated function to see other global methods defined later? (Oktalist gave a great answer below, check it out and the comments under it, to help demonstrate everything we've discussed, I've added a full, compiling solution at the bottom of my question that demonstrates everything discussed.) I have a collection of namespace global methods and templated methods like the following: namespace PrettyPrint { String to_string(bool val); String to_string(char val); String to_string(int val); String to_string(uint val); // ETC... template <typename T> String to_string(const T* val) { if (! val) return U("NULL"); return String().copy_formatted("(%p)-> %S", (const void*)val, to_string(*val).uchars()); } // ... and more templates to help with containers and such } The "String" type is not the C++ string, it's a special class derived off of IBM's ICU library, but not really relevant for this question. Point is, I have a bunch of namespace global methods called to_string and also some templated functions that override them. So far, so good, everything works great. But, now I have another header where I have something like the following defined: namespace User { struct Service { int code; String name; } //... } namespace PrettyPrint { String to_string(const User::Service& val) { return val.name; } } So, now I have defined some other type somewhere else, and I've also defined another to_string override in my PrettyPrint namespace to indicate how to convert my new type to a String. Toss both headers into a file, something like this: #include <the to_string and templates header> #include <the User::Service header> main() { User::Service s = {1, U("foo")}; User::Service *p = &s; PrettyPrint::to_string(s); PrettyPrint::to_string(p); } (Yes, the to_string methods should actually be returning a value somewhere, not the point.) The point is that the second call gives a compiler error (gcc, btw) saying that in the templated to_string method there is no matching function for call to 'to_string(const User::Service&)', which of-course exactly matches my method that is defined and included. If I reverse the #include ordering it works just fine. So, I surmise that the template is only looking at methods defined ahead of it. Is there any fix for this? Given the scope of my project and number of complicated #include's, simply saying "always make sure they come in the right order" is not a tractable solution, and would introduce too much complicated fragility in the code. The base to_string defintions is one of those files that will tend to get included high up in a lot of places, so making sure that any other random type definitions that happen to include a to_string override come first just isn't going to work. The other solution I have that works in some places is that I've defined a Printable interface in the base file: namespace PrettyPrint { class Printable { public: virtual String pretty_print_to_string() const = 0; } String to_string(const Printable& obj) { return obj.pretty_print_to_string(); } } That definition comes before the template methods in the same file. So, that works great for classes where I can simply add in that interface and implement it. Short of any great solutions here, I'm going to simply try to always use that, but there are places where it is not convenient and I'd also just like to understand if there is any way to get the method overloading solution to work without being dependent on #include ordering to work. Anyhow, what do you all think of these options? Is there an approach that I haven't thought of that might work nicely? Solution inspired from answer Oktalist gave This code actually does compile so you can copy it off and play with it, I think I've captured all the relevant use cases along with what works and what doesn't and why. #include <iostream> using namespace std; namespace PrettyPrint { void sample(int val) { cout << "PrettyPrint::sample(int)\n"; } void sample(bool val) { cout << "PrettyPrint::sample(bool)\n"; } template<typename T> void sample(T* val) { cout << "PrettyPrint::sample(pointer); -> "; sample(*val); } } namespace User { struct Foo { int i; bool b; }; void sample(const Foo& val) { //below doesn't work un-qualified, tries to convert the int (val.i) into a Foo to make a recursive call. //meaning, it matches the User namespace version first //sample(val.i); doesn't work, tries to call User::sample(const Foo&) cout << "User::sample(const Foo&); -> {\n"; cout << '\t'; PrettyPrint::sample(val.i); //now it works cout << '\t'; PrettyPrint::sample(val.b); cout << "}\n"; } } namespace Other { void test(User::Foo* fubar) { cout << "In Other::test(User::Foo*):\n"; //PrettyPrint::sample(*fubar); //doesn't work, can't find sample(const User::Foo&) in PrettyPrint PrettyPrint::sample(fubar); //works, by argument-dependent lookup (ADL) from the template call sample(*fubar); //works, finds the method by ADL //sample(fubar); //doesn't work, only sees User::sample() and can't instantiate a Foo& from a Foo* } void test2(User::Foo* happy) { using PrettyPrint::sample; //now both work! this is the way to do it. cout << "In Other::test2(User::Foo*):\n"; sample(*happy); sample(happy); } } int main() { int i=0, *p = &i; bool b=false; User::Foo f = {1, true}, *pf = &f; //sample(i); <-- doesn't work, PrettyPrint namespace is not visible here, nor is User for that matter. PrettyPrint::sample(i); //now it works //PrettyPrint::sample(f); //doesn't work, forces search in PrettyPrint only, doesn't see User override. using namespace PrettyPrint; // now they all work. sample(p); sample(b); sample(f); sample(pf); Other::test(pf); Other::test2(pf); return 0; } This results in the following output: PrettyPrint::sample(int) PrettyPrint::sample(pointer); -> PrettyPrint::sample(int) PrettyPrint::sample(bool) User::sample(const Foo&); -> { PrettyPrint::sample(int) PrettyPrint::sample(bool) } PrettyPrint::sample(pointer); -> User::sample(const Foo&); -> { PrettyPrint::sample(int) PrettyPrint::sample(bool) } In Other::test(User::Foo*): PrettyPrint::sample(pointer); -> User::sample(const Foo&); -> { PrettyPrint::sample(int) PrettyPrint::sample(bool) } User::sample(const Foo&); -> { PrettyPrint::sample(int) PrettyPrint::sample(bool) } In Other::test2(User::Foo*): User::sample(const Foo&); -> { PrettyPrint::sample(int) PrettyPrint::sample(bool) } PrettyPrint::sample(pointer); -> User::sample(const Foo&); -> { PrettyPrint::sample(int) PrettyPrint::sample(bool) } A: During the first phase of two phase lookup, when the template is defined, unqualified lookup looks for dependent and non-dependent names in the immediate enclosing namespace of the template and finds only those to_string overloads which appear before the template definition. During the second phase of two phase lookup, when the template is instantiated, argument-dependent lookup looks for dependent names in the namespaces associated with any class types passed as arguments to the named functions. But because your to_string(const User::Service&) overload is in the PrettyPrint namespace, it will not be found by argument-dependent lookup. Move your to_string(const User::Service&) overload into the User namespace to make use of argument-dependent lookup, which will find any overloads declared at the point of template instantiation, including any declared after the point of template definition. See also http://clang.llvm.org/compatibility.html#dep_lookup A: What the compiler does when instantiating a template is essentially expanding it (more or less like a macro), and compiling the result on the fly. To do that, any functions (or other stuff) mentioned must be visible at that point. So make sure any declarations used are mentioned beforehand (in the same header file, most probably). A: I don't entirely understand what's going on here, but it appears that if you want the later defined methods to be used, then they need to be template specializations. The compiler won't see function overrides later in the program. First off, we reproduce the problem. I do so with this program in gcc-4.8.2: // INCLUDE FILE 1 template <class T> void to_string (T const * a) { to_string (*a); } // INCLUDE FILE 1 END // INCLUDE FILE 2 // How do we make this program work when this is necessarily declared after to_string(T const * A)? void to_string(int const & a) { return; } // INCLUDE FILE 2 END int main (void) { int i = 5; int * p = &i; to_string(i); to_string(p); to_string(&i); return 0; } In order to get it working, we need to do this... // INCLUDE FILE 1 // The pointer version needs something to call... template <class T> void to_string (T const & a); // This can't be T const * a. Try it. So weird... template <class T> void to_string (T * a) { foo (*a); } // INCLUDE FILE 1 END // INCLUDE FILE 2 // This has to specialize template<> void to_string. If we just override, we get a linking error. template<> void to_string <int> (int const & a) { return; } // INCLUDE FILE 2 END int main (void) { int i = 5; int * p = &i; to_string(i); to_string(p); to_string(&i); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/22333301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: LiveData Duplicate Observers Concern I won't explain why this code is needed, but my question is whether the following code will lead to duplicate Observers or not: override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initializeRecyclerView() viewModel = ViewModelProvider(this).get(TestViewModel::class.java) updateUI() viewModel.getNewItems().observe(viewLifecycleOwner, { if (it != null && it == true){ updateUI() } }) } fun updateUI(){ viewModel.getItems().observe(viewLifecycleOwner, Observer { adapter.values = it adapter.notifyDataSetChanged() }) } fun initializeRecyclerView() { recyclerView.adapter = adapter } } As updateUI() gets called multiple times, does this create duplicate observers of viewmodel.getItems()??
{ "language": "en", "url": "https://stackoverflow.com/questions/66304999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure Redis Cache vs Redis Cloud service on Azure I need to use it in a .NET (webapi) app & using stackexchange.redis nuget package. Appreciate if someone please point me to appropriate resources for following - 1) Can I choose any of Azure Redis cache or Redis cloud service if I interface through stackexchange.redis nuget? 2) Azure Redis Cache vs Redis Cloud - differences & implications of choosing one over the other - if this info already available. Thanks A: Disclaimer: I work for Redis Labs, the company providing Redis Cloud. 1) Can I choose any of Azure Redis cache or Redis cloud service if I interface through stackexchange.redis nuget? Yes - both Azure Redis and Redis Cloud provide a Redis database that you can use with the StackEchange.Redis client from your app. 2) Azure Redis Cache vs Redis Cloud - differences & implications of choosing one over the other - if this info already available. While both are essentially a hosted Redis service, there are several differences between them. Most notably, Azure Redis Cache is deeply integrated in the Azure platform so you have everything (management, metrics, etc...) accessible from your management portal. OTOH, Redis Cloud is cloud-agnostic (it is available on multiple clouds) and offers more features than any other Redis-as-a-Service service. I think that the fact that Redis Cloud is the only service that can scale infinitely and w/o downtime/migration is perhaps the strongest differentiator, but feel free to refer to this comparison table for a high level overview: https://redislabs.com/redis-comparison
{ "language": "en", "url": "https://stackoverflow.com/questions/30474763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use Intl.NumberFormat to format square foot units I'm trying to use Intl.NumberFormat to format numbers with units and I have some units of square feet. When I try new Intl.NumberFormat('en-US', { useGrouping: true, style: "unit", unit: "square-foot" }).format(56) Uncaught RangeError: Invalid unit argument for Intl.NumberFormat() 'square-foot' The MDN documentation links to small list of approved units which were taken from a much larger list. The larger list has square feet but the smaller list does not, so that all makes sense. I see they allow compound units though. Pairs of simple units can be concatenated with "-per-" to make a compound unit. This suggests that it's only ratios of simple units, not products of two units. new Intl.NumberFormat('en-US', { useGrouping: true, style: "unit", unit: "foot-per-second" }).format(56) outputs --> "56 ft/s" Again, a link from MDN I see this page which suggests this is possible with this type="power2" argument but that's in some XML implementation of this which is not Javascript not totally clear on the relationship between unicode.org and what's implemented in a browser) Is there some way to get square feet as a the unit?
{ "language": "en", "url": "https://stackoverflow.com/questions/68581299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Awk, Shell Scripting I have a file which has the following form: #id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed 111|Arkas|Sarkas|male|1995-09-11|2010-03-17T13:32:10.447+0000|192.248.2.123|Midori Every field is separated with "|". I am writing a shell script and my goal is to remove the "-" from the fifth field (birthday), in order to make comparisons as if they were numbers. For example i want the fifth field to be like |19950911| The only solution I have reached so far, deletes all the "-" from each line which is not what I want using sed. i would be extremely grateful if you show me a solution to my problem using awk. A: If this is a homework writing the complete script will be a disservice. Some hints: the function you should be using is gsub in awk. The fifth field is $5 and you can set the field separator by -F'|' or in BEGIN block as FS="|" Also, line numbers are in NR variable, to skip first line for example, you can add a condition NR>1 A: An awk one liner: awk 'BEGIN { FS="|" } { gsub("-","",$5); print }' infile.txt A: To keep "|" as output separator, it is better to define OFS value as "|" : ... | awk 'BEGIN { FS="|"; OFS="|"} {gsub("-","",$5); print $0 }'
{ "language": "en", "url": "https://stackoverflow.com/questions/36116913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i match the exact text in XML I want to match the exact text "puts" in the (xml file) for a .tmTheme file for sublime text but I've come here as my last resort. I don't really know about regex please help. i'm trying to match the puts Ruby print keyword. for example: puts "cat" output cat My main aim is to only highlight the puts keyword as i can't find any other way to highlight its scope. It's for a syntax highlighting package. the seventh line with the --- <> --- is where i'm struggling with. Any help will be greatly appreciated. <dict> <key>name</key> <string>output</string> <key>scope</key> <string>source.ruby</string> <key>match</key> --- <string>>p[\'"]?([^\'" >]+)s</string> --- <key>settings</key> <dict> <key>foreground</key> <string>#ff0</string> </dict> </dict>
{ "language": "en", "url": "https://stackoverflow.com/questions/32477785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Network operation could not be completed - Alamofire I am using Alamofire in a Swift app I am developing. Recently whenever I try to perform a network call in the simulator iPhone5 8.1 (or any simulator 8.1) I am getting: Optional(Error Domain=NSURLErrorDomain Code=-1005 "The operation couldn’t be completed. (NSURLErrorDomain error -1005.)" UserInfo=0x7f9d148ac2c0 {NSErrorFailingURLStringKey=https:[URL REMOVED], NSErrorFailingURLKey=https:[URL REMOVED], _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSUnderlyingError=0x7f9d1273f0a0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1005.)"}) This use to work fine up until about a day ago. The only things I have changed are the servers are now sitting on Windows/IIS EC2 instances behind a load balancer and the request is no longer a HTTP but it is HTTPS. I had app transport configured when using HTTP but removed now everything is over HTTPS. I tried putting it back but still nothing. I have disabled keepalive headers on IIS but I can't seem to get any connection to go through. I have read through the comments here https://github.com/AFNetworking/AFNetworking/issues/2314 but nothing in that post works. Help please?!?!
{ "language": "en", "url": "https://stackoverflow.com/questions/37113341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "sequenced before" and "Every evaluation in the calling function" in c++ Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function. In other words, function executions do not interleave with each other. what is the meaning of "Every evaluation". #include <iostream> using namespace std; int a = 0; ing b = 0; int f(int,int) { cout << "call f, "; cout << "a=" << a << ", "; cout << "b=" << b << ", "; return 1; } int g() { cout << "call g, "; cout << "a=" << a << ", "; cout << "b=" << b << ", "; return 1; } int main() { f(a++, b++) + g(); return 0; } * *it menas evaluation of function call expression f(a++, b++), so evaluation of a++, evaluation of b++, and execution of f are all sequenced before or after the execution of g. In this case, there are two kinds of results. If evaluation of expression f(a++, b++) is sequenced before the execution of g: call f, a=1, b=1, call g, a=1, b=1, If execution of g issequenced before evaluation of expression f(a++, b++): call g, a=0, b=0, call f, a=1, b=1, 2.It means evaluation of a++, evaluation of b++, or execution of f. So evaluation of a++ may be sequenced before execution of g, evaluation of b++ and execution of f may be sequenced after execution of g. call g, a=1, b=0, call f, a=1, b=1, *It means value computation or side effect. So value computation of a++ may be sequenced before execution of g, side effect of a++, evaluation of b++ and execution of f may be sequenced after execution of g. call g, a=0, b=0, call f, a=1, b=1, In this case, f(a++, b++) + (a = g()); 1.value computation of a++ 2.execution of g 3.side effect of a++ 4.side effect of = (a = 0) 5.evaluation of b++ 6.execution of f call g, a=0, b=0, call f, a=0, b=1, Which one is right? Or other answer? I'm not an English speaker, and I'm not very good at English. I hope you can understand what i say f(h1(), h2()) + g(h3(), h4()) h1 and h2 are sequenced before f, h3 and h4 are sequenced before g. Is it possible: * *h1 *h4 *h2 *f *h3 *g A: [expr.post.incr]/1 ... The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. β€”end note ]... My reading of this is that the side effects of a++ and b++ must complete before the body of f is executed, and therefore within f it must be that a==1 and b==1. Your examples #2 and #3 are not possible with a conforming implementation. A call to g is indeterminately sequenced with a call to f, and thus can observe either pre-increment or post-increment values. A: f(a++, b++) + g(); Compiler can decide the order of execution of f() and g() in the above statement. These are only 2 possibilities not 3. Either f() will call first and modifies variables a and b OR g() will get call first.
{ "language": "en", "url": "https://stackoverflow.com/questions/30558980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reverse Indexing in Python? I know that a[end:start:-1] slices a list in a reverse order. For example a = range(20) print a[15:10:-1] # prints [15, ..., 11] print a[15:0:-1] # prints [15, ..., 1] but you cannot get to the first element (0 in the example). It seems that -1 is a special value. print a[15:-1:-1] # prints [] Any ideas? A: In Python2.x, the simplest solution in terms of number of characters should probably be : >>> a=range(20) >>> a[::-1] [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Though i want to point out that if using xrange(), indexing won't work because xrange() gives you an xrange object instead of a list. >>> a=xrange(20) >>> a[::-1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence index must be integer, not 'slice' After in Python3.x, range() does what xrange() does in Python2.x but also has an improvement accepting indexing change upon the object. >>> a = range(20) >>> a[::-1] range(19, -1, -1) >>> b=a[::-1] >>> for i in b: ... print (i) ... 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 >>> the difference between range() and xrange() learned from source: http://pythoncentral.io/how-to-use-pythons-xrange-and-range/ by author: Joey Payne A: You can assign your variable to None: >>> a = range(20) >>> a[15:None:-1] [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> A: Omit the end index: print a[15::-1] A: >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> print a[:6:-1] [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7] >>> a[7] == a[:6:-1][-1] True >>> a[1] == a[:0:-1][-1] True So as you can see when subsitute a value in start label :end: it will give you from start to end exclusively a[end]. As you can see in here as well: >>> a[0:2:] [0, 1] -1 is the last value in a: >>> a[len(a)-1] == a[-1] True A: EDIT: begin and end are variables I never realized this, but a (slightly hacky) solution would be: >>> a = range(5) >>> s = 0 >>> e = 3 >>> b = a[s:e] >>> b.reverse() >>> print b [2, 1, 0] A: If you use negative indexes you can avoid extra assignments, using only your start and end variables: a = range(20) start = 20 for end in range(21): a[start:-(len(a)+1-end):-1]
{ "language": "en", "url": "https://stackoverflow.com/questions/17610096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to create a XY chart in Java which reads data from two variables? I have difficulties understanding how to add my data to the chart object. I am simulating a supermarket activity in java program. After the simulation time is up. I have two variables time and customers. What should I use if I want the data to be added to an XY chart in java. Thanks, in advance. I have looked at JFreeChart but it seems overly complicated. A: JFreeChart is not overcomplicated. You have to try Time Series chart in your case. See here the example of how they use it. Although they leave behind the scene the main thing, which should create the data source for chart: see line final TimeSeries eur = DemoDatasetFactory.createEURTimeSeries(); I used this TimeSeries charts before, and as I remember you have to create this object and put there series of your values (probably iterating over your own values and inserting them one by one in cycle)
{ "language": "en", "url": "https://stackoverflow.com/questions/9836723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery .fadeIn() setup I have a few elements which I want to $('.hidden_item').fadeIn() when the button is clicked. So in order to do that I need to first hide them. I tried using $(document).ready(function(){ $('.hidden_item').hide(); }); But sometimes page onload sends heartbeat and my elements hidden_elements stay visible for some time. So I would like to hide them with CSS. What styling I should use to correctly hide them for later $('.hidden_item').fadeIn()? A: use .hidden_item{ display:none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/49132561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xpdf (pdftotext) with language pack call from different directory I am experimenting with xpdf (pdftotext) on a macOS Terminal. I use one language package (Japanese). Everything works fine if I call the executable like this (from the lib directory): lib kelly$ ./p2t -enc UTF-8 jp.pdf and my data structure files/lib/pdftotext files/lib/xpdfrc files/lib/jp.pdf #file to convert files/options/Enc/jp/ # Here I have the language package files and the following edited xpdfrc configuration file: #----- begin Japanese support package (2011-sep-02) cidToUnicode Adobe-Japan1 ../options/Enc/jp/Adobe-Japan1.cidToUnicode unicodeMap ISO-2022-JP ../options/Enc/jp/ISO-2022-JP.unicodeMap unicodeMap EUC-JP ../options/Enc/jp/EUC-JP.unicodeMap unicodeMap Shift-JIS ../options/Enc/jp/Shift-JIS.unicodeMap cMapDir Adobe-Japan1 ../options/Enc/jp/CMap toUnicodeDir ../options/Enc/jp/CMap #----- end Japanese support package the problem I have is to call 'pdftoext' from a different directory, for example from 'files'. In this case, the files that the configuration files is pointing to are not seen. files kelly$ ./lib/p2t -enc UTF-8 ./lib/jp.pdf I get the following error: Syntax Error: Unknown character collection 'Adobe-Japan1' And the generated file is garbage. Any idea on how the configuration file needs to be changed? A: I was able to solve a similar problem. I installed pdftotext with a brew cask. The installation was done with the following command $ brew cask install pdftotext $ pdftotext -v pdftotext version 3.03 Copyright 1996-2011 Glyph & Cog, LLC and place the xpdfrc/language support packages in the following directory I did. ls /usr/local/etc/xpdfrc /usr/local/etc/xpdfrc I downloaded the Japanese Language Pack from here. https://www.xpdfreader.com/download.html $ tree /usr/local/share/xpdf /usr/local/share/xpdf └── japanese β”œβ”€β”€ Adobe-Japan1.cidToUnicode β”œβ”€β”€ CMap β”‚ β”œβ”€β”€ 78-EUC-H β”‚ β”œβ”€β”€ 78-EUC-V β”‚ β”œβ”€β”€ 78-H β”‚ β”œβ”€β”€ 78-RKSJ-H β”‚ β”œβ”€β”€ 78-RKSJ-V β”‚ β”œβ”€β”€ 78-V β”‚ β”œβ”€β”€ 78ms-RKSJ-H β”‚ β”œβ”€β”€ 78ms-RKSJ-V β”‚ β”œβ”€β”€ 83pv-RKSJ-H β”‚ β”œβ”€β”€ 90ms-RKSJ-H β”‚ β”œβ”€β”€ 90ms-RKSJ-UCS2 β”‚ β”œβ”€β”€ 90ms-RKSJ-V β”‚ β”œβ”€β”€ 90msp-RKSJ-H β”‚ β”œβ”€β”€ 90msp-RKSJ-V β”‚ β”œβ”€β”€ 90pv-RKSJ-H β”‚ β”œβ”€β”€ 90pv-RKSJ-UCS2 β”‚ β”œβ”€β”€ 90pv-RKSJ-UCS2C β”‚ β”œβ”€β”€ 90pv-RKSJ-V β”‚ β”œβ”€β”€ Add-H β”‚ β”œβ”€β”€ Add-RKSJ-H β”‚ β”œβ”€β”€ Add-RKSJ-V β”‚ β”œβ”€β”€ Add-V β”‚ β”œβ”€β”€ Adobe-Japan1-0 β”‚ β”œβ”€β”€ Adobe-Japan1-1 β”‚ β”œβ”€β”€ Adobe-Japan1-2 β”‚ β”œβ”€β”€ Adobe-Japan1-3 β”‚ β”œβ”€β”€ Adobe-Japan1-4 β”‚ β”œβ”€β”€ Adobe-Japan1-5 β”‚ β”œβ”€β”€ Adobe-Japan1-6 β”‚ β”œβ”€β”€ Adobe-Japan1-UCS2 β”‚ β”œβ”€β”€ EUC-H β”‚ β”œβ”€β”€ EUC-V β”‚ β”œβ”€β”€ Ext-H β”‚ β”œβ”€β”€ Ext-RKSJ-H β”‚ β”œβ”€β”€ Ext-RKSJ-V β”‚ β”œβ”€β”€ Ext-V β”‚ β”œβ”€β”€ H β”‚ β”œβ”€β”€ Hankaku β”‚ β”œβ”€β”€ Hiragana β”‚ β”œβ”€β”€ Katakana β”‚ β”œβ”€β”€ NWP-H β”‚ β”œβ”€β”€ NWP-V β”‚ β”œβ”€β”€ RKSJ-H β”‚ β”œβ”€β”€ RKSJ-V β”‚ β”œβ”€β”€ Roman β”‚ β”œβ”€β”€ UniJIS-UCS2-H β”‚ β”œβ”€β”€ UniJIS-UCS2-HW-H β”‚ β”œβ”€β”€ UniJIS-UCS2-HW-V β”‚ β”œβ”€β”€ UniJIS-UCS2-V β”‚ β”œβ”€β”€ UniJIS-UTF16-H β”‚ β”œβ”€β”€ UniJIS-UTF16-V β”‚ β”œβ”€β”€ UniJIS-UTF32-H β”‚ β”œβ”€β”€ UniJIS-UTF32-V β”‚ β”œβ”€β”€ UniJIS-UTF8-H β”‚ β”œβ”€β”€ UniJIS-UTF8-V β”‚ β”œβ”€β”€ UniJIS2004-UTF16-H β”‚ β”œβ”€β”€ UniJIS2004-UTF16-V β”‚ β”œβ”€β”€ UniJIS2004-UTF32-H β”‚ β”œβ”€β”€ UniJIS2004-UTF32-V β”‚ β”œβ”€β”€ UniJIS2004-UTF8-H β”‚ β”œβ”€β”€ UniJIS2004-UTF8-V β”‚ β”œβ”€β”€ UniJISPro-UCS2-HW-V β”‚ β”œβ”€β”€ UniJISPro-UCS2-V β”‚ β”œβ”€β”€ UniJISPro-UTF8-V β”‚ β”œβ”€β”€ UniJISX0213-UTF32-H β”‚ β”œβ”€β”€ UniJISX0213-UTF32-V β”‚ β”œβ”€β”€ UniJISX02132004-UTF32-H β”‚ β”œβ”€β”€ UniJISX02132004-UTF32-V β”‚ β”œβ”€β”€ V β”‚ └── WP-Symbol β”œβ”€β”€ EUC-JP.unicodeMap β”œβ”€β”€ ISO-2022-JP.unicodeMap β”œβ”€β”€ README β”œβ”€β”€ Shift-JIS.unicodeMap └── add-to-xpdfrc 2 directories, 76 files The contents of xpdfrc are as follows $ cat /usr/local/etc/xpdfrc cidToUnicode Adobe-Japan1 /usr/local/share/xpdf/japanese/Adobe-Japan1.cidToUnicode unicodeMap ISO-2022-JP /usr/local/share/xpdf/japanese/ISO-2022-JP.unicodeMap unicodeMap EUC-JP /usr/local/share/xpdf/japanese/EUC-JP.unicodeMap unicodeMap Shift-JIS /usr/local/share/xpdf/japanese/Shift-JIS.unicodeMap cMapDir Adobe-Japan1 /usr/local/share/xpdf/japanese/CMap toUnicodeDir /usr/local/share/xpdf/japanese/CMap
{ "language": "en", "url": "https://stackoverflow.com/questions/58681637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scrapy Response Changes After Visiting Page in Web Browser Below is a spider I wrote to crawl an RSS feed and extract the first link and image title, and save them to a text file: import scrapy class artSpider(scrapy.Spider): name = "metart" start_urls = ['https://www.metmuseum.org/art/artwork-of-the-day?rss=1'] def parse(self, response): title = response.xpath('//item/title/text()').extract_first().replace(" ", "_") description = response.xpath('//item/description/text()').extract_first() lnkstart = description.find("https://image") lnkcut1 = description.find("web-highlight") lnkcut2 = lnkcut1 + 13 lnkend = description.find(".jpg") + 4 link = description[lnkstart:lnkcut1] + "original" + description[lnkcut2:lnkend] ttlstart = description.find("who=") + 4 ttlend = description.find("&rss=1") filename = "/path/to/save/folder/" + description[ttlstart:ttlend].replace("+", "_") + "-" + title + ".jpg" print(filename) print(link) filename_file = open('filename_metart.txt', 'w') filename_file.write(filename) filename_file.close link_file = open('link_metart.txt', 'w') link_file.write(link) link_file.close It goes over the Met Museum "Artwork of the Day" RSS feed and finds the newest artwork. Then parses the title and the link to the original (the link in the RSS feed is for a thumbnail) and saves them to individual text files. The title is used to generate a filename when downloading the image. I know the parse function is a mess and that the way I am saving the links and filenames is ugly. I am just starting out with Scrapy and just wanted to get the spider working because it is only a part of the broader project I am working on. The project itself draws from artwork/image/photo of the day feeds and websites, downloads the images and sets them as a desktop background slideshow. My issue is that when I set the spider off it comes back with a response of "NoneType". BUT if I go to the RSS feed in a browser (https://metmuseum.org/art/artwork-of-the-day?rss=1) AND THEN run the spider it works correctly. Process that fails * *Call scrapy crawl metart * *Output shows that the variable title has the type NoneType *Repeating step 1 results in the same output Process that works * *Open https://metmuseum.org/art/artwork-of-the-day?rss=1 in a web browser *Call scrapy crawl metart * *Successfully saves the link and filename to the relevant text files Some troubleshooting I have already done I have used a Scrapy shell to replicate exactly the process that the spider goes through and this worked fine. I went through each step that the spider goes through starting with: fetch("https://metmuseum.org/art/artwork-of-the-day?rss=1") Then typing in each line of the parse function. This works fine and results in the correct link and filename being saved WITHOUT having to open the URL in a web browser first. Just for completeness below is my Scrapy project settings.py file: BOT_NAME = 'wallpaper_scraper' SPIDER_MODULES = ['wallpaper_scraper.spiders'] NEWSPIDER_MODULE = 'wallpaper_scraper.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'cchowgule for a wallpaper slideshow' # Obey robots.txt rules ROBOTSTXT_OBEY = True I am very confused as to how the act of opening the URL in a web browser could possibly affect the response of the spider. Any help cleaning up my parse function would also be lovely. Thanks Update At 0535 UTC I ran scrapy crawl metart and got the following response: 2018-06-23 11:02:54 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: wallpaper_scraper) 2018-06-23 11:02:54 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 2.7.15 (default, May 1 2018, 05:55:50) - [GCC 7.3.0], pyOpenSSL 17.5.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.2.2, Platform Linux-4.16.0-2-amd64-x86_64-with-debian-buster-sid 2018-06-23 11:02:54 [scrapy.crawler] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'wallpaper_scraper.spiders', 'SPIDER_MODULES': ['wallpaper_scraper.spiders'], 'ROBOTSTXT_OBEY': True, 'USER_AGENT': 'cchowgule for a wallpaper slideshow', 'BOT_NAME': 'wallpaper_scraper'} 2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.logstats.LogStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.corestats.CoreStats'] 2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2018-06-23 11:02:54 [scrapy.middleware] INFO: Enabled item pipelines: [] 2018-06-23 11:02:54 [scrapy.core.engine] INFO: Spider opened 2018-06-23 11:02:54 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2018-06-23 11:02:54 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023 2018-06-23 11:02:56 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.metmuseum.org/robots.txt> (referer: None) 2018-06-23 11:02:56 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.metmuseum.org/art/artwork-of-the-day?rss=1> (referer: None) 2018-06-23 11:02:56 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.metmuseum.org/art/artwork-of-the-day?rss=1> (referer: None) Traceback (most recent call last): File "/home/cchowgule/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/home/cchowgule/WD/pyenvscrapy/wallpaper_scraper/wallpaper_scraper/spiders/metart.py", line 9, in parse title = response.xpath('//item/title/text()').extract_first().replace(" ", "_") AttributeError: 'NoneType' object has no attribute 'replace' 2018-06-23 11:02:57 [scrapy.core.engine] INFO: Closing spider (finished) 2018-06-23 11:02:57 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 646, 'downloader/request_count': 2, 'downloader/request_method_count/GET': 2, 'downloader/response_bytes': 1725, 'downloader/response_count': 2, 'downloader/response_status_count/200': 2, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2018, 6, 23, 5, 32, 57, 65104), 'log_count/DEBUG': 3, 'log_count/ERROR': 1, 'log_count/INFO': 7, 'memusage/max': 52793344, 'memusage/startup': 52793344, 'response_received_count': 2, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'spider_exceptions/AttributeError': 1, 'start_time': datetime.datetime(2018, 6, 23, 5, 32, 54, 464466)} 2018-06-23 11:02:57 [scrapy.core.engine] INFO: Spider closed (finished) I ran scrapy crawl metart 5 times with the same result. Then I opened a browser, went to https://metmuseum.org/art/artwork-of-the-day?rss=1 and ran scrapy crawl metart again. This time it worked correctly...... I just don't get it.
{ "language": "en", "url": "https://stackoverflow.com/questions/50974118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a floating widget hovering other widgets on Windows? Assume we have a wxWebView control in both window hierarchy and sizer hierarchy. How do we create a static text "loading" hovering above the wxWebView on Windows? Thanks. It's straightforward on Linux. Create a wxStaticText of which the parent/owner is the same as the wxWebView and that's all. Unfortunately, it won't work on Windows. The wxStaticText is invisible because it is covered by the wxWebView. I've tried many ways, including calling their method Lower and Raise to adjust their z-orders, but in vain. I also tried putting the text into a wxFrame and use samples/shaped/ as an example, but on the second thought, the new top-level frame may cover the GUI of other processes. So it isn't a good design. Any suggestion? Thanks. A: wxWidgets doesn't support overlapping child controls, so you would need to use a different top level window for your floating control, typically a wxPopupWindow -- then you could either draw your text in it or make wxStaticText its child.
{ "language": "en", "url": "https://stackoverflow.com/questions/71391809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Include files in sdist but not wheel I have a Python C extension that contains header files in the include folder. I am currently trying to build wheels and a source distribution. Because wheels are pre-compiled, they don't need to contain header files but the sdist does. According to the Python docs, the following files are included in a sdist: * *all Python source files implied by the py_modules and packages options *all C source files mentioned in the ext_modules or libraries options *scripts identified by the scripts option See Installing Scripts. *anything that looks like a test script: test/test*.py (currently, the Distutils don’t do anything with test scripts except include them in source distributions, but in the future there will be a standard for testing Python module distributions) *Any of the standard README files (README, README.txt, or README.rst), setup.py (or whatever you called your setup script), and setup.cfg. *all files that matches the package_data metadata. See Installing Package Data. *all files that matches the data_files metadata. See Installing Additional Files. These files are also included in the wheels as well. How can I add the header files to a sdist but not a wheel?
{ "language": "en", "url": "https://stackoverflow.com/questions/72100311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which class provides implementation for RequestDispatcher forward() and include() method Does RequestDispatcher object exits as it is an interface and as for i know we cant create an object to interface. So what is happening in following code RequestDispatcher requestDispatcher = request.getRequestDispatcher('somePage'); Are we creating object to RequestDispatcher or to subclass that implements RequestDispatcher. Thanks in advance. A: RequestDispatcher is an interface and we can't create an object obviously with that. So, it is an object of the class that implements RequestDispatcher that you get when the calling getRequestDispatcher(). You need to have the source code of the Servlet implementation(this depends on the container that you are using) to see the class that is providing the implementation. A: You are right, RequestDispatcher is an interface you we can not create an object of this. Now see: request.getRequestDispatcher('somePage'); This method returns a class which implements RequestDispatcher and that class is totally depends upon the server which you are using. For Ex. In case of Glass Fish server, it returns org.apache.catalina.core.ApplicationDispatcher object and it has already told by @Pshemo.
{ "language": "en", "url": "https://stackoverflow.com/questions/22039398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c# ValueInjecter : Mapping the whole object Graph I just started using ValueInjecter for my Entity Mappings(DTO <-> Entity). Heres my DTO : public class IncidentDTO { int ID { get; set; } string Name { get; set; } AgencyDTO agencyDTO { get; set; } } public class AgencyDTO { int ID { get; set; } string Name { get; set; } List<IncidentTypeDTO> incidentTypeDTOList { get; set; } } public class IncidentTypeDTO { int ID { get; set; } string TypeName { get; set; } } Heres my NHibernate Proxy classes : public class Incident { int ID { get; set; } string Name { get; set; } Agency agency { get; set; } } public class Agency { int ID { get; set; } string Name { get; set; } } public class IncidentType { int ID { get; set; } string TypeName { get; set; } } public class AgencyIncidentType { int ID { get; set; } Agency agency { get; set; } IncidentType incidentType { get; set; } } Now, I need to query IncidentDTO from Repository. Repository query Incident & AgencyIncidentType tables from database and map Incident -> IncidentDTO using ValueInjecter and return IncidentDTO. What is the best possible way to do the above mapping using ValueInjecter?? Thanks, Prateek A: If you want to map Incident to IncidentDTO while retaining and mapping the Agency object in the agency property (to an AgencyDTO) of an Incident instance I'd suggest renaming the agencyDTO property to agency in your IncidentDTO and then use a tweak to the CloneInjection sample from the Value Injector documentation as described here: omu.valueinjecter deep clone unlike types
{ "language": "en", "url": "https://stackoverflow.com/questions/11184596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: /bin/bash - Alfred 3 workflow does not detect php So I downloaded this plugin https://github.com/vmitchell85/alfred-vuejs-docs and I got the Powerpack. Here is me trying to execute the workflow but pressing enter at this point does nothing: After I press space and enter "vue events", I get in the debug: [2018-09-02 16:56:33][ERROR: input.scriptfilter] Code 127: /bin/bash: php: command not found Which is strange because I fire up my Terminal.app (Which uses bash) and I do php -v which gives me: PHP 7.2.8 (cli) (built: Jul 19 2018 12:15:24) ( NTS ). Same thing on my zsh profile. What do I do? A: Look at the image you posted. There's a Script Filter object on the Alfred Editor. You just have to double-click on it and replace php vuejs.php "{query}" with /usr/local/bin/php vuejs.php "{query}".
{ "language": "en", "url": "https://stackoverflow.com/questions/52141329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to focus to a block when cursor at start of line with Slate JS? I am using Slate JS. I have some code, which should focus a given block (move the cursor there). The use case here is: press / to open a modal, then when the modal closes, we want to refocus to the block we were at before. To do this, we use Transforms.select(). Something like this: getCurrentBlock(editor: Editor) { const { selection } = editor; if (!selection) { return { block: null, anchor: null, focus: null }; } const { anchor, focus } = selection; const { path } = anchor const block = editor.children[path[0]] as Block; return { block, anchor, focus }; } const focusBlock = (editor, path) => { ReactEditor.focus(editor); Transforms.select(editor, { anchor: { path: [path[0], 0], offset: 0 }, focus: { path: [path[0], 0], offset: 0 }, }); } It generally works in all cases like this: const { block, anchor, focus} = getCurrentBlock(editor) const { path } = anchor focusBlock(editor, path) However, it does not work when the position of the cursor is at the start of a line. i.e. when offset = 0. In this case, the focus moves the cursor to the very top of the page. Why might this be happening, and how can I make it focus the block in question, even when the cursor is at the start of the line? A: Solved this by doing: refocusEditor({ editor }: { editor: Editor }) { const block = Editor.above(editor, { match: (n) => Editor.isBlock(editor, n), }); const path = block ? block[1] : []; ReactEditor.focus(editor); // @ts-ignore Transforms.setSelection(editor, path); }
{ "language": "en", "url": "https://stackoverflow.com/questions/74337796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QObject::connect: no such signal. Also, Qtimer not calling I have a class, myClass: class myClass : public QObject { Q_OBJECT public: QQuickWidget* widget; QString mystring; myClass (QQuickWidget* quickWidget, QString string); void myfunction(); public slots: void slot(); signals: void clicked(); }; myClass::myClass(QQuickWidget* quickWidget, QString string) : widget(quickWidget), mystring(string) { QTimer::singleShot(60000, this, SLOT(slot())); myfunction(); } void myClass::slot() { } void myClass::myfunction() { widget->setVisible(true); widget->setSource(QUrl("qrc:/qmlsource.qml")); connect(widget, SIGNAL(clicked()), this, SLOT(slot())); } What I want to do is to call the slot() function 60 seconds after I create a myClass object. That doesn't happen. Also, at the connect line I get QObject::connect: No such signal QQuickWidget::clicked() message. I would appreciate if someone could help me. A: So, I think you have a few issues here. 1. QWidget The big one is that QWidget (which QQUickWidget inherits from) does not have a signal called "clicked", so the message QObject::connect: No such signal QQuickWidget::clicked() is quite right ;) What you need to do is create your own object that inherits from QQuickWidget and then re-implement/overload the function void QWidget::mousePressEvent(QMouseEvent * event) and/or void QWidget::mouseReleaseEvent(QMouseEvent * event) These are the functions that are called in the widget that you can then emit your signal. Which means you also need to add a new signal into you your widget. So your new class header may look a bit like (just including the main elements): class MyQQuickWidget: public QQuickWidget { Q_OBJECT public: MyQQuickWidget(QWidget *parent = 0); signals: void clicked(); protected: void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; }; And then in your implementation: void MyQQuickWidget::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { emit clicked(); } } Then when you connect your MyQQuickWidget signal clicked() to MyClass slot slot() it will connect ok. 2. QTimer It looks like your timer should fire... but there appears to be no debug in the slot slot() so how would you know if this is working or not?
{ "language": "en", "url": "https://stackoverflow.com/questions/33609803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to properly get the int for totalEntries in MySQL database using PHP? I'm using PHP and a MySQL database to build a website. However, I find PHP quite horrible compared to other languages I have learnt previously. Largely because I seem to find a lot of instructions online which are over 5 years old and they just don't work. For example the accepted answer here: select count(*) from table of mysql in php I have this code so far, but it gives me error (undefined index $recordCount = $row['totalEntries'];). // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM games ORDER BY id DESC LIMIT $startRow, $rowsPerPage"; $result = $conn->query($sql); $sql = "SELECT COUNT(*) as totalEntries FROM games"; $results = $conn->query($sql); $row = $result->fetch_assoc(); $recordCount = $row['totalEntries']; echo "<br/> record count = " . $recordCount; $totalPages = ceil($recordCount / $rowsPerPage); $pagination = "<div class='pagination'>"; for ($i = 0; $i <= $totalPages; $i++) { $pagination .= "<a href='index.php?page=" . $i . "'>" . $i . "</a>"; echo 'wtf!'; } $pagination .= "</div>"; echo ' <br/> pagination = ' . $pagination; I also tried: $recordCount = Count($row); and $recordCount = Count($result->num_rows); and many other parameters passed into Count but they always return either 1 or 7(which is the number of COLUMNS) I guess I find PHP so hard to learn because I don't have a good IDE for it and am using Notepad++. Can anyone tell me how we get the Count of all entries in the table after I have done the SELECT statement as in the above code? A: $conn = new \mysqli('127.0.0.1', 'dev', 'SoMuchDev', 'test', '3306'); $result = $conn->query('select * from test'); while ($row = $result->fetch_assoc()) { $res[] = $row; } $res['total'] = $result->num_rows; echo "<pre>"; var_export($res);die(); http://php.net/manual/en/class.mysqli-result.php As for editors, PhpStorm is widely used but afaik there's only a 30 day trial use. You could also give notepad ++ a try, I think it has some php plugins for autocomplete and what not.
{ "language": "en", "url": "https://stackoverflow.com/questions/51114716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does the path in an action of the following action-mapping mean What does the path in an action of the following action-mapping mean .Does it specify the jsp page from which a request is coming (search.jsp)? <action-mappings> <action path="/search" type="SearchAction" name="searchForm" scope="request" validate="true" input="/search.jsp"> </action> </action-mappings> A: The path refers to the name of the action you call from your HTML or jsp file. For eg - <html:form action="Name" name="nameForm" type="example.NameForm"> The corresponding action mapping will be something like - <action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp"> <forward name="success" path="/displayname.jsp"/> Check out this link for a complete example.
{ "language": "en", "url": "https://stackoverflow.com/questions/11222859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ReactJS: What's the real world use of Immutability Helpers in React? React's official document provide Immutability Helpers. What would be some real world usage of such helpers? I think I am missing something really basic here. A: React assumes that objects set in state are immutable, which means that if you want to add or remove some element inside your array you should create new one with added element keeping previous array untouched: var a = [1, 2, 3]; var b = React.addons.update(a, {'$push': [4] }); console.log(a); // [1, 2, 3]; console.log(b); // [1, 2, 3, 4]; By using immutable objects you can easily check if content of object has changed: React.createClass({ getInitialState: function () { return { elements: [1, 2, 3] }; }, handleClick: function() { var newVal = this.state.elements.length + 1; this.setState({ elements: React.addons.update(this.state.elements, { '$push': [ newVal ] }) }) }, shouldComponentUpdate: function (nextProps, nextState) { return this.state.elements !== nextState.elements; }, render: function () { return ( <div onClick={this.handleClick}>{ this.state.elements.join(', ') }</div> ); } }); A: ReactJS state should preferably be immutable. Meaning that, everytime render() is called, this.state should be a different object. That is: oldState == newState is false and oldState.someProp == newState.someProp is also false. So, for simple state objects, there's no doubt they should be cloned. However, if your state object is very complex and deep, cloning the entire state might impact performance. Because of that, React's immutability helpers is smart and it only clones the objects that it thinks it should clone. This is how you do it when you clone the state by yourself: onTextChange: function(event) { let updatedState = _.extend({}, this.state); // this will CLONE the state. I'm using underscore just for simplicity. updatedState.text = event.text; this.setState(updatedState); } This is how you do it when you let React's immutability helpers determine which objects it should actually clone: onTextChange: function(event) { let updatedState = React.addons.update(this.state, { text: {$set: event.text} }); this.setState(updatedState); } The above example will perform better then the first one when the state is too complex and deep. A: React application prefer immutability, there are two ways (from Facebook) to support immutability, one is to use immutable.js that is a complete immutability library, another one is the immutable helper that is a lightweight helper. You only need to choose one to use in one project. The only disadvantege of immutable.js is that it leak itself throughout your entire application including the Stores and View Components, e.g., // Stores props = props.updateIn(['value', 'count'], count => count + 1); // View Components render: function() { return <div>{this.props.getIn("value", "count")}</div>; } If you use immutable helper, you can encapsulate the immutability operations at the place where updates happen (such as Stores and Redux Reducers). Therefore, your View Components can be more reusable. // Stores or Reducers props = update(props, { value: {count: {$set: 7}} }; // View Components can continue to use Plain Old JavaSript Object render: function() { return <div>{this.props.value.count}</div>; }
{ "language": "en", "url": "https://stackoverflow.com/questions/28032173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Compatibility of textbox AutoCompleteMode and keyPress event, C# I have a textbox tbx. For it I had an event handler: public void tbxPress(object sender, KeyPressEventArgs e) { MessageBox.Show("message 1"); if (e.KeyChar == 13) // i.e. on Enter { MessageBox.Show("message 2"); } } and it worked perfect until I set AutoCompleteMode parameter of tbx. After that auto-complete works fine, but on Enter i don't get "message 2". ... the hell?! VC#2008EE A: You can use the KeyDown event and check e.KeyCode == Keys.Enter.
{ "language": "en", "url": "https://stackoverflow.com/questions/3247046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RTC value in stm32 Nucleo I'm trying to print RTC date and time on Tera Term. But I'm getting errors mentioned in code. Also nothing is being printed on Tera term. I have used pointer as the declaration for Setdate and Getdate have mentioned. Also there are few warning such as 1)format '%d' expects a matching 'int' argument [-Wformat=] 2)passing argument 2 of 'HAL_RTC_GetDate' from incompatible pointer type [-Wincompatible-pointer-types] 3)passing argument 2 of 'HAL_RTC_SetDate' from incompatible pointer type [-Wincompatible-pointer-types] #include "main.h" #include "stdio.h" //uint8_t Time[6]="HH:MM:SS"; //uint8_t Date[6]="DD/MM/YY"; int main(void) { /* USER CODE BEGIN 1 */ typedef struct { uint8_t Month = 0x03; uint8_t Date = 0x24; uint8_t Year = 0x21; }Date_struct; uint8_t *Date; Date = &Date_struct; Error: Expected expression before Date_struct HAL_RTC_SetDate(&hrtc, &Date, RTC_FORMAT_BCD); while (1) { HAL_RTC_GetDate(&hrtc,&Date, RTC_FORMAT_BCD); HAL_Delay(1000); } } A: I frankly don't have experience with Tera Term in particular, but I've programmed Atmel MCUs before and there seem to be issues with your general C code, rather than the MCU functions. The C compiler errors can be often hard to read, but I can see you're mixing up the structure definition, declaration and initialization, as well as struggle with pointers. Consider the following plain C code and let's go over the differences with yours. #include <stdio.h> #include <stdint.h> int main(void) { struct date_struct { uint8_t month; uint8_t date; uint8_t year; }; // Define a structure named date_struct typedef struct date_struct date_struct_type; // make 'struct date_struct' into a new type date_struct_type date; // Declare a variable of the new type date.month = 0x03; // Initialize the fields of the variable date.date = 0x24; date.year = 0x21; date_struct_type * date_ptr; // Create a new pointer to the struct date_ptr = &date; // Assign the address of the variable to the pointer // Use the pointer to adress the structure's values printf("Month: %d\nDate: %d\nYear: %d\n", date_ptr->month, date_ptr->date, date_ptr->year); // ... or pass the pointer into any hypothetical function // func(date_ptr); // ... or pass a reference to the structure, but never a reference to the pointer // unless you know that you need it! // func(&date); return 0; } In your code, you first define an anonymous local structure and immediately typedef it to create a new type. That means, from that point on, you work with the structure as if it was just a variable type. In my code, I split up the structure definition and the typedef into two individual statements. That code is identical to writing typedef struct date_struct { uint8_t Month; uint8_t Date; uint8_t Year; } date_struct_type; // Define and typedef a structure at the same time ... or we can even leave the structure's name out and leave it anonymous - like you did in your code - we don't need it named at all since we already have a new type made out of it that we can use. typedef struct // <-- leave out the name { uint8_t Month; uint8_t Date; uint8_t Year; } date_struct_type; // Define and typedef a structure at the same time However, a structure definition is a "template" that tells the compiler how to allocate and access the structure in memory. The definition itself doesn't store any values and as such, we can't assign to it. We first need to declare a variable of that type*. date_struct_type date; * C is a very wild language, and you can do and use all sorts of shorthands, such as this. However, I strongly recommend against doing this when you're just starting out (and also in the future), as it's really not needed and is harder to read, maintain and debug. With the variable in place, we can finally assign our values to the individual elements of the structure. When accessing members of a structure we use the member reference operator - .. date.month = 0x03; date.date = 0x24; date.year = 0x21; Now we're moving to pointers and the two magical operators - * and & in C, that often cause a lot of headaches. In your code, you've successfully declared a pointer with this: uint8_t *Date;. Here, the * is not an operator, it signifies the variable holds a pointer - in other words, the uint8_t *Date; says "There is a variable named Date and it will hold an address of a uint8_t variable somewhere in the memory". However, that is not what we intend - we want to point to our new structure, not the uint8_t. Pointers all have the same size (in your case 32 bits on the smt32 platform), so it works, but that's what's setting off the "incompatible pointer type" warnings of your compiler. Instead, we should declare a pointer of the same type as the variable we intend to "point at" using this pointer. We'll once again split up the declaration and assignment statements for clarity - we're doing two things, writing them as one statement is just a shorthand. date_struct_type * date_ptr; The assignment is where the & operator comes into play. The & operator takes any variable and returns an address to it - which is exactly the thing we want to store inside our pointer. date_ptr = &date; Now whenever we want to pass a pointer to our new structure, either we use the one we just created - date_ptr, or directly pass a reference to the structure - &date. Both are viable, but be sure to not mistakenly write this: &date_prt. This gives you a pointer to a pointer, which is not something you usually want. A few more things. When accessing member of a structure through a pointer to that structure, we have to use a structure dereference operator - ->. That's why the printf statement contains -> operators instead of just .. I'm sure with this you can tweak your code to have it work. There shouldn't be any more issues in your function calls and the infinite while loop, just pay attention which pointers are you passing into the HAL_RTC_SetDate and HAL_RTC_GetDate functions. Do ask in the comments if there's still anything unclear or not working!
{ "language": "en", "url": "https://stackoverflow.com/questions/66780883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get __dirname of a file before webpack bundling I'm making and app that deals with serialization and dynamic imports: I serialize objects of some class with something like this fs.write('savename.json', JSON.stringify(someObject.getSerializable()), () => console.log('done')) this way though I don't get to save the constructor name or any info about the prototype or stuff, so I save the constructor name in a property type like this: export default class SomeObjectClass { // [...] getSerializable(): string { return { type: this.constructor.name, ...this } } } but in this way I don't save its full path, so when I try to dynamically import it with const plainObject = fs.readFileSync('savename.json').toString(); const ctor = await import(plainObject.type); const object = new ctor.default(); // this fails it just fails, because the module was in a nested folder somewhere in my project. I tried to concatenate __dirname like this export default class SomeObjectClass { // [...] getSerializable(): string { return { type: path.join(__dirname, this.constructor.name), ...this } } } but it doesn't work because after bundling __dirname returns the path relative to the distribution folder that has different structure than my source folder. So. How do I get the file path before webpack processing at runtime? Alternative solutions to the problem are obviously welcome. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/58260693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XAML WinRT Chart Remove Axis Label Im Using the Chart library "ModernUI Toolkit" (http://modernuitoolkit.codeplex.com/). How can I remove the Label in WinRT? I found some answers but it was for the Silverlight version and this does not work with this library. Here is my XAML Code: <Chart:Chart x:Name="LineChart" HorizontalAlignment="Left" Title="Line Chart" Margin="24,222,0,0" VerticalAlignment="Top" Width="318" Height="342"> <Series:StackedLineSeries x:Name="StackedLineSeries"> </Series:StackedLineSeries> </Chart:Chart> A: I think it might be something like this: <Series:StackedLineSeries.IndependentAxis> <Series:LinearAxis xmlns:datavis="using:WinRTXamlToolkit.Controls.DataVisualization"> <Series:LinearAxis.TitleStyle> <Style TargetType="datavis:Title"> <Setter Property="Visibility" Value="Collapsed"/> </Style> </Series:LinearAxis.TitleStyle> </Series:LinearAxis> </Series:LineSeries.IndependentAxis>
{ "language": "en", "url": "https://stackoverflow.com/questions/23485200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using angular 1 simple with express js I have used node js with handlebars and now want to move towards the proper MEAN stack. I have learned angular1 and using it with single page node js apps. But when it comes to express, after doing "express project-name" I start my server by "npm start" and in the "views" lies my html and angular code. How will by angular app there will interact or will run with my nodejs, I have scratched my head all over youtube videos and questions here but didn't find a satisfactory answer. What I want to work in angular is:- $http.get('/users/signup',function(res){ console.log(res.data); } and in nodejs users.js route resides this:- router.get('/signup',function(req,res,next){ res.send("req recieved here"); } How will the req from angular be made to the server running using npm start?? A: Try this:- router.get('/signup',function(req,res){ res.send("Any data"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/44995451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Applying filter to a dropdown list - ngoptions I have a method that returns the list of custom types, those values are being used in both the dropdown lists, but now I want to remove a subset of them based on the type and then add to first drop down. I am using angular js, asp.net mvc. What is the best way to apply filter even before data is being rendered and keeping the same method. Below is the method in the controller which returns names and departments as a json response. Now I want this method to return two different json objects one with subset of the current set being returned based on department they belong to. Public JsonResult GetDetails() { List<Cust> Customers = new List<Cust>(); Customers = GetCustomerDetails(); var name = Customers.Select(e => new{e.custname}).Distinct().ToList(); var dept = Customers.Select(e => new{e.deptname}).Distinct().ToList(); var response = new{CustomerNames = name, CustomerDepartments = dept}; return Json(response, JsonRequestBehaviour.AllowGet(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/38707875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JTextfield not updating when calling `setText()` This is a music player. It works fine, but when I try to create a Jframe around I fail. I have 3 jTextfields that should present me the playtime and the remaining playtime. But in the program they dont update. import java.awt.*; import java.awt.event.*; import java.io.File; import java.awt.Container; import java.awt.Dimension; import java.awt.Toolkit; import java.io.File; import java.io.IOException; import java.io.InputStream; // import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiSystem; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Sequencer; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.*; import javax.swing.event.*; /** * * Beschreibung * * @version 1.0 vom 26.10.2015 * @author */ public class test extends JFrame { // Anfang Attribute private static File chossen = new File(""); private static int x=1; private static JTextField jTextField1 = new JTextField(); private static JTextField jTextField2 = new JTextField(); private static JTextField jTextField3 = new JTextField(); private JLabel jLabel1 = new JLabel(); private JLabel jLabel2 = new JLabel(); private JLabel jLabel3 = new JLabel(); private static JProgressBar jProgressBar1 = new JProgressBar(); private JButton jButton1 = new JButton(); private JButton jButton2 = new JButton(); private JButton jButton3 = new JButton(); // Ende Attribute public test(String title) throws MidiUnavailableException { // Frame-Initialisierung super(title); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); int frameWidth = 574; int frameHeight = 412; setSize(frameWidth, frameHeight); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int x = (d.width - getSize().width) / 2; int y = (d.height - getSize().height) / 2; setLocation(x, y); setResizable(false); Container cp = getContentPane(); cp.setLayout(null); // Anfang Komponenten jTextField1.setBounds(400, 8, 150, 20); cp.add(jTextField1); jTextField2.setBounds(400, 32, 150, 20); cp.add(jTextField2); jTextField3.setBounds(400, 56, 150, 20); cp.add(jTextField3); jLabel1.setBounds(288, 8, 110, 20); jLabel1.setText("Gesamte Dauer"); cp.add(jLabel1); jLabel2.setBounds(288, 32, 110, 20); jLabel2.setText("Aktuelle Dauer"); cp.add(jLabel2); jLabel3.setBounds(288, 56, 110, 20); jLabel3.setText("Verbleibend"); cp.add(jLabel3); jProgressBar1.setBounds(280, 88, 270, 16); cp.add(jProgressBar1); jButton1.setBounds(480, 344, 75, 25); jButton1.setText("Start"); jButton1.setMargin(new Insets(2, 2, 2, 2)); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { jButton1_ActionPerformed(evt); } catch (MidiUnavailableException | InvalidMidiDataException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); cp.add(jButton1); jButton2.setBounds(400, 344, 75, 25); jButton2.setText("Stop"); jButton2.setMargin(new Insets(2, 2, 2, 2)); jButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { jButton2_ActionPerformed(evt); } catch (MidiUnavailableException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidMidiDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); cp.add(jButton2); jButton3.setBounds(8, 8, 267, 73); jButton3.setText("Dateiauswahl"); jButton3.setMargin(new Insets(2, 2, 2, 2)); jButton3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jButton3_ActionPerformed(evt); } }); cp.add(jButton3); // Ende Komponenten setVisible(true); } // end of public test // Anfang Methoden public static void main(String[] args) throws MidiUnavailableException { new test("test"); } // end of main public void test(int zahl) throws MidiUnavailableException, InvalidMidiDataException, IOException, InterruptedException{ final Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); if(zahl==2){ sequencer.setSequence(MidiSystem.getSequence(chossen)); sequencer.setTempoFactor(1); sequencer.start(); System.out.println("start"); Thread.sleep(5000); System.out.println("tettstdt"); x=1; while(x==1){ long z = sequencer.getMicrosecondLength()/1000/1000; long y=sequencer.getMicrosecondPosition()/1000/1000; jProgressBar1.setMinimum(0); jProgressBar1.setMaximum((int) z); jTextField1.setText(z+"s"); z = sequencer.getMicrosecondLength()/1000/1000; y=sequencer.getMicrosecondPosition()/1000/1000; System.out.println(z+" "+y); jProgressBar1.setValue((int) y); jTextField2.setText(y+"s"); jTextField3.setText("s"); if(z-y==0){ x=0; } } }else if(zahl==3){ System.out.println("stop fehlerhaft"); sequencer.stop(); }else{ System.out.println("fehler"); } } public void jButton1_ActionPerformed(ActionEvent evt) throws MidiUnavailableException, InvalidMidiDataException, IOException, InterruptedException { System.out.println(chossen); test(2); } public void jButton2_ActionPerformed(ActionEvent evt) throws MidiUnavailableException, InvalidMidiDataException, IOException { // test(3); } public void jButton3_ActionPerformed(ActionEvent evt) { File chossen2 = new File("C:/Users/Eric/workspace/Komplex/midi/"+ (dic())); chossen = chossen2; } public static String dic() { File f = new File("C:/Users/Eric/workspace/Komplex/midi"); JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(f); int state = fc.showOpenDialog( null ); if ( state == JFileChooser.APPROVE_OPTION ) { File file = fc.getSelectedFile(); return file.getName(); } else return ""; } } When I print the information to console it works. A: Call the repaint() method to force the JTextField to repaint itself using the current options set.
{ "language": "en", "url": "https://stackoverflow.com/questions/33365806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ClickOnce Deployed to Multiple Network Shares We have several offices around the US and one in India. Our IT department setup a system where we copy files and directories to a specific shared folder on a local server and it will be distributed to another office. In other words, we have a folder on a local server called "To India". When I copy a folder there it will be sent to India using UDP (or whatever speedier than Windows file transfer method) to a folder called "From East Coast US Office". I have a ClickOnce application that I deploy to a local network share that our developers use. Our QA team in India also wants to be able to use this application. I set up a job that copies the contents of the deployment folder to the shared network folder every hour. All this works flawlessly. In India they get the ApplicationFiles directory, setup program, and "application" file just as it appears where I deploy it locally. They run the setup program, but instead of downloading the application files from their local machine it starts downloading the application files (dlls, etc) from where application was originally deployed. This is a big deal for us because some of the 3rd party DLLs are rather large (50+ mb) and the transfers are often dropped causing the install to fail. Is there a way to deploy to multiple locations or edit some file through a script so that when the India QA team installs from their local server the files are pulled from there (and updates look to that folder too)? I've looked at several files in notepad. It seems like I may have to edit the ".application" file somehow. Any ideas? PS: I know this sounds like a ServerFault or SuperUser question, but I figure that since it is specifically related to the functionality of ClickOnce it is probably better addressed here first. A: It appears that this is as designed. Click-once applications are designed to be deployed to one location. You can specify an update location, but these locations become static once the application is deployed. The best bet for anyone looking to do this would be some sort of content hosting solution ala Akamai. I tried to come up with a solution similar to that but my IT/Network Admin skills are lacking.
{ "language": "en", "url": "https://stackoverflow.com/questions/8490116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you set the datasource of a combo and set the text value on load I want to populate combos with the same list of data from the "modules" table however, depending on what is in the "completedModules" data table I will set the text value to a particular item on the load. Setting the data source seems to override the set text value. With ComboBox1 .FlatStyle = FlatStyle.Popup .ValueMember = modules.Columns("id").ColumnName .DisplayMember = modules.Columns(0).ColumnName .DataSource = modules .Text = completedModules.Rows(0).Item(0).ToString End With
{ "language": "en", "url": "https://stackoverflow.com/questions/55845857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I group values to an array for the same field value in jq? I have json data that looks like [ { "session": "ffe887f3f150", "src_ip": "81.71.87.156" }, { "session": "fff42102e329", "src_ip": "143.198.224.52" }, { "session": "fff9c8ca82be", "src_ip": "159.203.97.7" } ] I've managed to filter out unique values of session but there can be more sessions linked to a same src_ip. Now I would like to merge the dataset in a way so that I have grouped session ID's to src_ip at one place such as [ ... { "src_ip": "81.71.87.156" "sessions": ["ffe887f3f150","fff42102e329"] }, ... ] This is somewhat similar to question asked here: How do I collect unique elements of an array-valued field across multiple objects in jq? , however I struggle to transform that for my scenario. A: With group_by you can group by any criteria given, then assemble all grouped items by taking their common .src_ip from any of them (eg. the first), and .sessions as a mapped array on .session from all of them. Add other parts as you see fit. jq 'group_by(.src_ip) | map({src_ip: .[0].src_ip, sessions: map(.session)})'
{ "language": "en", "url": "https://stackoverflow.com/questions/72217255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call file dialog box in access form application I am using access 2000 to write an form application. I need to open a file dialog box to select a file and extract the file path. The solution should be compatible to all version of access from 97 and above, and it should not require any extra module to be pre-installed in the user's computer. No third party library, only native call to windows api. P.S. I need detail steps which shows me where to add the code. A: For these kind of Access FAQs, you should always try the Access Web as a starting point for searching (though the search interface sucks -- it's easier to search the site with Google). That site is the official FAQ site for a number of the non-MS Access newsgroups. It doesn't get updated often, but the code is still quite useful, precisely because it answers questions that are asked frequently. The code you need is in one of the API modules, helpfully titled Call the standard Windows File Open/Save dialog box A: That should be "...to write a form application." There is an unsupported declare not into the Windows API but into msaccess.exe itself. It was first publicized, I believe, in the AccessDeveloper's Handbook. I'm not on my development machine at the moment but I can look it up when I get there. Or, you can probably find it yourself without too much trouble.
{ "language": "en", "url": "https://stackoverflow.com/questions/5958911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: selecting columns by colSums and filtering by rowSums in data.table library(data.table) a <- mtcars setDT(a) b <- a[,colSums(.SD)>500,.SDcols=setdiff(names(a),c("vs","am"))] In this contrived example, IΒ΄d like to select the columns fulfilling the colSums condition, without using the vs and am columns. The code above just results in a logical vector of the correct columns, but without actually selecting the desired entire columns into a new dt. Moreover, the setdiff solution to .SDcols seems quite terse and verbose. Is there a more efficient/succint syntax to do this - I tried using .SDcols=-c("vs","am") to no help? A: We can use .SD to select to columns based on the logical vector library(data.table) a[, .SD[, colSums(.SD)>500, with = FALSE],.SDcols=setdiff(names(a),c("vs","am"))] If we wanted to do rowSums, just use that as index d <- a[, .SD[rowSums(.SD)>300],.SDcols=-c(8,9)] Or with Reduce a[, .SD[Reduce(`+`, .SD) > 300], .SDcols = -c(8, 9)] If we need to get all the columns, use .I instead of .SD a[a[, .I[Reduce(`+`, .SD) > 300], .SDcols = -c(8, 9)]]
{ "language": "en", "url": "https://stackoverflow.com/questions/61192887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending objects to another class's ArrayList I have a project for class where I have to send information from a driver class to a class holding an ArrayList, before separating them it worked fine but now I cannot figure out how to send the items to the second class, they are Driver and CardStack respectfully: import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Driver{ public static void main( String[] args ){ CardStack cs = new CardStack(); //what to do with this? MathCard m1 = new MathCard(7, "+", 6); System.out.println(m1); MathCard m2 = new MathCard(18, "*", 2); MathCard m3 = new MathCard(112, "-", 94); MathCard m4 = new MathCard(2, "/", 2); VocabCard vc1 = new VocabCard("Who was the first President of the United States?", "George Washington."); VocabCard vc2 = new VocabCard("What comes after A?", "B."); VocabCard vc3 = new VocabCard("What is the tune to the Alphabet Song?", "Twinkle Twinkle Little Star."); VocabCard vc4 = new VocabCard("Is Pluto a planet?", "Not any more."); cs.add( m1 ); cs.add( m2 ); cs.add( m3 ); cs.add( m4 ); cs.add( vc1 ); cs.add( vc2 ); cs.add( vc3 ); cs.add( vc4 ); } } And the CardStack class: import java.util.ArrayList; import java.util.Collections; public class CardStack{ private ArrayList< FlashCard > FlashCards; public CardStack(){ ArrayList< FlashCard > FlashCards = new ArrayList< FlashCard >(); Collections.shuffle(FlashCards); for( FlashCard fc : FlashCards ){ System.out.println("Test1 " + fc); } } } Any suggestions? A: As per comments, the solution is to create an add(...) method inside of your CardStack class where in the method, add the parameter to the ArrayList. If I posted the code in this answer (which is only 3 lines of code), I'd be cheating you of the opportunity of first trying it yourself. Please check out your text book or a basic Java tutorial on methods and on passing information into methods (please see links) and give it a go. You may surprise yourself with what you come up with. In pseudocode: public void add method that takes a FlashCard parameter add the FlashCard parameter to the FlashCards ArrayList End of method
{ "language": "en", "url": "https://stackoverflow.com/questions/31307123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Error handling in collection environment I have a macro that copies the content of a input table to an output table using the header names stored in a collection. Code: Sub Process_Data() Dim rawSht As Worksheet Dim procSht As Worksheet Dim headers As Collection Dim c As Integer Dim v As Variant Set rawSht = ThisWorkbook.Worksheets("Backend - raw") Set procSht = ThisWorkbook.Worksheets("Backend - processed") Set headers = New Collection For c = 1 To rawSht.Cells(4, Columns.Count).End(xlToLeft).Column headers.Add c, rawSht.Cells(4, c).Text Next For c = 5 To 50 On Error GoTo ErrorHandler rawCol = headers(procSht.Cells(8, c).Text) v = rawSht.Range(rawSht.Cells(5, rawCol), rawSht.Cells(Rows.Count, rawCol).End(xlUp)).Value2 procSht.Cells(9, c).Resize(UBound(v, 1)).Value = v ErrorHandler: Next End Sub I now tried to handle the error if I would insert a column in the output table, with a header not contained in the collection of headers from the input table. My solution with On Error GoTo ErrorHandler and then ErrorHandler: Next works if there is no more than 1 inserted column at a time (e.g. 2 or more inserted columns following each other returns an error). It also does not work if the inserted column is at the beginning or at the end of the output table. What I would like to do is: If the header is found in the collection, copy & paste the data from input table, if the header is not found in the collection, go to the next header, if the next header is empty, stop the macro. A: You can do something like this: For c = 5 To 50 rawCol = vbNullString On Error Resume Next rawCol = headers(procSht.Cells(8, c).Text) On Error Goto 0 if rawcol <> vbnullstring then v = rawSht.Range(rawSht.Cells(5, rawCol), rawSht.Cells(Rows.Count, rawCol).End(xlUp)).Value2 procSht.Cells(9, c).Resize(UBound(v, 1)).Value = v End If Next
{ "language": "en", "url": "https://stackoverflow.com/questions/33475678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySql : How do I generate a query to combine more then 2 tables? I have to generate an SQL query to fetch more than 1 table data with and without matching values and display the results. I used Left Join. However, it is not displaying all the values. My result needs to get all the questions and their corresponding answers for all the products, And also suggest me, Is there any flaw in the database table design? Thanks for your help. SQL SELECT product.product_name AS 'Product', question.question_id AS 'Id', question.question_name AS 'Question', answer.answer_value AS 'Answer' FROM question LEFT JOIN answer ON question.question_id = answer.question_id LEFT JOIN assessment ON answer.assessment_id = assessment.assessment_id LEFT JOIN product ON product.product_id = assessment.product_id ORDER BY question.question_id The above SQL generated only the questions which had answers not all the questions
{ "language": "en", "url": "https://stackoverflow.com/questions/40268213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing gcc 7.4.0 on CentOs 7 does not update my version of libstdc++ I am using CentOs7 on VirtualBox. I need the 6.0.20 version of libstdc++ at minimum. I installed gcc 7.4.0 on my system from source using the instructions given here: https://linuxhostsupport.com/blog/how-to-install-gcc-on-centos-7/ gcc --version prints gcc (GCC) 7.4.0 as expected. Running strings /usr/lib64/libstdc++.so.6|grep GLIBCXX prints: GLIBCXX_3.4.1 GLIBCXX_3.4.2 GLIBCXX_3.4.3 GLIBCXX_3.4.4 GLIBCXX_3.4.5 GLIBCXX_3.4.6 GLIBCXX_3.4.7 GLIBCXX_3.4.8 GLIBCXX_3.4.9 GLIBCXX_3.4.10 GLIBCXX_3.4.11 GLIBCXX_3.4.12 GLIBCXX_3.4.13 GLIBCXX_3.4.14 GLIBCXX_3.4.15 GLIBCXX_3.4.16 GLIBCXX_3.4.17 GLIBCXX_3.4.18 GLIBCXX_3.4.19 According to https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html, my version of GLIBCXX should be 3.4.24 A: Do you have a /usr/local/lib64/libstdc++.so.6? Typically only package installs have /usr prefix; the default for anything else is /usr/local. I'd check where your GCC was installed because I think you're examining the wrong file. You should find that your one is ultimately a link to a libstdc++.so.6.0.24. GLIBCXX_3.4.19 implies GCC 4.8.3+ which (from memory) is the CentOS 7-packaged GCC.
{ "language": "en", "url": "https://stackoverflow.com/questions/57328037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting a period in field based on range Thank you all in advance for any help. I'm Still very new to access and have no idea where to start to find a solution. What I am trying to do is to auto populate a field in my table called "Period". I would like to have it use the "Activity_Date" to look into a different table that has date ranges that reference to the correct period. Based on which "Period" the "Activity_Date" falls under will return the correct "Period". I've tried using calculated data type and queries and I feel no closer to an answer than when I started. Thanks again for your time. A: I would question why you NEED to populate the field period in your table. In short, I wouldn't bother. The period it is in can be derrived from the activity date field that is in the same record. So you can write select statements that calc the period for the record in your MyTable as required. SELECT TableWithPeriods.period, MyTable.activity_date FROM MyTable LEFT JOIN TableWithPeriods ON MyTable.activity_date BETWEEN TableWithPeriods.StartDate AND TableWithPeriods.EndDate If you need to access the period a lot then there is an argument for keeping a period value in the MyTable in step with the TableWithPeriods. Keeping in step could be akward though as what if someone changes one of the period 's dates? Keeping in step might mean writing a bit of SQL to update ALL MyTable rows that wither do not have the period set or when the period is now different. A VBA update statement will look a bit like the SELECT above. Or you could use database the onchange macros that respond to data being added or updated in the MyTable (and the TableWithPeriods, if users can change dates). Anyway, there's my opinion. I would NOT copy the value over. PS I'm not 100% sure about the SQl I gave above, this might work though SELECT TableWithPeriods.period, MyTable.activity_date FROM MyTable LEFT JOIN TableWithPeriods ON ( MyTable.activity_date >= TableWithPeriods.StartDate AND MyTable.activity_date <= TableWithPeriods.EndDate )
{ "language": "en", "url": "https://stackoverflow.com/questions/32464474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change width of a lookup column I've created a lookup with two columns, first one containing and integer which works just fine but the second one has a long name and this is where the problem arises. Users should horizontally scroll in order to check the entire string and even in that case, the column's width is not big enough to display the whole data. I've found this : Adjusting column width on form control lookup But i don't understand exactly where and what to add. I am not sure but maybe I have to add the fact that this lookup is used on a menu item which points to an SSRS report, in the parameters section. Update 1: I got it working with a lookup form called like this : Args args; FormRun formRun; ; args = new Args(); args.name(formstr(LookupOMOperatingUnit)); args.caller(_control); formRun = classfactory.formRunClass(args); formRun.init(); _control.performFormLookup(formRun); and in the init method of this form i added: public void init() { super(); element.selectMode(OMOperatingUnit_OMOperatingUnitNumber); } meaning the field i really need. I am not sure i understand the mechanism completely but it seems it knows how to return this exact field to the DialogField from where it really started. In order to make it look like a lookup, i have kept the style of the Design as Auto but changed the WindowType to Popup, HideToolBar to Yes and Frame to Border. A: Probably the best route is do a custom lookup and change the extended data type of the key field to reflect that. In this way the change is reflected in all places. See form FiscalCalendarYearLookup and EDT FiscalYearName as an example of that. If you only need to change a single place, the easy option is to override performFormLookup on the calling form. You should also override the DisplayLength property of the extended data type of the long field. public void performFormLookup(FormRun _form, FormStringControl _formControl) { FormGridControl grid = _form.control(_form.controlId('grid')); grid.autoSizeColumns(false); super(_form,_formControl); } This will not help you unless you have a form, which may not be the case in this report scenario. Starting in AX 2009 the kernel by default auto-updates the control sizes based on actual record content. This was a cause of much frustration as the sizes was small when there was no records and these sizes were saved! Also the performance of the auto-update was initially bad in some situations. As an afterthought the grid control autoSizeColumns method was provided but it was unfortunately never exposed as a property. A: you can extends the sysTableLookup class and override the buildFromGridDesign method to set the grid control width. protected void buildFormGridDesign(FormBuildGridControl _formBuildGridControl) { if (gridWidth > 0) { _formBuildGridControl.allowEdit(true); _formBuildGridControl.showRowLabels(false); _formBuildGridControl.widthMode(2); _formBuildGridControl.width(gridWidth); } else { super(_formBuildGridControl); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/34434080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Access an object with automatic storage duration from another thread I stumbled upon this question: Thread access to stack of another thread. Linked question is about plain C, but my main language is C++, so I tried to find if the same rules apply to C++. I found this section in C11 draft N1570: 6.2.4.5 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals. The result of attempting to indirectly access an object with automatic storage duration from a thread other than the one with which the object is associated is implementation-defined. I believe corresponding section from C++20 draft N4810 is [basic.stc.auto] and it does not mention this case. C++11 draft has exactly the same text as C++20 in this part. Under [intro.multithread] I've found this sentence with footnote: Every thread in a program can potentially access every object and function in a program. An object with automatic or thread storage duration (6.6.5) is associated with one specific thread, and can be accessed by a different thread only indirectly through a pointer or reference (6.7.2). So I assume in C++ it's always fine to access an object with automatic storage duration from another thread (until the end of an object's lifetime and if there is no data race of course). Is that correct? A: You are correct, the line you quoted for C++ effectively establishes that all threads in a C++ program see the same address space. One of the cornerstones of the C++ object model is that every living object has a unique address [intro.object]/9. Based on [intro.multithread]/1, you can pass a pointer or reference to an object created in one thread's automatic or thread-local storage to another thread and access the object from that second thread as long as the object is guaranteed to exist and there are no data races… Interestingly, the C standard doesn't appear to explicitly give similar guarantees. However, the fact that different objects have different addresses and the address of an object is the same from the perspective of each thread in the program would still seem to be an implicit, necessary consequence of the rules of the language. C18 specifies that the address of a live object doesn't change [6.2.4/2], any object pointer can be compared to a pointer to void [6.5.9/2], and two pointers compare equal if and only if they point to the same object [6.5.9/6]. Storage class is not part of the type of a pointer. Thus, a pointer pointing to an object in the automatic storage of one thread must compare unequal to a pointer to some other object in the automatic storage of another thread, as well as to a pointer pointing to some object with different storage duration. And any two pointers pointing to the same object in automatic storage of some thread must compare equal no matter which thread got these pointers from where in what way. Thus, it can't really be that the value of a pointer means something different in different threads. Even if it may be implementation-defined whether a given thread can actually access an object in automatic storage of another thread via a pointer, I can, e.g., make a global void*, assign to it a pointer to an object of automatic storage from one thread, and, given the necessary synchronization, have another thread observe this pointer and compare it to some other pointer. The standard guarantees me that the comparison can only be true if I compare it to another pointer that points to the same object, i.e., the same object in automatic storage of the other thread, and that it must be true in this case… I cannot give you the exact rationale behind the decision to leave it implementation-defined whether one thread can access objects in automatic storage of another thread. But one can imagine a hypothetical platform where, e.g., only the thread a stack was allocated for is given access to the pages of that stack, e.g., for security reasons. I don't know of any actual platform where this would be the case. However, an OS could easily do this, even on x86. C is already based on some, arguably, quite strong assumptions concerning the address model. I think it's a good guess that the C standards committee was simply trying to avoid adding any more restrictions on top of that…
{ "language": "en", "url": "https://stackoverflow.com/questions/55885240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Siri Shortcut integration in Apple watch 
What i want to achieve is i am developing one app which gives store list located all over the world. I want to implement one feature in which when i say Siri to search near by stores than it redirect me to the my app with filter of near by stores in 10 miles so can you please guide me is there any other way to achieve it?
 I have try to achieve this using siri shortcut. I have iphone 6s (OS 13.3.1). I have created Siri shortcut both manually and programatically which work perfectly in my iphone but when i try to access same shortcut in paired watch (Series 4, OS 5) it gives me error "I do not recognise that command". 
 A: Sounds like a bug with Siri for watchOS, I would report it in Feedback Assistant with logs attached.
{ "language": "en", "url": "https://stackoverflow.com/questions/60703992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a string as an argument to a `do.call` command? How can I pass a string (e.g. "na.rm=TRUE") as an argument to a do.call command? For example this works as expected: > do.call(mean, list(1:10, na.rm=TRUE)) [1] 5.5 But what if I get the argument na.rm=TRUE as a string: "na.rm=TRUE"? If I try the following then it fails: > do.call(mean, list(1:10, "na.rm=TRUE")) Error in mean.default(1:10, "na.rm=TRUE") : 'trim' must be numeric of length one > do.call(mean, list(1:10, na.rm="na.rm=TRUE")) Error in if (na.rm) x <- x[!is.na(x)] : argument is not interpretable as logical So given an argument in form of a string ("na.rm=TRUE"), how can I use it in a do.call command? To give a bit more background, the GUI in question is for dcast in reshape2. The user can input in two separate boxes: * *the function name * *say, user_fun <- "mean", that is then passed to dcast(fun.aggregate=get(user_fun)) *the function args * *say, user_ags <- "na.rm=TRUE", that is then passed to dcast(...) via do.call So at the end of the day it would look something like: do.call(dcast, list(data_set, form, fun.aggregate=user_fun, user_ags)) As you can see, I have trouble with fitting the user_ags into do.call. For all I know the user_ags can contain any number of arguments in it and of any possible type (say, user_ags <- "na.rm=TRUE, other.arg='both', yet.another=NULL"). So I am looking for a generic way to parse such a string, such as a eval(parse(text="")) approach or similar. I tried various combinations of eval, parse, deparse, substitute, all to no avail.. A: Here's a method that does not use eval but does wrap the params in a fake function call and uses parse to extract them #sample function myfun<-function(...) { print(list(...)) } strparam <- "na.rm=TRUE, plot=F, age=15" params <- as.list(parse(text=paste0("f(", strparam , ")"))[[1]])[-1] do.call(myfun,params) A: If the input format follows some specification, you can always do string processing: fun <- "mean" args <- "trim=0.1, na.rm=FALSE" args <- strsplit(args, ",", fixed=TRUE) args <- strsplit(args[[1]], "=", fixed=TRUE) names(args) <- gsub(" ", "", sapply(args, "[", 1), fixed=TRUE) args <- lapply(args, "[", -1) args <- lapply(args, type.convert) do.call(get(fun), c(list(1:10), args)) #[1] 5.5 mean(1:10, trim=0.1, na.rm=FALSE) #[1] 5.5 But it's always dangerous to allow arbitrary input.
{ "language": "en", "url": "https://stackoverflow.com/questions/25160165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I match an element with a name such as "data[title]" in a selector? I have an element like this: <input type="text" name="data[title]" /> Is it possible to match that input element based on it's name? This does not work: input[name=data[title]] {} I'm using the latest release of Chrome. A: You need to use quotes: input[name="data[title]"] {}
{ "language": "en", "url": "https://stackoverflow.com/questions/15979162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure DocumentDB and Spring Boot conflict In my spring boot application I run this simple code client.getDatabaseAccount() in two places: 1) In main method. Before spring boot is "booted", DocumentClient works great!!! public static void main(String[] args) { // just to test if it can connect to cosmos db before spring boot starts DocumentClient client = new DocumentClient("URL","KEY", new ConnectionPolicy(), ConsistencyLevel.Session); // this runs great and connects to azure cosmos db. client.getDatabaseAccount(); SpringApplication.run(DemoApplication.class, args); } 2) In a Service class. When the below method (with the exact same code client.getDatabaseAccount()) is called, it throws an exception @Service @Component public class TestService { public DocumentClient connectCosmos() throws Exception { DocumentClient client = new DocumentClient("URL","KEY", new ConnectionPolicy(), ConsistencyLevel.Session); // this throws an exception client.getDatabaseAccount(); } } ERROR: Execution encountered exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target, status code 403 sub status code null. Clearly there is no problem with certificate since the two exact pieces of code run within the same SpringBootApplication Here is the POM azure-documentdb <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>azure-documentdb</artifactId> <version>2.4.7</version> </dependency> Why does this happen? My only guess is Spring Boot doesn't like azure-documentdb. How to execute azure-documentdb code within Spring Boot. I DON'T WANT TO USE Azure Document DB Spring Boot Starter because my spring boot backend database is something else, and I only need azure-documentdb to retreive little data. I don't want Azure Document DB Spring Boot Starter to backup the whole Spring Boot project as ORM. So is it possible to have azure-documentdb pom inside of a spring boot project? A: John I did something very similar to what you tried and it worked for me without any issue. @Service public class CosmosService { public void connectCosmos() throws Exception { DocumentClient client = new DocumentClient("https://somename-cosmosdb.documents.azure.com:443/", "somepassword", new ConnectionPolicy(), ConsistencyLevel.Session); client.getDatabaseAccount(); FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); List<Document> result = client .queryDocuments( "dbs/" + "samples" + "/colls/" + "orders", "SELECT * FROM c", options) .getQueryIterable() .toList(); result.stream().forEach(System.out::println); } } Application class @SpringBootApplication public class RatellaStackApplication implements CommandLineRunner { @Autowired CosmosService cosmosService; public static void main(String[] args) { SpringApplication.run(RatellaStackApplication.class, args); } @Override public void run(String... args) throws Exception { cosmosService.connectCosmos(); System.exit(0); } } Dependency <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>azure-documentdb</artifactId> <version>2.4.7</version> </dependency> calling the service method from the controller works too. @RestController public class MyController { @Autowired CosmosService cosmosService; @GetMapping("/hello") public String hello() throws Exception { cosmosService.connectCosmos(); return "OK"; } } Link to the source code of the Rest API. For simplicity I put everything in the SpringBoot Application class. https://gist.github.com/RaviTella/e544ef7b266ba425abead7f05193f717 A: How about getting the documentClient from applicationContext instead of initializing a new one. Let spring initialize one for you. @Autowired private ApplicationContext applicationContext; DocumentClient documentClient = (DocumentClient) applicationContext.getBean(DocumentClient.class); What version of Spring Boot are you using ? Are you using spring-data-cosmosdb SDK ?
{ "language": "en", "url": "https://stackoverflow.com/questions/61783327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can not access imported accounts in paypal development environment just found that PayPal changed their Sanbox, now I need real PayPal account to develop. Ok, I went to my real one, imported my test sandbox accounts into it. Then, I go to one of these accounts on developer.paypal.com, and click "sandbox site" link. I expect that it will go to sandbox site where I can log in with this test account. But instead after clicking the link I'm getting "please login to use PayPal sandbox features" message on paypal.sandbox.com, that has a link to developer.paypal.com, where I'm logged in already. So, I don't know any way to log in with my test accounts now. Please help. A: This is a known issue due to transition from old sandbox to the new site. You need to delete your cookies and re-login to access the sandbox site. Please note that IE has permanent cookies stored on file system that need to be deleted. Firefox or Chrome would work better than IE8.
{ "language": "en", "url": "https://stackoverflow.com/questions/15594050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doxygen: C typedef names in description do not become links I am using Doxygen on C header files, and I have trouble getting the occurrences of typedef names in description text to become links to the respective typedef definition. This works nicely with structures, but not with typedefs. Example: struct _my_s1; /** Description for typedef my_s1. */ typedef struct _my_s1 my_s1; struct _my_s2; /** Description for typedef my_s2. */ typedef struct _my_s2 my_s2; /** * @brief Structure _my_s1 */ struct _my_s1 { my_s2 * s2t; ///< pointer to my_s2 struct _my_s2 * s2s; ///< pointer to struct _my_s2 /** * @brief Function f2t * @param s2t A pointer to my_s2. * @return An integer. */ int (*f2t)(my_s2* s2t); /** * @brief Function f2s * @param s2s A pointer to struct _my_s2. * @return An integer. */ int (*f2s)(struct _my_s2* s2s); }; /** * @brief Structure _my_s2 */ struct _my_s2 { int a; ///< integer }; In the output, all occurrences of the typedef name my_s2 in any description text become just plain text. All occurrences of struct _my_s2 become links to the structure definition. I added the description lines for the typedef definitions after reading How should I classify a typedef with Doxygen? (I was speculating that Doxygen maybe needs to have documentation on something before that something can be the target of a link), but adding the description did not help. How can I have Doxygen create links to typedefs, like it does for structs? I am using doxygen 1.8.6 on Ubuntu 14.04. I do not get any errors when running doxygen on the example above (there is also @file and @defgroup, not shown here). Andy
{ "language": "en", "url": "https://stackoverflow.com/questions/30804504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Accelerated (with HAXM) android mac emulator freezes Situation: I have android x86 accelerated emulator on Mac OS X. It starts normally (and shows HAX is working and emulator runs in fast virt mode line) and I can run programs. After program being launched emulator works some time and freezes, so I cannot interact with it. Example: if I call adb shell ls -l /sdcard/ (or many other adb commands) nothing is printed in console and I must press control+C to return control. After emulator restart problem vanishes and after time it occurs again. Works right on not-accelerated emulator. Works wrong only with HAXM turned on. I have tried to * *Reinstall android SDK *Create emulators with different properties *Run on another mac machine *Reboot emulator/computer *Enable 64-bit Kernel and Extensions (was disabled) I need to make emulator working all the time (not only first N minutes). That's not a duplicate to this question because of: * *Mac OS X version is lower than 10.9 and I cannot use hotfix Intel provided *No crash observed here *Computer doesn't freeze (but emulator stops work) *Freeze occurs after emulator has been working for time (up to 30 min) Possibly relates to this question, but * *cannot analyze is it the same question *no helpful answers there System information: Model Identifier:iMac10,1 Memory:8 GB System Version:Mac OS X 10.6.8 (10K549) Kernel Version:Darwin 10.8.0 HAXM release 1.0.6 It met Intel requirements Supported Operating Systems: Mac OS X* 10.6 Snow Leopard and 10.7 Lion (32/64-bit) Making setup I followed instructions from developer.android. I allocated 2048 Mb during HAXM install and created emulator with 512 Mb RAM. There are some messages in dmesg in the meantime. History: 1) After emulator was started (it works) Kext com.intel.kext.intelhaxm not found for unload request. 13 possible map ffffffffffffffff cpu_online_map 3 haxm_error: fc_msr haxm_error: fc_msr 5 5 haxm_error: vt_enablhaxm_error: vt_enable e 1 haxm_error: nx_enable 1 haxm_error: nx_enable 2048 2048 haxm_error: ---- HAXM release 1.0.6 -------- haxm_error: This log collects runnging status of HAXM driver. haxm_error: set memlimit 0x80000000 2) After some time passed (it still works!) 23 possible map ffffffffffffffff cpu_online_map 3 haxm_error: fc_msr h5 axm_error: fc_msr h5 ahaxm_error: vt_enable xm_error: vt_enable 1 1 haxm_error: nx_haxm_error: nx_enable ena2048 ble 2048 haxm_error: ---- HAXM release 1.0.6 -------- haxm_error: This log collects runnging status of HAXM driver. .......hax_vm_create_ui 0 cvcpu 0x1d803000 vmid 0 vcpu_id 0 minor id 1000before the crate node setup hax tunnel request for already setup one haxm_error: hax_vm_alloc_ram: size 0x20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC haxm_error: Memory allocation, va:123787000, size:20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: ...........hax_teardown_vm .......hax_vm_create_ui 0 cvcpu 0x1d585800 vmid 0 vcpu_id 0 minor id 1000before the crate node setup hax tunnel request for already setup one haxm_error: hax_vm_alloc_ram: size 0x20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC haxm_error: Memory allocation, va:123637000, size:20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: ...........hax_teardown_vm .......hax_vm_create_ui 0 cvcpu 0x1d7a8800 vmid 0 vcpu_id 0 minor id 1000before the crate node setup hax tunnel request for already setup one haxm_error: hax_vm_alloc_ram: size 0x20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC haxm_error: Memory allocation, va:123637000, size:20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 3) After emulator hung .......hax_vm_create_ui 0 cvcpu 0xf5e5000 vmid 0 vcpu_id 0 minor id 1000before the crate node setup hax tunnel request for already setup one haxm_error: hax_vm_alloc_ram: size 0x20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC haxm_error: Memory allocation, va:123641000, size:20000000 haxm_error: !VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 haxm_error: hax_vm_alloc_ram: size 0x20000 haxm_error: spare alloc: mem_limit 0x0, size 0x20000, spare_ram 0x5800000 haxm_error: VM_STATE_FLAGS_MEM_ALLOC: spare_ram 0x5800000 Please excuse me for all these similar logs but I do hope they can help in diagnostics. I didn't find other output facing with freezes. Am I doing something wrong here? Can I somehow fix/workaround these freezes? P.S. $ top PID COMMAND %CPU TIME #TH #WQ #POR #MREG RPRVT RSHRD RSIZE VPRVT VSIZE PGRP PPID STATE UID FAULTS COW MSGSENT MSGRECV SYSBSD SYSMACH CSW PAGEINS 35308 emulator64-x 99.9 93:35.44 2/1 1 67 114 13M 18M- 179M 297M 3459M 35303 35303 running 503 180922 477 134488 1390 604431027+ 1732 83769+ 7 A: Not sure if you still running into this issue or not but your on an older release of Intel's HAXM. The current release is: HAX 1.0.8 Download I saw your post and kept getting a crash. When tailing the /var/log/system.log on Mac OSX 10.9 I would see your above messages. When I tried to reinstall the HAX I would see the below: Aug 19 12:03:55 3c15c2cf84fe kernel[0]: haxm_error: -------- HAXM release 1.0.7 -------- Aug 19 12:03:55 3c15c2cf84fe kernel[0]: haxm_error: This log collects runnging status of HAXM driver. Aug 19 12:03:55 3c15c2cf84fe kernel[0]: haxm_error: set memlimit 0x80000000 I was able to resolve my issue by removing all of the AVD's that I created with Android Studio. From the AVD (Android Virtual Devices) just "Delete" all the emulators in your Virtual devices. Then start over. If you get the below ERROR: Do the following: * *Open up a Terminal Window. *Type: ~/.android/avd *From here remove everything by this command: rm -rf . *NOTE: you will delete everything in the path that you run it from. All ways good to do: pwd <-- Print working directory so see what you will be removing. *Start up the AVD again and recreate the devices you want. I hope that helps someone. A: Please make sure that the memory you allocate for the emulator during install is always greater than the memory you specify while creating an instance of the emulator. A: I would want to check that there are no faults with the RAM on the machine. If the memory is faulty, it could mean that data is lost and the emulator doesn't know how to cope with this situation. CNET cover how to test memory on a Mac in this recent article http://www.cnet.com/uk/how-to/how-to-test-the-ram-on-your-mac/ It will take a long while to do the extended test, but it does need ruling out if you want to find the problem here.
{ "language": "en", "url": "https://stackoverflow.com/questions/22967573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to use oracle flash recovery option? I an using oracle 10g and I want to use flash recovery option to recover the deleted table by accidently.How to achieve this?
{ "language": "en", "url": "https://stackoverflow.com/questions/32208447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java.io.FileNotFoundException: null\gallery2.jpg (The system cannot find the path specified) java.io.IOException: An exception occurred processing JSP page /upimg.jsp at line 43 String s23=f1.getString(); String fpath=request.getRealPath("files")+"\\"+filename; 43: f1.write(new File(fpath)); A: You have encountered a FileNotFoundException, which means the file you search doesn't exist in the path you have declared. Check whether you have given the correct path. And if you are sure about the path, then make sure the file you search is available in that path.
{ "language": "en", "url": "https://stackoverflow.com/questions/56373229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-7" }
Q: Solr SSl self sign certificate I have a problem with solr 8_4 SSL. I can't connect with https://localhost:8983 ,but http://localhost:8983 is worked. I am use https://lucene.apache.org/solr/guide/8_4/enabling-ssl.html for configuring SSL with self sign certificate. Setting made are : SOLR_SSL_ENABLED=true SOLR_SSL_KEY_STORE=/opt/solr/server/etc/solr-ssl.keystore.jks SOLR_SSL_KEY_STORE_PASSWORD=secret SOLR_SSL_TRUST_STORE=/opt/solr/server/etc/solr-ssl.keystore.jks SOLR_SSL_TRUST_STORE_PASSWORD=secret SOLR_SSL_NEED_CLIENT_AUTH=false SOLR_SSL_WANT_CLIENT_AUTH=false SOLR_SSL_CLIENT_HOSTNAME_VERIFICATION=false SOLR_SSL_KEY_STORE_TYPE=JKS SOLR_SSL_CHECK_PEER_NAME=true
{ "language": "en", "url": "https://stackoverflow.com/questions/62796317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS timer wont stop I'm running the following code, i'm trying to when it gets to 10 seconds, stop the timer basically var mytimeout; $scope.startTimer = function() { $scope.counter = 0; $scope.onTimeout = function() { $scope.counter++; $log.info($scope.counter); if ($scope.counter == 10) { $scope.stop(); $state.go($state.current.name, {}, { reload: true }) } mytimeout = $timeout($scope.onTimeout, 1000); } mytimeout = $timeout($scope.onTimeout, 1000); } $scope.stop = function(){ $log.info("Stop"); $timeout.cancel(mytimeout); } The log goes like: angular.js:10126 1 angular.js:10126 2 angular.js:10126 3 angular.js:10126 4 angular.js:10126 5 angular.js:10126 6 angular.js:10126 7 angular.js:10126 8 angular.js:10126 9 angular.js:10126 10 angular.js:10126 Stop angular.js:10126 11 angular.js:10126 12 angular.js:10126 13 A: Your counter is indeed stoppping, but you then reassign mytimeout after the if statement so the timer starts again. I'm guessing the $state.go() still runs but the counter continues in the console. Instead, call the timer if less than 10, otherwise call the resolving function. $scope.startTimer = function() { $scope.counter = 0; $scope.onTimeout = function() { $log.info($scope.counter); if($scope.counter < 10){ mytimeout = $timeout($scope.onTimeout, 1000) }else{ $scope.stop(); $state.go($state.current.name, {}, { reload: true }) } $scope.counter++; } mytimeout = $timeout($scope.onTimeout, 1000); }
{ "language": "en", "url": "https://stackoverflow.com/questions/27822669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automatically create a nested for loop using a list of ranges? I want to create a nested for loop that uses a list of integer numbers for the loops' ranges, just as follows: a = [5,4,7,2,7,3,8,3,8,9,3,2,1,5] for i in range(a[0]): for j in range(a[1]): for k in range(a[2]): for l in range(a[3]): ... ... ... do_some_function() Is there a way that I can do it automatically? A: You will be able to iterate over the permutations of the list's ranges with for items in itertools.permutations(range(item) for item in a): items will contain the sequence with one item from each range. Note: The approach is very time and resource consuming. It might be good to consider if the concept your question is based on can be optimized.
{ "language": "en", "url": "https://stackoverflow.com/questions/53815138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How to remove spaces between editText boxes Hi I have an LinearLayout inside FrameLayout , the linear layout contains few edittext fields but there is a lot of space between each edittext, I want to decrease the space between each editfield. Please help XML <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center"> <ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/bg_reddotted" android:scaleType="centerInside" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_main" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_margin="0dp" android:padding="0dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Almost done! Please verify your info and provide your mobile number" android:singleLine="false" /> <EditText android:id="@+id/edit_fname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="First Name (Required)" /> <EditText android:id="@+id/edit_lname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Surname Name (Required)" /> <EditText android:id="@+id/edit_email" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Email (Required)" /> <EditText android:id="@+id/edit_phone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Mobile Number (Optional)" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="β€œSign Up”" android:paddingBottom="10dp" android:gravity="center_horizontal" android:paddingTop="10dp" /> <Button android:id="@+id/btn_signup" android:layout_width="100dp" android:layout_height="wrap_content" android:text="Sign Up" android:layout_gravity="center_horizontal" android:padding="12dp" android:background="@drawable/btn_grey_square" /> </LinearLayout> </FrameLayout> A: Use android:paddingTop attribute together with EditText view with negative dps. Example: <EditText android:id="@+id/edit_fname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="First Name (Required)" android:paddingTop=-3dp /> Based on your requirement you can apply to any of these attributes. android:paddingLeft android:paddingRight android:paddingBottom android:paddingTop A: use negative margins instead of padding...
{ "language": "en", "url": "https://stackoverflow.com/questions/7488717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't save a PIL image file after cropping out extra transparent pixels I have this function that takes svg logos, converts them to png (first for loop), removes the extra redundant transparent pixels and saves it to its destination folder (second for loop). def convert_to_png(source_path, destination_path, output_w, output_h): if not os.path.exists(destination_path): os.mkdir(destination_path) # Turns SVG images to to PNG for i in os.listdir(source_path): new_file_name = i.split('.') new_file_name = new_file_name[0] cairosvg.svg2png(url=source_path + str(i), write_to=destination_path + str(new_file_name) + '.png', output_width=output_w, output_height=output_h) for j in os.listdir(destination_path): img = cv2.imread(destination_path + j, cv2.IMREAD_UNCHANGED) img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA) logo = Image.fromarray(np.uint8(img)).convert('RGBA').crop().getbbox() logo.save(destination_path + j, 'PNG') This is how I call the function: convert_to_png(current_dir + '/riot_sponsors/', current_dir + '/new_logos/', 2000, 1500) For some reason, I am getting this error: logo.save(destination_path + j, 'PNG') AttributeError: 'tuple' object has no attribute 'save' My goal is to save the new cropped out png files to the destination_path A: .getbbox() returns a tuple of the left, right, upper, and lower coordinates. This is what is returned to the logo variable. If you want to remove transparent portions of the image, use the following code: logo = Image.fromarray(np.uint8(img)).convert('RGBA') logo = logo.crop(logo.getbbox())
{ "language": "en", "url": "https://stackoverflow.com/questions/65962663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cURL variable empty I am using charts.js and trying to load data from a JSON API using cURL to pass to the chart. So I am using a PHP variable to pass to JavaScript. I did a test in ajax and it worked, but wanting to use cURL I cannot figure out the issue. I created an if statement that it will print out nothing on an empty variable and that's what it has been doing, so I believe the issue is with cURL. <?php $url = "https://api.coindesk.com/v1/bpi/historical/close.json?currency=btc"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($curl); if(!empty($data)) { $data = $btc; } else { print ("nothing"); } curl_close($curl); ?> <body> <canvas id="myChart" width="250px" height="250px"></canvas> <script> jsonData=<?php echo $btc ?>; var jsonLabels=[]; var jsonValues=[]; for(x in jsonData['bpi']){ jsonLabels.push(x); jsonValues.push(jsonData['bpi'][x]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/55800492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to scroll away the uiview and have a continuous ui collection view I have a problem with the uiview and a ui collection view in a fixed position. Is there a way to scroll the ui view upwards and have an infinite ui collection view under with content? I want the whole view to be uicollection. Is there something I have to do with my constraints? --uiview ----uiview << sorta like a header for the page which can be scrolled up and out of the way. But once at the top, they will see it again. ----uicollection view <<< whole view should push up a continuous ui collection view Currently the uiview and uicollection view are on the same layer. A: You are looking to add a header to your UICollection views. There are MANY tutorials that can help you. This one here can get you started: http://www.appcoda.com/supplementary-view-uicollectionview-flow-layout/
{ "language": "en", "url": "https://stackoverflow.com/questions/29731421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to compute stride mean in Pytorch? For example, we have x = [1, 2, 3, 4, 5] with stride = 3, step = 1, then the stride mean would be result = [2, 3, 4]. More specifically, I have a vector with shape = (batch_size, sequence_len, embed_dim), and I want to perform the above operation on dim = 1 (sequence_len). How can I implement that efficiently in PyTorch? A: I think what you mean - in PyTorch notation - is a kernel size of 3 and a stride of 1. You can use torch.nn.AvgPool1d to perform this kind of operation: mean = nn.AvgPool1d(kernel_size=3, stride=1) Note, you will need one extra dimension, for the channel, to be compatible with this kind of layer: >>> x = torch.tensor([[1, 2, 3, 4, 5]]).unsqueeze(0) tensor([[[1, 2, 3, 4, 5]]]) >>> mean(x) tensor([[[2, 3, 4]]])
{ "language": "en", "url": "https://stackoverflow.com/questions/65629678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: collapse This tag is deprecated and should not be used. This tag has been deprecated due to lacking discriminating power. Instead, use a tag related to the library that the collapse function belongs to.
{ "language": "en", "url": "https://stackoverflow.com/questions/18385340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to cast COM object of type 'FAXCOMEXLib.FaxServerClass' Hi All, I have created a Dotnet Application using Dotnet 4.0 Programming language as VB.Net4.0. I have a Windows Service which sends out Fax Document using FaxComexLib Com Component, i have its Inetrop.FaxComexLib.dll, it works great in Windows 7 and Window 2008 Server, i can send out Faxes without any problems. I have a Legacy Client which Windows XP home with ServicePack3 , i installed my WindowsService there and the Service Works fine other than communicationg with the FaxComexLib Com Component. I tried Several Possible solutions, i copied the the Registry entry({571CED0F-5609-4F40-9176-547E3A72CA7C}) from windows 7 to windows XP, Still no luck Here is my exception: System.InvalidCastException: Unable to cast COM object of type 'FAXCOMEXLib.FaxServerClass' to interface type 'FAXCOMEXLib.IFaxServer2'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{571CED0F-5609-4F40-9176-547E3A72CA7C}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)). at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, Boolean& pfNeedsRelease) at FAXCOMEXLib.FaxServerClass.Connect(String bstrServerName) Any Solutions for this would be greatly appeciated. Thanks In advance Suresh A: It's been a looong time since I used FaxComExLib, but if memory serves, you need to install the Fax printer or something for XP, it is not installed by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/11302289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS, different expand and collapsed behavior in Firefox and IE I have an panel which has expand menu and other like: When I expand panel in IE 10 and Firefox 55.0.3, it seems like this: But in chrome, it works well There is two part on .tbl-main.Expandable search panel and result panel(tbl-container). I use flex layout to cover parent.Search panel is only 15px here.Rest of .tbl-main must be .tbl-container.It is okey here. But Browsers behave strange. Here my html and css codes .tbl-main { height: 100%; box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3); display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ display: -moz-box; /* OLD - Firefox 19- (doesn't work very well) */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: -webkit-flex; /* NEW - Chrome */ display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */ -webkit-box-direction: normal; -moz-box-direction: normal; -ms-flex-direction: column; -webkit-flex-direction: column; flex-direction: column; } .tbl-searchpanel { min-height: 15px; background: yellow; } .tbl-container { min-height: 50px; background-color: blue; -webkit-box-flex: 1; -moz-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; } .tbl-searchpanel input { display: none; visibility: hidden; } .tbl-searchpanel label { display: block; padding: 0.5em; text-align: center; border-bottom: 1px solid #CCC; color: #666; background-color: lightcoral; min-height: 100%; } .tbl-searchpanel label:hover { color: #000; } .tbl-searchpanel label::before { font-family: Consolas, monaco, monospace; font-weight: bold; font-size: 15px; content: "+"; vertical-align: central; display: inline-block; width: 20px; height: 20px; margin-right: 3px; background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%); } #expand { width: 100%; height: 250px; overflow: hidden; transition: height 0.5s; /*background: url(http://placekitten.com/g/600/300);*/ /*color: #FFF;*/ background-color: red; display: none; } #toggle:checked~#expand { display: block; } #toggle:checked~label::before { content: "-"; } <div class="tbl-main"> <div class="tbl-searchpanel"> <input id="toggle" type="checkbox" /> <label for="toggle"></label> <div id="expand"></div> </div> <div class="tbl-container"> </div> </div> A: Remove the min-height: 100%; from the .tbl-searchpanel label rule Stack snippet html, body { height: 100%; margin: 0; } .tbl-main { height: 100%; box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3); display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ display: -moz-box; /* OLD - Firefox 19- (doesn't work very well) */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: -webkit-flex; /* NEW - Chrome */ display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */ -webkit-box-direction: normal; -moz-box-direction: normal; -ms-flex-direction: column; -webkit-flex-direction: column; flex-direction: column; } .tbl-searchpanel { min-height: 15px; background: yellow; } .tbl-container { min-height: 50px; background-color: blue; -webkit-box-flex: 1; -moz-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; } .tbl-searchpanel input { display: none; visibility: hidden; } .tbl-searchpanel label { display: block; padding: 0.5em; text-align: center; border-bottom: 1px solid #CCC; color: #666; background-color: lightcoral; /* min-height: 100%; removed */ } .tbl-searchpanel label:hover { color: #000; } .tbl-searchpanel label::before { font-family: Consolas, monaco, monospace; font-weight: bold; font-size: 15px; content: "+"; vertical-align: central; display: inline-block; width: 20px; height: 20px; margin-right: 3px; background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%); } #expand { width: 100%; height: 250px; overflow: hidden; transition: height 0.5s; /*background: url(http://placekitten.com/g/600/300);*/ /*color: #FFF;*/ background-color: red; display: none; } #toggle:checked~#expand { display: block; } #toggle:checked~label::before { content: "-"; } <div class="tbl-main"> <div class="tbl-searchpanel"> <input id="toggle" type="checkbox" /> <label for="toggle"></label> <div id="expand"></div> </div> <div class="tbl-container"> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/46419353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Very basic multiprocessing example with pool.apply() never calls function or terminates I am trying to set up the very basic example of multiprocessing below. However, the execution only prints here and <_MainProcess(MainProcess, started)> and pool.apply() never even calls the function cube(). Instead, the execution just keeps running indefinitely without termination. import multiprocessing as mp def cube(x): print('in function') return x**3 if __name__ == '__main__': pool = mp.Pool(processes=4) print('here') print(mp.current_process()) results = [pool.apply(cube, args=(x,)) for x in range(1,7)] print('now here') pool.close() pool.join() print(results) I have tried various other basic examples including pool.map() but keep running into the same problem. I am using Python 3.7 on Windows 10. Since I am out of ideas, does anybody know what is wrong here or how I can debug this further? Thanks! A: Thank you, upgrading to Python 3.7.3 solved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/55446710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cannot change text to handwriting using pywhatkit Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Temp\tempCodeRunnerFile.python", line 2, in <module> pywhatkit.text_to_handwriting(""" File "C:\Users\HP\AppData\Roaming\Python\Python311\site-packages\pywhatkit\handwriting.py", line 22, in text_to_handwriting raise exceptions.UnableToAccessApi("Unable to access Pywhatkit api right now") pywhatkit.core.exceptions.UnableToAccessApi: Unable to access Pywhatkit api right now Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Temp\tempCodeRunnerFile.python", line 2, in <module> pywhatkit.text_to_handwriting(""" File "C:\Users\HP\AppData\Roaming\Python\Python311\site-packages\pywhatkit\handwriting.py", line 22, in text_to_handwriting raise exceptions.UnableToAccessApi("Unable to access Pywhatkit api right now") pywhatkit.core.exceptions.UnableToAccessApi: Unable to access Pywhatkit api right now A: Someone reported this issue on Github. The maintainers aren't hosting the API on Heroku (or anywhere else) at the moment. They've made their source code for the API function available here though. I've extracted the text_to_handwriting function below: import urllib.request import string import numpy as np from PIL import Image import cv2 char = string.ascii_lowercase file_code_name = {} width = 50 height = 0 newwidth = 0 arr = string.ascii_letters arr = arr + string.digits + "+,.-? " letss = string.ascii_letters def getimg(case, col): global width, height, back try: url = ( "https://raw.githubusercontent.com/Ankit404butfound/HomeworkMachine/master/Image/%s.png" % case ) imglink = urllib.request.urlopen(url) except: url = ( "https://raw.githubusercontent.com/Ankit404butfound/HomeworkMachine/master/Image/%s.PNG" % case ) imglink = urllib.request.urlopen(url) imgNp = np.array(bytearray(imglink.read())) img = cv2.imdecode(imgNp, -1) cv2.imwrite(r"%s.png" % case, img) img = cv2.imread("%s.png" % case) img[np.where((img != [255, 255, 255]).all(axis=2))] = col cv2.imwrite("chr.png", img) cases = Image.open("chr.png") back.paste(cases, (width, height)) newwidth = cases.width width = width + newwidth def text_to_handwriting(string, rgb=[0, 0, 138], save_to: str = "pywhatkit.png"): """Convert the texts passed into handwritten characters""" global arr, width, height, back try: back = Image.open("zback.png") except: url = "https://raw.githubusercontent.com/Ankit404butfound/HomeworkMachine/master/Image/zback.png" imglink = urllib.request.urlopen(url) imgNp = np.array(bytearray(imglink.read())) img = cv2.imdecode(imgNp, -1) cv2.imwrite("zback.png", img) back = Image.open("zback.png") rgb = [rgb[2], rgb[1], rgb[0]] count = -1 lst = string.split() for letter in string: if width + 150 >= back.width or ord(letter) == 10: height = height + 227 width = 50 if letter in arr: if letter == " ": count += 1 letter = "zspace" wrdlen = len(lst[count + 1]) if wrdlen * 110 >= back.width - width: width = 50 height = height + 227 elif letter.isupper(): letter = "c" + letter.lower() elif letter == ",": letter = "coma" elif letter == ".": letter = "fs" elif letter == "?": letter = "que" getimg(letter, rgb) back.save(f"{save_to}") back.close() back = Image.open("zback.png") width = 50 height = 0 return save_to text_to_handwriting("hello, world!", save_to="myimage.png")
{ "language": "en", "url": "https://stackoverflow.com/questions/75472489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Calling a Procedure inside a Function PL/SQL I am trying to figure out how to call the following procedure from a function using Oracle 11g 11.2.0.2.0. Does anyone have some ideas? : -- CREATES or REPLACES insert_into_table_a Procedure. CREATE OR REPLACE PROCEDURE insert_into_table_a -- Declares variable to be inserted into tables. (test_insert_a VARCHAR2) IS -- Begins Procedure. BEGIN -- Creates a savepoint. SAVEPOINT all_or_none; -- Inserts test_insert_a into the CONTACT_ID column of the CONTACT table. INSERT INTO CONTACT (CONTACT_ID) VALUES (test_insert_a); -- Inserts test_insert_a into the ADDRESS_ID column of the ADDRESS table. INSERT INTO ADDRESS (ADDRESS_ID) VALUES (test_insert_a); -- Inserts test_insert_a int the TELEPHONE_ID column of the TELEPHONE table. INSERT INTO TELEPHONE (TELEPHONE_ID) VALUES (test_insert_a); --Commits inserts. COMMIT; -- Creates exception, incase any errors occur, all changes are rolled back. EXCEPTION WHEN OTHERS THEN ROLLBACK TO all_or_none; -- Ends procedure. END; / -- Shows any errors created. SHOW ERRORS A: You can call the procedure from a function just as you'd call any other PL/SQL block CREATE OR REPLACE FUNCTION my_function RETURN integer IS l_parameter VARCHAR2(100) := 'foo'; BEGIN insert_into_table_a( l_parameter ); RETURN 1 END; That being said, it doesn't make sense to call this procedure from a function. Procedures should manipulate data. Functions should return values. If you call a procedure that manipulates data from a function, you can no longer use that function in a SQL statement, which is one of the primary reasons to create a function in the first place. You also make managing security more complicated-- if you use functions and procedures properly, DBAs can give read-only users execute privileges on the functions without worrying that they'll be giving them the ability to manipulate data. The procedure itself seems highly suspicious as well. A column named address_id in the address table should be the primary key and the name implies that it is a number. The same applies for the contact_id column in the contact table and the telephone_id column in the telephone table. The fact that you are inserting a string rather than a number and the fact that you are inserting the same value in the three tables implies that neither of these implications are actually true. That's going to be very confusing for whoever has to work with your system in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/30687269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'python.analysis.typeCheckingMode'. Error: Unable to write to Folder Settings because no resource is provided I get this error when I open vs code. I have everything updated to the latest version. Type checking doesn't work. I re-installed Python and vs code with all extensions, but the Pylance doesn't seem to work. A: Change the following code in your settings.json: "workbench.editorAssociations": { "*.ipynb": "jupyter.notebook.ipynb" },
{ "language": "en", "url": "https://stackoverflow.com/questions/74763341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP generate random phrases from text I am trying to build unique random phrases from text for detecting plagiarism. The idea is author will submit an article and then php will build phrases from text which will be used for plagiarism detection Consider following sentence: This is a very long and boring article and this article is plagiarized. Based upon the above text, system will determine how many phrases will be generated i.e. 20 words long article will have 3 phrases. Max generated phrase can be minimum two words long and maximum 3 words long. The returned output will be like this * *very long *article is plagiarized I wrote following code $words = str_word_count($text, 1); $total_phrases_required = count($words) /2; //build phrases I need hint how to complete rest of the part. A: You could break up text into two arrays of sentences and then use a function like the similar_text function to recursively check for similar strings. Another idea, to find outright pauperism. You could break down text into sentences again. But then put into a database and run a query that selects count of index column and groups by sentence column. If any results comes back greater than 1, you to have an exact match for that sentence.
{ "language": "en", "url": "https://stackoverflow.com/questions/8023988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chart kick Timeline using Ruby on Rails and dynamic data I've installed Chartkick within my ROR app and I'm looking to use the timeline feature to display projects to give a simple and quick overview. <%= @projects.each do |project| timeline [ ['project.hospital', "project.construction_start", "project.construction_end"], ] %> <% end %> I'm trying to get it to display all projects with the construction_start and end format be set at YYYY-MM-DD I have no idea what to do... anything assistance would be appreciated A: Your code is showing something you dont want, the loop instead the timeline, and it's showing , not one timeline but many of them . Change your code to: <% data = @projects.pluck(:hospital,:construction_start,:construction_end) %> <%= timeline data %> This should only create one timeline with all the data about the hospitals of all projects you passed from the controller . Note that this will only work on Rails 4+. If you have Rails 3 you will have to override the pluck method (it's not hard actually)
{ "language": "en", "url": "https://stackoverflow.com/questions/37591123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get weights from tensorflow model Hello I would like to finetune VGG model from tensorflow. I have two questions. How to get the weights from network? The trainable_variables returns empty list for me. I used existing model from here: https://github.com/ry/tensorflow-vgg16 . I find the post about getting weights however this doesn't work for me because of import_graph_def. Get the value of some weights in a model trained by TensorFlow import tensorflow as tf import PIL.Image import numpy as np with open("../vgg16.tfmodel", mode='rb') as f: fileContent = f.read() graph_def = tf.GraphDef() graph_def.ParseFromString(fileContent) images = tf.placeholder("float", [None, 224, 224, 3]) tf.import_graph_def(graph_def, input_map={ "images": images }) print("graph loaded from disk") graph = tf.get_default_graph() cat = np.asarray(PIL.Image.open('../cat224.jpg')) print(cat.shape) init = tf.initialize_all_variables() with tf.Session(graph=graph) as sess: print(tf.trainable_variables() ) sess.run(init) A: This pretrained VGG-16 model encodes all of the model parameters as tf.constant() ops. (See, for example, the calls to tf.constant() here.) As a result, the model parameters would not appear in tf.trainable_variables(), and the model is not mutable without substantial surgery: you would need to replace the constant nodes with tf.Variable objects that start with the same value in order to continue training. In general, when importing a graph for retraining, the tf.train.import_meta_graph() function should be used, as this function loads additional metadata (including the collections of variables). The tf.import_graph_def() function is lower level, and does not populate these collections.
{ "language": "en", "url": "https://stackoverflow.com/questions/36412065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I avoid "line breaking up" with line chart-JasperReport? I am using Jaspersoft Studio version 6.3.0.final with JasperReports Library version 6.3.0 . I'm creating a Line chart with different series and category values. My question is that, when the graph is plotted, I observed that if for one category there are no values for a particular series, the line breaks and the line starts again from the next data point. Is there anyway in which we can connect ALL the points in a particular series, so that it will be one continuous single line instead of broken lines and dots ? I put an image as an example of what I get and I want to do and my .jrxml file for the line chart. line chart example <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="chart_subreport" pageWidth="842" pageHeight="595" columnWidth="842" leftMargin="0" rightMargin="0" topMargin="10" bottomMargin="10"> <style name="table 1_TH" mode="Opaque" backcolor="#646464" forecolor="#FFFFFF" > <box> <pen lineColor="#969696" lineWidth="1.0"/> </box> </style> <field name="TimePoints" class="java.util.Date"/> <field name="LongAxis" class="java.lang.Double"/> <field name="Lesion" class="java.lang.String"/> <detail> <band height="400" > <printWhenExpression><![CDATA[$V{REPORT_COUNT}==1]]></printWhenExpression> <lineChart> <chart> <reportElement style="table 1_TH" x="10" y="0" width="800" height="400"/> <chartTitle> <titleExpression><![CDATA["Lesion's evolution"]]></titleExpression> </chartTitle> </chart> <categoryDataset> <categorySeries> <!-- This is the lesions you want to see on charts--> <seriesExpression><![CDATA[$F{Lesion}]]></seriesExpression> <!--You can change the format date here --> <categoryExpression><![CDATA[(new SimpleDateFormat("MMM d, yyyy")).format($F{TimePoints})]]></categoryExpression> <valueExpression><![CDATA[$F{LongAxis}]]></valueExpression> </categorySeries> </categoryDataset> <linePlot isShowLines="true"> <plot backcolor="#323232" /> <categoryAxisFormat> <axisFormat/> </categoryAxisFormat> <valueAxisFormat> <axisFormat > <labelFont> <font fontName="Arial" size="10"/> </labelFont> </axisFormat> </valueAxisFormat> </linePlot> </lineChart> </band> </detail> </jasperReport> A: I achieved to get what I want, I've just changed the type of the chart, now I'm using "timeSeriesChart". <style name="table 1_TH" mode="Opaque" backcolor="#646464" forecolor="#FFFFFF" > <box> <pen lineColor="#969696" lineWidth="1.0"/> </box> </style> <queryString> <![CDATA[]]> </queryString> <field name="TimePoints" class="java.util.Date"/> <field name="LongAxis" class="java.lang.Double"/> <field name="Lesion" class="java.lang.String"/> <field name ="nbInstance" class="java.lang.Integer"/> <detail> <band height="400" > <printWhenExpression><![CDATA[$V{REPORT_COUNT}==$F{nbInstance}]]></printWhenExpression> <timeSeriesChart> <chart> <reportElement style="table 1_TH" x="10" y="0" width="800" height="400"/> <chartTitle> <titleExpression><![CDATA["Lesion's evolution"]]></titleExpression> </chartTitle> </chart> <timeSeriesDataset> <timeSeries> <seriesExpression><![CDATA[$F{Lesion}]]></seriesExpression> <timePeriodExpression> <![CDATA[$F{TimePoints}]]></timePeriodExpression> <valueExpression><![CDATA[$F{LongAxis}]]></valueExpression> </timeSeries> </timeSeriesDataset> <timeSeriesPlot > <plot backcolor="#323232" /> <timeAxisLabelExpression/> <timeAxisFormat> <axisFormat/> </timeAxisFormat> <valueAxisLabelExpression/> <valueAxisFormat> <axisFormat/> </valueAxisFormat> </timeSeriesPlot> </timeSeriesChart> </band> </detail>
{ "language": "en", "url": "https://stackoverflow.com/questions/47871437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get an index of a two dimensional array? I have a two-dimensional array like this: (0|0),(0|1),(0|2) (1|0),(1|1),(1|2) I know the width and height of the array. I want to calculate the indexes as a single number like this: 0,1,2 3,4,5 How do I do this? A: Looks like index = row * width + column to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/71284710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: 2 sliding menu with different size I use this sliding menu as a library. I want to have 2 menu with different sizes. I have a problem : when i push the big one, another one will move with it I change my main.java like this to have 2 different size menu in lef and right @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Hello"); // set the content view setContentView(R.layout.main); // configure the SlidingMenu final SlidingMenu menu = new SlidingMenu(this); menu.setMode(SlidingMenu.LEFT); menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); DisplayMetrics display = this.getResources().getDisplayMetrics(); int width = display.widthPixels; int menu_width = width - width / 3; if (menu_width < 100) { menu_width = 100; } menu.setBehindWidth(menu_width); menu.setFadeDegree(0.35f); menu.setSlidingEnabled(true); menu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW); menu.setSlidingEnabled(true); View view = G.layoutInflater.inflate(R.layout.menu, null); menu.setMenu(view); final SlidingMenu menu2 = new SlidingMenu(this); menu2.setMode(SlidingMenu.RIGHT); menu2.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); menu2.setBehindWidth(menu_width / 2); menu2.setFadeDegree(0.35f); menu2.setSlidingEnabled(true); menu2.attachToActivity(this, SlidingMenu.SLIDING_WINDOW); menu2.setSlidingEnabled(true); View view22 = G.layoutInflater.inflate(R.layout.menu, null); menu2.setMenu(view22); } A: Why you are using two sligingMenu instead try LEFT_RIGHT Mode for your SlidingMenu This class has method as setMode() LEFT_RIGHT_ACTIVITY A: you can use a code like this: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Hello"); // set the content view setContentView(R.layout.main); // configure the SlidingMenu final SlidingMenu menu = new SlidingMenu(this); menu.setMode(SlidingMenu.LEFT); menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); /// get 1/3 screen width DisplayMetrics display = this.getResources().getDisplayMetrics(); int width = display.widthPixels; int menu_width = width - width / 3; if (menu_width < 100) { menu_width = 100; } menu.setBehindWidth(menu_width); // set the first sliding size menu.setFadeDegree(0.35f); menu.setSlidingEnabled(true); menu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW); menu.setSlidingEnabled(true); View view = G.layoutInflater.inflate(R.layout.menu, null); menu.setMenu(view); final SlidingMenu menu2 = new SlidingMenu(this); menu2.setMode(SlidingMenu.RIGHT); menu2.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); menu2.setBehindWidth(menu_width / 2); // set the second sliding size half of first slidingه menu2.setFadeDegree(0.35f); menu2.setSlidingEnabled(true); menu2.attachToActivity(this, SlidingMenu.SLIDING_WINDOW); menu2.setSlidingEnabled(true); View view22 = G.layoutInflater.inflate(R.layout.menu, null); menu2.setMenu(view22);
{ "language": "en", "url": "https://stackoverflow.com/questions/25384061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: GetObject and VB6 ActiveX exe The VB6 help on GetObject says "You can't use GetObject to obtain a reference to a class created with Visual Basic" (the very last sentence!). My VB6 GUI exposes objects as an ActiveX exe, for other components to manipulate. I want the other components to connect to the GUI that's already running, rather than start a new instance of the exe. I've found using GetObject does work, if you use this syntax: Set myobj = GetObject("", "ProjectName.ClassName") It worries me that the help says this shouldn't work, although I have done quite a bit of testing and haven't found any problems so far. Any COM experts out there who can tell me whether I going to run into problems down the line? And would I be OK with CreateObject anyway? The ActiveX exe settings are: thread pool with only one thread. The class has MultiUse instancing. It's possible these settings are enough to prevent CreateObject starting a new instance of the exe anyway. Is that correct? A: I want the other components to connect to the GUI that's already running, rather than start a new instance of the exe. The trick is to remember that in a ActiveX EXE it can be setup so that there is only one instance of the LIBRARY running. It is correct that you can't reach and just pluck a given instance of a class across process boundary. However the ActiveX EXE can be setup so that the GLOBAL variables are accessible by ANY instance of classes. How to exactly to do this gets a little complex. You can use a ActiveX EXE as a normal EXE the main difference is that you HAVE to use Sub Main. You can also check to see if it run standalone or not. Now I am assuming this is the case with MarkJ's application. If this is the case what you need to is create a application class and set it up so that that when it is created (by using Class_Initialize) that it is populated with the current running instances of forms and collections. I strongly recommend that you create an ActiveX DLL (not EXE) that has nothing but classes to implemented as interfaces. Instead going of going 'Class ThisGUIApp Public MainForm as Form You create an interface that has all the properties and methods needed to access the elements of the mainform. Then you go 'Class ThisGUIApp Public MainForm as IMainForm Private Sub Class_Initialize Set MainForm = frmMyMainForm End Sub 'Form frmMyMainForm Implements IMainForm You do this because while you can send a Form across application process things get wonky when you try to access it members and controls. If you assigned via an interface then the connection is a lot more solid. Plus it better documents the type of things you are trying to do. A: The documentation is confusing, but correct. The MSDN page you reference helps to explain why your GetObject call doesn't throw an error: If pathname [the first argument] is a zero-length string (""), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs. It's subtle, but the implication is that GetObject "", "ProjectName.ClassName is actually equivalent to CreateObject "ProjectName.ClassName" That is to say, passing an empty string to the first parameter of GetObject makes it operate exactly like CreateObject, which means it will create a new instance of the class, rather than returning a reference to an already-running instance. Going back to the MSDN excerpt, it mentions that omitting the first argument to GetObject altogether will cause GetObject to return a reference to an already-running instance, if one exists. Such a call would look like this: GetObject , "ProjectName.ClassName" 'Note nothing at all is passed for the first argument' However, if you try to do this, you will immediately get a run-time error. This is the use-case that the documentation is referring to when it says that GetObject doesn't work with classes created with VB6. The reason this doesn't work is due to how GetObject performs its magic. When the first parameter is omitted, it tries to return an existing object instance by consulting the Running Object Table (ROT), a machine-wide lookup table that contains running COM objects. The problem is that objects have to be explicitly registered in the Running Object Table by the process that creates them in order to be accessible to other processes - the VB6 runtime doesn't register ActiveX EXE classes in the ROT, so GetObject has no way to retrieve a reference to an already-running instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/914628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: UIImageView with gestures recognizers Xcode Ios I have a UIImageView with gestures recognizers (scale, rotate, translate). But after using it, the gestures don't work. And my UIImageview changes the size and position. How to fix this issue? A: By default, UIImageViews do not have user interaction enabled. Try setting your UIImageView's user interaction enabled to "YES": [myImageView setUserInteractionEnabled:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/13316372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Descending not working in query, but it should work? I am making a scoreboard for my internship, for the games we play in the break. I have a really big query to get the results of all games and count the total of wins by players. SELECT winner, SUM(total) AS total FROM (SELECT pw.name AS `winner`, COUNT(*) AS total FROM billiard_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN billiard_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner WHERE winner IS NOT NULL GROUP BY winner UNION ALL SELECT pw.name AS `winner`, COUNT(*) AS total FROM dart_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN dart_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner GROUP BY winner UNION ALL SELECT pw.name AS `winner`, COUNT(*) AS total FROM fifa_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN fifa_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner WHERE winner IS NOT NULL GROUP BY winner ) A WHERE winner IS NOT NULL group by winner DESC LIMIT 5 Output: Player_1 | 5 Player_2 | 1 Player_3 | 3 That's not the right order. Is there something wrong? A: Last part should be WHERE winner IS NOT NULL group by winner order by total DESC LIMIT 5 Because you just missed the ORDER BY
{ "language": "en", "url": "https://stackoverflow.com/questions/55101431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a tree template in SQL I am working with a database used to store information about entities in the form of a tree of components. For example, it might have a camry object with children air-conditioner and engine. The engine might have pistons as children, and air-con have vents as children. The idea is that the user would custom-create something like this as a 'template' which would then be used to instantiate the camry 'tree' as needed. So the user might first create the template, and then use it to add ten of those camry trees to a workshop, storing unique data against each by selecting 'add new car', selecting camry, and then picking a name. How would you store such a construction in a database, and is there any easy way to instantiate a tree like that? A: I've done the first half of this before, so we'll start there (convenient, no?). Without knowing to much about your needs I'd recommend the following as a base (you can adjust the column widths as needed): CREATE TABLE tree ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, parent_id INT UNSIGNED NOT NULL DEFAULT 0, type VARCHAR(20) NOT NULL, name VARCHAR(32) NOT NULL, PRIMARY KEY (id), UNIQUE KEY (parent_id, type, name), KEY (parent_id) ); Why did I do it this way? Well, let's go through each field. id is a globally unique value that we can use to identify this element and all the elements that directly depend on it. parent_id lets us go back up through the tree until we reach parent_id == 0, which is the top of the tree. type would be your "car" or "vent" descriptions. name would let you qualify type, so things like "Camry" and "Driver Left" (for "vent" obviously). The data would be stored with values like these: INSERT INTO tree (parent_id, type, name) VALUES (0, 'car', 'Camry'), (1, 'hvac', 'HVAC'), (2, 'vent', 'Driver Front Footwell'), (2, 'vent', 'Passenger Front Footwell'), (2, 'vent', 'Driver Rear Footwell'), (2, 'vent', 'Passenger Rear Footwell'), (1, 'glass', 'Glass'), (7, 'window', 'Windshield'), (7, 'window', 'Rear Window'), (7, 'window', 'Driver Front Window'), (7, 'window', 'Passenger Front Window'), (7, 'window', 'Driver Rear Window'), (7, 'window', 'Passenger Rear Window'), (1, 'mirrors', 'Mirrors'), (14, 'mirror', 'Rearview Mirror'), (14, 'mirror', 'Driver Mirror'), (14, 'mirror', 'Passenger Mirror'); I could keep going, but I think you get the idea. Just to be sure though... All those values would result in a tree that looked like this: (1, 0, 'car', 'Camry') | (2, 1, 'hvac', 'HVAC') | +- (3, 2, 'vent', 'Driver Front Footwell') | +- (4, 2, 'vent', 'Passenger Front Footwell') | +- (5, 2, 'vent', 'Driver Rear Footwell') | +- (6, 2, 'vent', 'Passenger Rear Footwell') +- (7, 1, 'glass', 'Glass') | +- (8, 7, 'window', 'Windshield') | +- (9, 7, 'window', 'Rear Window') | +- (10, 7, 'window', 'Driver Front Window') | +- (11, 7, 'window', 'Passenger Front Window') | +- (12, 7, 'window', 'Driver Rear Window') | +- (13, 7, 'window', 'Passenger Rear Window') +- (14, 1, 'mirrors', 'Mirrors') +- (15, 14, 'mirror', 'Rearview Mirror') +- (16, 14, 'mirror', 'Driver Mirror') +- (17, 14, 'mirror', 'Passenger Mirror') Now then, the hard part: copying the tree. Because of the parent_id references we can't do something like an INSERT INTO ... SELECT; we're reduced to having to use a recursive function. I know, we're entering The Dirty place. I'm going to pseudo-code this since you didn't note which language you're working with. FUNCTION copyTreeByID (INTEGER id, INTEGER max_depth = 10, INTEGER parent_id = 0) row = MYSQL_QUERY_ROW ("SELECT * FROM tree WHERE id=?", id) IF NOT row THEN RETURN NULL END IF IF ! MYSQL_QUERY ("INSERT INTO trees (parent_id, type, name) VALUES (?, ?, ?)", parent_id, row["type"], row["name"]) THEN RETURN NULL END IF parent_id = MYSQL_LAST_INSERT_ID () IF max_depth LESSTHAN 0 THEN RETURN END IF rows = MYSQL_QUERY_ROWS ("SELECT id FROM trees WHERE parent_id=?", id) FOR rows AS row copyTreeByID (row["id"], max_depth - 1, parent_id) END FOR RETURN parent_id END FUNCTION FUNCTION copyTreeByTypeName (STRING type, STRING name) row = MYSQL_QUERY_ROW ("SELECT id FROM tree WHERE parent_id=0 AND type=? AND name=?", type, name) IF NOT ARRAY_LENGTH (row) THEN RETURN END IF RETURN copyTreeByID (row["id"]) END FUNCTION copyTreeByTypeName looks up the tree ID for the matching type and name and passes it to copyTreeByID. This is mostly a utility function to help you copy stuff by type/name. copyTreeByID is the real beast. Fear it because it is recursive and evil. Why is it recursive? Because your trees are not predictable and can be any depth. But it's okay, we've got a variable to track depth and limit it (max_depth). So let's walk through it. Start by grabbing all the data for the element. If we didn't get any data, just return. Re-insert the data with the element's type and name, and the passed parent_id. If the query fails, return. Set the parent_id to the last insert ID so we can pass it along later. Check for max_depth being less than zero, which indicates we've reached max depth; if we have return. Grab all the elements from the tree that have a parent of id. Then for each of those elements recurse into copyTreeByID passing the element's id, max_depth minus 1, and the new parent_id. At the end return parent_id so you can access the new copy of the elements. Make sense? (I read it back and it made sense, not that that means anything).
{ "language": "en", "url": "https://stackoverflow.com/questions/29761813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return function in another function, please? May someone help me with the following code, please. I try to return a function result in another function: alert("Your email is: " /*+ email of the user*/); Spiritueux Wines and Liquors <script> function check_user_age() { if (age_of_user() < 18) alert("You are too young to buy alcohol."); } function age_of_user() { var age = prompt("What is your age?"); return age; } function check_user_mail() { if (email_of_user().includes("@")) alert("Your email is: " /*+ email*/); else alert("Your email should include an '@' symbol"); } function email_of_user() { var email = prompt("What is your email?") return email; } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/60816182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joomla: Display part of menu I'm trying to make a small left menu in my Joomla articles. Since I use the SP Pagebuilder to display the articles, the module on my page isn't also displayed on my article. With the advanced module manager I was able to put a module in my articles, but there's one problem: I can't display my menu. Say you have this kind of menu: *Home *Item *Item 1 *Item 1.1 *Item 1.2 *Item 1.3 *Item 2 *Item 2.1 *Item 2.2 On the articles I've put in Item 1.1, 1.2 and 1.3, I want to display a menu with these parts: *1.1 *1.2 *1.3 On 2.1 and 2.2 it's: *2.1 *2.2 Still, my articles are technically in the "home" part of my menu. The url should be something like: www.mysite.be/component/content/article/item/item1-1/article1 If you then place a menu module with these options: Menu: Menu1 Basic Item: Item1 Start: 3 Stop: 3 It doesn't wanna display it, since my articles aren't in the "basic item" (being item1), but in the "home". Is there any way make a menu that uses this? I want it because if I add an item (say "item 1.4"), then I don't have to add another link. Please help... Thank you in advance. I hope you understand what I mean XD A: I don't know if i got your question right, but normally, if you set up an new menu-module you can set the Menu you want to use and the Base-Item (Home) where all the Sub Items are placed. So if you want to only display the Sub-Items of home you normally should then set start-level to "1" (Since your base item is already "Home" and you want to display down all items from home... so if you choose "3" it would start displaying menus that are the third sublevel of "home") and end-level to "all" (or the maximal depth you choose), assign the right position for the Module and give it a go.
{ "language": "en", "url": "https://stackoverflow.com/questions/39142300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PayPal Payment not working any more - Laravel Paypal I recently added PayPal payment to my site (using Laravel in general). Therefore I'm using this plugin. The complete code I'm using is: public function getCheckout(Request $request) { $userInfo = \App\User::where('id', '=', \Auth::user()->id) ->first(); if ($userInfo->street == "") { $request->session()->flash('alert-info', 'Vor der ersten Bestellung mΓΌssen Sie erst Ihre Daten vervollstΓ€ndigen'); return redirect('/editData'); } $cart = Cart::where('user_id', \Auth::user()->id)->first(); $items = $cart->cartItems; $total = 0; foreach ($items as $item) { $total += $item->product->price; } $itemList = PayPal::itemList(); foreach ($items as $item) { $product = Product::where('id', '=', $item->product->id)->first(); $itemName = $product->name; $itemPrice = $product->price; $payPalItem = PayPal::item(); $payPalItem->setName($itemName) ->setDescription($itemName) ->setCurrency('EUR') ->setQuantity(1) ->setPrice($itemPrice); $itemList->addItem($payPalItem); } $payer = PayPal::Payer(); $payer->setPaymentMethod('paypal'); $details = PayPal::details(); $details->setShipping("2.50") ->setSubtotal($total); $amount = PayPal:: Amount(); $amount->setCurrency('EUR'); $amount->setTotal(($total + 2.5)); $amount->setDetails($details); $transaction = PayPal::Transaction(); $transaction->setAmount($amount); $transaction->setItemList($itemList); $transaction->setDescription('Ihr Warenkorb'); $redirectUrls = PayPal:: RedirectUrls(); $redirectUrls->setReturnUrl(action('PayPalController@getDone')); $redirectUrls->setCancelUrl(action('PayPalController@getCancel')); $payment = PayPal::Payment(); $payment->setIntent('sale'); $payment->setPayer($payer); $payment->setRedirectUrls($redirectUrls); $payment->setTransactions(array($transaction)); try { $response = $payment->create($this->_apiContext); } catch (PayPalConnectionException $ex) { echo $ex->getCode(); // Prints the Error Code echo $ex->getData(); // Prints the detailed error message die($ex); } $redirectUrl = $response->links[1]->href; return Redirect::to($redirectUrl); } public function getDone(Request $request) { $cart = Cart::where('user_id', \Auth::user()->id)->first(); $items = $cart->cartItems; $total = 0; foreach ($items as $item) { $total += $item->product->price; } $order = new Order(); $order->total_paid = $total + 2.5; $order->user_id = \Auth::user()->id; $order->save(); foreach ($items as $item) { $orderItem = new OrderItem(); $orderItem->order_id = $order->id; $orderItem->product_id = $item->product->id; $orderItem->save(); $product = $item->product; if ($product->stockCount != "") { $product->stockCount--; } $product->save(); CartItem::destroy($item->id); } $id = $request->get('paymentId'); $token = $request->get('token'); $payer_id = $request->get('PayerID'); $payment = PayPal::getById($id, $this->_apiContext); $paymentExecution = PayPal::PaymentExecution(); $paymentExecution->setPayerId($payer_id); try { $payment->create($this->_apiContext); } catch (PayPalConnectionException $ex) { echo $ex->getCode(); // Prints the Error Code echo $ex->getData(); // Prints the detailed error message die($ex); } try { $payment->execute($paymentExecution, $this->_apiContext); } catch (PayPalConnectionException $ex) { echo $ex->getCode(); echo $ex->getData(); die($ex); } // Clear the shopping cart, write to database, send notifications, etc. // Thank the user for the purchase $userInfo = \App\User::where('id', '=', \Auth::user()->id) ->first(); $userMail = $userInfo->email; $orderItems = OrderItem::where('order_id', '=', $order->id)->get(); Mail::to($userMail)->send(new orderFinished($order)); $sellerArray = []; foreach ($orderItems as $orderItem) { $product = $orderItem->product; $seller = User::where('id', '=', $product->user_id)->first(); $buyer = User::where('id', '=', $order->user_id)->first(); if (!in_array($seller, $sellerArray)) { Mail::to($seller->email)->send(new newOrderMail($order, $seller, $buyer)); array_push($sellerArray, $seller); } } return view('checkout.done'); } It worked before and I'm quite sure I didn't change anything but suddenly it doesn't work anymore... I'm getting this error: 400{"name":"MALFORMED_REQUEST","message":"Incoming JSON request does not map to API request","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"5c8663496f505"}PayPal\Exception\PayPalConnectionException: Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment Does anybody see a problem why this could happen? I really have no idea.... Edit: After reverting to the latest revision (where I was sure it worked), I get another error, saying: PayPalConnectionException in PayPalHttpConnection.php line 174: Got Http response code 500 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAY-1DS60820MW1392725LAYAB6A/execute. in PayPalHttpConnection.php line 174 at PayPalHttpConnection->execute('{"payer_id":"J922HVAQ2RHAW"}') in PayPalRestCall.php line 74 at PayPalRestCall->execute(array('PayPal\Handler\RestHandler'), '/v1/payments/payment/PAY-1DS60820MW1392725LAYAB6A/execute', 'POST', '{"payer_id":"J922HVAQ2RHAW"}', array()) in PayPalResourceModel.php line 102 at PayPalResourceModel::executeCall('/v1/payments/payment/PAY-1DS60820MW1392725LAYAB6A/execute', 'POST', '{"payer_id":"J922HVAQ2RHAW"}', null, object(ApiContext), object(PayPalRestCall)) in Payment.php line 650 at Payment->execute(object(PaymentExecution), object(ApiContext)) in PayPalController.php line 142 at PayPalController->getDone(object(Request)) at call_user_func_array(array(object(PayPalController), 'getDone'), array(object(Request))) in Controller.php line 55 at Controller->callAction('getDone', array(object(Request))) in ControllerDispatcher.php line 44 at ControllerDispatcher->dispatch(object(Route), object(PayPalController), 'getDone') in Route.php line 189 But: This doesn't happen everytime, some orders work and some not, or to say with other words: Sometimes it works, sometimes not...What I'm wondering about is not only, why an error occurs, but also why the behaviour changed, because as I said, the only thing I did is revert the file to latest revision (using GIT). And the only things that changed from my local version to the latest revision are some formatting things (space before ( and so on) as well as a stockCount, that's simply a counter for products, also I added some try catch around the execution (as you can see in the code) A: Hi dear sorry for the details . I think the total amount sent to paypal is not calculated correctly . when you set the subtotal within details can you confirm that the subtotal set there is calculated using this formula subtotal = sum((item1 price * quantity) + ... (item2 price * Quantity)) then check the total set to amount is calculated using this formula total = subtotal + shipping Just make sure that the amount sent to paypal is correctly calculated
{ "language": "en", "url": "https://stackoverflow.com/questions/40684154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ efficient way to store and update sorted items I have a operation that continuously generates random solutions (std::vector<float>). I evaluate the solutions against a mathematical function to see their usefulness (float). I would like to store the top 10 solutions all the time. What would be the most efficient way to do this in C++? I need to store both the solutions(std::vector) and their usefulness (float). I am performing several hundred thousands of evaluations and hence I am in need of an efficient solution. Edit: I am aware of sorting methods. I am looking for methods other than sorting and storing the values. Looking for better data structures if any. A: * *You evaluate the float score() function for current std::vector<T> solution, store them in a std::pair<vector<T>, float>. *You use a std::priority_queue< pair<vector<T>, float> > to store the 10 best solutions based on their score, and the score itself. std::priority_queue is a heap, so it allows you to extract its max value according to a compare function that you can set up to compare score_a < score_b. *Store the first 10 pairs, then for each new one compare it with the top of the heap, if score(new) > score(10th) then insert(new) into the priority_queue p, and p.pop_back() to get rid of the old 10th element. *You keep doing this inside a loop until you run out of vector<T> solutions. A: Have a vector of pair, where pair has 1 element as solution and other element as usefulness. Then write custom comparator to compare elements in the vector. Add element at last, then sort this vector and remove last element. As @user4581301 mentioned in comments, for 10 elements, you dont need to sort. Just traverse vector everytime, or you can also perform ordered insert in vector. Here are some links to help you: https://www.geeksforgeeks.org/sorting-vector-of-pairs-in-c-set-1-sort-by-first-and-second/ Comparator for vector<pair<int,int>>
{ "language": "en", "url": "https://stackoverflow.com/questions/63552767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Kibana user forbidden error {"statusCode":403,"error":"Forbidden","message":"Forbidden"} I just setup my xpack in elasticsearch 7.1.0 as below in elasticsearch.yml: xpack.security.enabled: true discovery.type: single-node in my elasticsearch.yml Then, i ran >elasticsearch-setup-passwords interactive and changed all my built-in user passwords. this is the change i made in Kibana.yml xpack.security.enabled: true elasticsearch.username: "kibana" elasticsearch.password: "password@123" When i restarted Kibana, i ws prompted with a username password page, where i gave kibana/password@123 that i had set in my yml. Im getting the below response: {"statusCode":403,"error":"Forbidden","message":"Forbidden"} Please help me out. A: Resolution: using "elastic" user account instead of kibana fixed this issue. A: Configuring security in Kibana To use Kibana with X-Pack security: Update the following settings in the kibana.yml configuration file: elasticsearch.username: "kibana" elasticsearch.password: "kibanapassword" Set the xpack.security.encryptionKey property in the kibana.yml configuration file. xpack.security.encryptionKey: "something_at_least_32_characters" Optional: Change the default session duration. xpack.security.sessionTimeout: 600000 Restart Kibana. Please follow this link using-kibana-with-security
{ "language": "en", "url": "https://stackoverflow.com/questions/58026128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CakePHP - a code sample seems strange to me, what am i missing? Attached code taken from cakephp bakery, where someone uploaded a sample about custom validation rules. class Contact extends AppModel { var $name = 'Contact'; var $validate = array( 'email' => array( 'identicalFieldValues' => array( 'rule' => array('identicalFieldValues', 'confirm_email' ), 'message' => 'Please re-enter your password twice so that the values match' ) ) ); function identicalFieldValues( $field=array(), $compare_field=null ) { foreach( $field as $key => $value ){ $v1 = $value; $v2 = $this->data[$this->name][ $compare_field ]; if($v1 !== $v2) { return FALSE; } else { continue; } } return TRUE; } } In the code, the guy used a foreach to access an array member which he had its name already! As far as I understand - it's a waste of resources and a bad(even strange) practice. One more thing about the code: I don't understand the usage of the continue there. it's a single field array, isn't it? the comparison should happen once and the loop will be over. Please enlighten me. A: In the code, the guy used a foreach to access an array member which he had its name already! As far as I understand - it's a waste of resources and a bad(even strange) practice. The first parameter is always an array on one key and its value, the second parameter comes from the call to that function, in a block named as the key... So, all you need is to send the key and no need to iterate The code uses foreach to iterate through $field, which is an array of one key value pair. It all starts when the validation routine invokes identicalFieldValues, passing it two values - $field, which would be an array that looks like: array ( [email] => 'user entered value 1' ) The second parameter $compare_field would be set to the string confirm_email. In this particular case, it doesn't look like it makes a lot of sense to use foreach since your array only has one key-value pair. But you must write code this way because CakePHP will pass an array to the method. I believe the reason why CakePHP does this is because an array is the only way to pass both the field name and its value. While in this case the field name (email) is irrelevant, you might need in other cases. What you are seeing here is one of the caveats of using frameworks. Most of the time, they simplify your code. But sometimes you have to write code that you wouldn't write normally just so the framework is happy. One more thing about the code: I don't understand the usage of the continue there. it's a single field array, isn't it? the comparison should happen once and the loop will be over. Please enlighten me. Indeed. And since there are no statements in the foreach loop following continue, the whole else block could also be omitted. A simplified version of this would be: function identicalFieldValues($field=array(), $compare_field=null) { foreach ($field as $field) { $compare = $this->data[$this->name][$compare_field]; if ($field !== $compare) { return FALSE; } } return TRUE; } And I agree with you, the loop only goes through one iteration when validating the email field. regardless of the field. You still need the foreach because you are getting an array though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7265005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete from a Map with JPQL I have these entities: @Entity public class ActiveQuest { @OneToMany(orphanRemoval=true,cascade=CascadeType.ALL,mappedBy="activeQuest") @MapKey(name="task") private Map<String, ActiveTask> activeTasks = Maps.createHash(); } @Entity public class ActiveTask implements Serializable { @ManyToOne(optional=false) private ActiveQuest activeQuest; } To delete an ActiveTask from an ActiveQuest I currently do: final ActiveQuest aq = em.find(....); aq.getActiveTasks().remove(task); Can I do the same faster (no fetching) with a single JPQL query? A: Yes. The JPQL specification even has some examples DELETE FROM Publisher pub WHERE pub.revenue > 1000000.0 A: Just realised that I don't need to consider the Map at all if I just view it from the side of the task, not the quest. DELETE FROM ActiveTask t WHERE t.activeQuest = :quest AND t.task = :taskname
{ "language": "en", "url": "https://stackoverflow.com/questions/13378801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make different lower and upper in mysql select I want to search for a name on database. But I just want select Bill , not biLL or BiLL or ... just "Bill". But when I use this query which shows Bill , BiLL, BILL, bilL and ... query=`select * from names where name='Bill'` A: To quote the documentation: The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation You can overcome this by explicitly using a case sensitive collation: select * from names where name='Bill' COLLATE latin1_general_cs A: There is also another solution to set the collection of the column to utf8mb4_unicode_520 or any case sensitive standard collections.
{ "language": "en", "url": "https://stackoverflow.com/questions/26692398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I handle this response from YQL In a request to YQL (select * from html where url="...") I got the following response: callback({ "query": {"count":"1","created":"2011-05-09T23:29:05Z","lang":"en-US" }, "results": ["<body>... we\ufffdll call Mr ...</body>"] } This is from the YQL console page. When I type that sequence into firebug (even on YQL's page) I get: ... weοΏ½ll call Mr ... What am I doing wrong? Is YQL's site in a bad encoding? Is there some way to convert symbols like this to their ascii equivalent? BTW this isn't my site so it's not like I can change the meta charset on that site A: * *It seems like that (the question mark in a solid black diamond) is what you should be seeing: http://www.fileformat.info/info/unicode/char/fffd/browsertest.htm *The comment on that character's page says: used to replace an incoming character whose value is unknown or unrepresentable in Unicode Maybe the answers to these might help get a better answer: * *What character are you expecting at that place? *Can you post the URL that you're scraping? *Is that the character on that page also or is it getting mangled when picked up by YQL? Update You might want to check out the charset option in the where clause of your YQL query - I'm not entirely sure what it does but it looks like it forces the YQL engine to use the specified charset when parsing the page. Perhaps setting it to UTF-8 will solve your problem. For example, select * from html where url = 'http://google.com' and charset='utf-8'
{ "language": "en", "url": "https://stackoverflow.com/questions/5957363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring controller is not being called I am new in spring application. I am trying to create small spring application but I am getting 404 error message. Seems like controller (indexController) is not begin called. I tired to debug but its not going there. Files location: /WebContent/WEB-INF/pages/index.html /WebContent/WEB-INF/HelloWeb-servlet.xml /WebContent/WEB-INF/web.xml HelloWeb-servlet.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.requestengine.controller" /> IndexController.java package com.requestengine.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") public String index(){ return "index"; } } web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name></display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.html</url-pattern> <url-pattern>*.htm</url-pattern> <url-pattern>*.jason</url-pattern> <url-pattern>*.xml</url-pattern> A: HTTP 404 means the URL is not found: https://en.wikipedia.org/wiki/HTTP_404 It usually tells me that my packaging or mapping or request URL is incorrect. Start with the basics: write an index.html page and see that it's displayed. It's not typical to have an index controller. Once you have that page working, see if you can map to something meaningful. Is that controller in a package? I don't see a package statement at the top. It's impossible to be a Spring developer without being a solid Java developer first. No one would create a class without a package. A: I modified your code a bit to make it work. web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name></display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> </web-app> IndexController.java package com.requestengine.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") @ResponseBody public String index(){ return "index"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/38945362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone: How to retrieve the same photo from media library between application instances How do I retrieve the same photo from the media library between application instances? I launch the photo library for the user to select a photo via: PhotoChooserTask myPhotoChooser = new PhotoChooserTask(); myPhotoChooser.ShowCamera = true; myPhotoChooser.Show(); myPhotoChooser.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed); and then in the Event handler, I retrieve the file name of the selected file like this: private void cameraCaptureTask_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { string imagePath = e.OriginalFileName.ToString(); } } I persist this information in isolated storage so that when a user launches the application again I can retrieve the path and display the image like this: private BitmapImage ConvertUriToBitmap(string pathToImage) { StreamResourceInfo streamResInfo = null; Uri uri = new Uri(pathToImage, UriKind.Relative); streamResInfo = Application.GetResourceStream(uri); //This fails! StreamResInfo is null BitmapImage convertedBitmap = new BitmapImage(); convertedBitmap.SetSource(streamResInfo.Stream); return convertedBitmap; } However, this doesn't seem to work as the photo path from the photo chooser is some sort of guid in the form: "\Applications\Data\02E58193-119F-42E2-AD85-C24247BE2AB0\Data\PlatformData\PhotoChooser-4edd185d-d934-4dac-8a34-758cac09d338.jpg" Application.GetResourceStream(uri) is null whenenever I switch out of the application or move between pages. Is there a better way to do this? How do I retrieve the same path everytime so that when I tombstone or kill the app, i can retireve the file and display it? Or is there a different /more efficient way of doing it. A: I found the answer in the documentation: http://msdn.microsoft.com/en-us/library/gg680264%28v=pandp.11%29.aspx Basically, there is a bug in the photo chooser which returns a temporary path. Microsofts recommendation is to copy the picture to isolated storage if you want to use it between app instances. A: Application.GetResourceStream will return null for that path because the GetResourceStream method is looking for a resource within the application itself, not from the device. To re-load the same image on resume from tombstoning simply persist the OriginalFileName property, and then use that to create a BitmapImage as follows: string path = /* Load the saved OriginalFileName */; var bitmap = new BitmapImage(new Uri(path, UriKind.Absolute)); myImageControl.Source = bitmap; NOTE: The OriginalFileName property is already a string, so you don't need to call .ToString() on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/5740552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When to store pointers to structs in variables instead of the struct itself I'm currently learning Go and am following a tutorial about how to use Go with Stripe. There is this example code: package main import ( "fmt" "github.com/stripe/stripe-go" "github.com/stripe-go/customer" ) func main() { sc := &client.API{} sc.Init("somekey") c, _ := sc.Customers.Get("customerid", nil) // ... } What is/could be the reason that sc stores the pointer to the struct and not the struct itself? A: [To supplement the comment you received] While in this case with the small code sample it's hard to say, in most scenarios you'll see non-trivial types passed around by pointer to enable modification. As an anti-example, consider this code which uses a variable of a struct type by value: type S struct { ID int } func (s S) UpdateID(i int) { s.ID = i } func main() { s := S{} s.UpdateID(99) fmt.Println(s.ID) } What do you think this will print? It will print 0, because methods with value receivers cannot modify the underlying type. There's much information about this in Go - read about pointers, and about how methods should be written. This is a good reference: https://golang.org/doc/faq#methods_on_values_or_pointers, and also https://golang.org/doc/effective_go#pointers_vs_values Back to your example: typically non-trivial types such as those representing a "client" for some services will be using pointers because method calls on such types should be able to modify the types themselves.
{ "language": "en", "url": "https://stackoverflow.com/questions/67193289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select columns that have name beginning with same prefix? Using PostgreSQL 8.1.11, is there a way to select a set of columns that have name beginning with same prefix. Suppose we have columns : PREFIX_col1, PREFIX_col2, ... Is it possible to do a request like : SELECT 'PREFIX_*' FROM mytable; Which of course doesn't work. A: information_schema.COLUMNS contains all the columns in your DB so you can query for a specific pattern in the name like this: select c.COLUMN_NAME from information_schema.COLUMNS as c where c.TABLE_NAME = 'mytable' and c.COLUMN_NAME like 'PREFIX_%'; A: You are going to have to construct the query with a query and use EXECUTE. Its a little easier w/ 8.3+. Here's a query that will run on 8.1 and pulls all columns starting with r% from the film table $$ DECLARE qry TEXT; BEGIN SELECT 'SELECT ' || substr(cols, 2, length(cols) - 2) || ' FROM film' INTO qry FROM ( SELECT array( SELECT quote_ident(column_name::text) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'film' AND column_name LIKE 'r%' ORDER BY ordinal_position )::text cols -- CAST text so we can just strip off {}s and have column list ) sub; EXECUTE qry; END; $$ A: To me it looks like the syntax description of PostgreSQL 8.x's SELECT statement does not allow this. A SELECT list must be an expression or list of expressions, and the syntax for expressions does not seem to allow for wildcarded partial column names. Share and enjoy.
{ "language": "en", "url": "https://stackoverflow.com/questions/3941156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: logger.debug ["This is", "an", "Array"] Rails Why is my output of logger.debug ["This is", "an", "Array"] This isanArray and not something like ["This is", "an", "Array"] Is there a way to do this? (I know I could do to_yaml, but that is too verbose for me) What are some options for a nice clean output of an array, similar to print_r in php? A: Try this: logger.debug ["This is", "an", "Array"].inspect This also works for all other kinds of objects: Hashes, Classes and so on. A: you could try the .inspect method.... logger.debug array.inspect I agree with Andrew that there is nothing wrong with... puts YAML::dump(object) A: When you do that, to_s is automatically called on the array, and that's how to outputs. Calling to_yaml is by no means verbose. You could also look at using join or inspect.
{ "language": "en", "url": "https://stackoverflow.com/questions/5196240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: D3.js on("drag") called even when I just click a node I've been working with the example on directed graphs here - http://bl.ocks.org/cjrd/6863459. Here, there is a on drag function in the JS code (graph-creator.js)- .on("drag", function(args){ thisGraph.state.justDragged = true; thisGraph.dragmove.call(thisGraph, args); }) Most of the time, this works as expected. But sometimes, the browser seems to get stuck in a state where the function is called even if I simply click the node. Since this seems to be a native event, I don't know how to tweak this to make sure it doesn't happen. Does any one have a suggestion on why this is happening and what I can do to make this function robust?
{ "language": "en", "url": "https://stackoverflow.com/questions/34714679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using a temporary table to query and update existing table I am still new to using SQL and this query has got me particularly stuck. I am importing a .CSV file into a temporary table (it is only 1 column wide and it imports fine with the exception of the first row which is for some reason blank) for the purpose of updating a table in the existing database upon matching the imported column. The problem I am having is that it is only matching the last entry in the imported table and doing the update to only 1 record in the existing table. The .CSV file is generated from a spread which in turn was generated from a query of the existing DB so I know the names are correct and they are in the temporary table. I have seen several similar querying problems/solutions and tried to use parts of their solutions to no avail and am hoping that this community can help me out!! if object_id('dbo.namefile', 'u') is not null drop table dbo.namefile create table dbo.namefile ( name varchar(255) not null primary key --constraint pk_t1_name check(name not like 'zzzzzzz') ) bulk insert dbo.namefile from 'f:\list.csv' with (datafiletype = 'char', fieldterminator = '","', rowterminator = '\r', errorfile = 'f:\inp_err.log') update dbo.MeasurementLimit set LowLimit = 1 from namefile as nf join EntityName as en on en.EntityName = nf.name join MeasurementLimit as ml on en.uid = ml.UID where en.EntityName = nf.name Thanks for any help I tried this, this morning select * from namefile It returned 113 records the correct number of entries in the list.csv file This however only returned 1 record select * from namefile nf inner join Entityname as en on en.Entityname = nf.listname Entityname table Measurementlist A: My guess is that the problem is that you are not using an alias for the update. How about this version: update ml set LowLimit = 1 from namefile as nf join EntityName as en on en.EntityName = nf.name join MeasurementLimit as ml on en.uid = ml.UID where en.EntityName = nf.name; A: The solution was in the bulk insert.. The original code (above) would read in a single column csv file but it also added a blank record to the table which screwed up any query you would run against it the corrected insert code is bulk insert namefile from 'f:\list.csv' ( datafiletype = 'char', fieldterminator = ',', <========= This was wrong rowterminator = '\n',<====== and this was wrong errorfile = 'f:\inp_err.log' );
{ "language": "en", "url": "https://stackoverflow.com/questions/37796196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: download tool files from web browser of my Liberty server I would like to use my running server as a repository of files that my users can download from a link. is this possible with liberty? Is there a configuration that will allow me to do this ? thanks Stefania C:\Program Files\IBM\WebSphere\Liberty\usr\servers\myServerApp>dir Volume in drive C has no label. Volume Serial Number is 7B77-7220 Directory of C:\Program Files\IBM\WebSphere\Liberty\usr\servers\myServerApp 01/12/2018 10:26 AM . 01/12/2018 10:26 AM .. 01/12/2018 11:01 AM apps 01/15/2018 12:04 PM dropins 01/15/2018 12:05 PM logs 01/12/2018 10:26 AM resources 01/12/2018 10:26 AM 25 server.env 01/12/2018 10:26 AM 2,300 server.xml 01/15/2018 12:04 PM temp 01/15/2018 12:04 PM workarea 2 File(s) 2,325 bytes 8 Dir(s) 68,651,966,464 bytes free A: You can put any downloadable files you like in a hello-world .war file and they'll be downloadable over HTTP. It's silly to use an application server without an application. A: Liberty is not intended to be used as a generic file server. That said, there are MBean operations supporting file transfer capabilities via the Liberty REST Connector. Javadoc for these operations may be found at <liberty-install-root>/dev/api/ibm/javadoc/com.ibm.websphere.appserver.api.restConnector_1.3-javadoc.zip
{ "language": "en", "url": "https://stackoverflow.com/questions/48270096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: what is the IDE for using SPECMAN I have been searching for what IDE to use in order to start studying SPECAMAN. I would like to know what is the IDE for e/specman and where I can download it ? Also if there is a good tutoriaal for it. Thanks in advance. A: This is a plugin for eclipse which costs money. http://www.dvteclipse.com/ I've never tried it. Most people at my work use VIM or emacs to edit e-files. I use JEdit. Here's a crash-course on Specman.
{ "language": "en", "url": "https://stackoverflow.com/questions/16669768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display text/banner if AdView cant loaded I try to display a banner / text if the AdView fails to load (because of AdBlock or anything else). I tried different methods: * *Two RelativeLayouts above (both were hidden from AdBlock ...) *Set a text view in the RelativeLayout which contain my AdView to visible if App Fails to load. *and different layout tricks nothing works. Can anyone help me? A: You can implement the AdListener interface to listen for AdMob events. public interface AdListener { public void onReceiveAd(Ad ad); public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error); public void onPresentScreen(Ad ad); public void onDismissScreen(Ad ad); public void onLeaveApplication(Ad ad); } Then you will want your AdView to listen to the AdListener. // Assuming AdView is named adView and this class implemented AdListener. adView.setAdListener(this); In particular, you will be interested in the the onFailedToReceiveAd callback. This called if AdMob failed to load an ad. If you implement this method, you can take appropriate action in your application when an ad is not returned.
{ "language": "en", "url": "https://stackoverflow.com/questions/9084260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSLT 2 character only generate-id I'd like to use generate-id in my xslt stylesheet. However, this function generates a 8 character long id. Is there a way to make the id have only two characters ? Of course this makes a limited number of possible id (1296 possibilities), but I will never need to go beyond that limit. Thanks A: If you only need the ID to be unique for nodes within a single document, you could use <xsl:number count="*" level="any" from="/*" format="a"/> A: You'd have much more than 1296 possibilities with 2 characters if you wanted to use all the unicode characters that are allowed in an XML name! Unfortunately, XSLT processors are free to decide how that create IDs for the generate-id() function (meaning that depending on the processor you are using you can get more or less then 8 characters). That being said, if that's really important to you, you should be able to write your own generate-id() based on the number of preceding siblings and ancestor node nodes (count(ancestor::node()|preceding::node()))... You could convert this number into a two character id using lookup tables or any other mechanism and that would probably not be very efficient but that should work...
{ "language": "en", "url": "https://stackoverflow.com/questions/10937246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: App Pool Timeout Destroys ASP.NET code behind properties I am maintaining some data in form of a dictionary as an ASP.NET code behind property. When the App Pool timeout is reached, dictionary with data is destroyed (surprisingly other string properties are not). I am using PageMethods (works like AJAX) to load part of the data from my dictionary as per the request by Javascript. I need to detect when the App Pool has timed out in my code behind, so that I could probably refresh the page. Dictionary is being stored in an object wrapper as: public partial class SourceWorkqueue : System.Web.UI.Page { internal static ObjectType _dbList;
{ "language": "en", "url": "https://stackoverflow.com/questions/45065361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring Controller / leading/trailing whitespaces in URL I've a very simple Spring MVC application, for example: @Controller @RequestMapping("/rest") public class MyController { @RequestMapping(value = "/endpointA"} public @ResponseBody ResponseObject endpointA() { return something; } } The endpoint method should be mapped to the URL: "/rest/endpointA", but it is invoked also for "/%20rest/endpointA", "/rest /endpointA" and any form of leading and/or trailing whitespaces. Why is it, and is there a way to enforce an exact match of the URL to "/rest/endpointA", in terms of "/%20rest/endpointA" would result in a 404 Not Found response by Tomcat. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/39169769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }