text
stringlengths
15
59.8k
meta
dict
Q: Grouping rows with Groupby and converting date & time of rows of start date-time and end date- time columns I have a dataset looking like this: Blast Hole East Coordinate North Coordinate Collar Theoritical Depth Tag Detector ID Date and Time Detection_Location Detection Date & Time 64 16745.42 107390.32 2634.45 15.95 385656531 23-08-2018 2:39:34 PM CV23 2018-09-08 14:18:17 61 16773.48 107382.6 2634.68 16.18 385760755 23-08-2018 2:38:32 PM CV23 2018-09-08 14:24:19 63 16755.07 107387.68 2634.58 16.08 385262370 23-08-2018 2:39:30 PM CV23 2018-09-08 14:12:42 105 16764.83 107347.67 2634.74 16.24 385742468 23-08-2018 2:41:29 PM CV22 2018-09-06 20:02:46 100 16752.74 107360.32 2634.33 15.83 385112050 23-08-2018 2:41:08 PM CV22 2018-09-06 20:15:42 99 16743.1 107362.96 2634.36 15.86 385087366 23-08-2018 2:41:05 PM CV22 2018-09-06 20:49:21 35 16747.75 107417.68 2635.9 17.4 385453358 23-08-2018 2:36:09 PM CV22 2018-09-23 05:47:44 5 16757.27 107452.4 2636 17.5 385662254 23-08-2018 2:35:03 PM CV22 2018-09-23 05:01:12 19 16770.89 107420.83 2634.81 16.31 385826979 23-08-2018 2:35:50 PM CV22 2018-09-23 05:52:54 I intended to group all the rows having 3 detections at one place ( in column Detection_location) in one hour. I used the following code for grouping the rows falling in one hour per 3 detection: df2 = df1.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'), df1.Detection_Location]).size().reset_index(name = 'Tags') This code gave me a result like this: I would rather like to have result in which each rows have start time when the first detection was there in that hour and when the last detection was seen and thus i would like to have a result like this: This is the required output: Detection Date & Time - Start Detection Date & Time - End Detection_Location Tags 2018-09-06 20:02:46 2018-09-06 20:49:21 CV22 3 2018-09-08 14:12:42 2018-09-08 14:24:19 CV23 3 2018-09-23 05:01:12 2018-09-23 05:47:44 CV22 3 Can anyone suggest what else should i add in my group-by function to get this result. Thanks A: Check if this works for you. Inside the aggregate function, you can pass all the values that you want to capture. df2 = (df.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),df.Detection_Location],sort=False)['Detection Date & Time'] .agg(['first','last','size'])).reset_index().rename(columns={"first": "Detection Date & Time - Start", "last": "Detection Date & Time - End", "size": "Tags"})
{ "language": "en", "url": "https://stackoverflow.com/questions/57549303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linking to iOS simulator binaries on OSX I was curious what would happen if I linked to an iOS simulator framework in a Mac app. So I copied UIKit to it's own folder (so the Framework search path wouldn't include all the iOS simulator framework, as like CoreFoundation is both on Mac and iOS but has different headers), and dragged it into the link section in Xcode. The error Xcode gave me was: building for MacOSX, but linking against dylib built for iOS Simulator file '/Users/jonathan/Desktop/macuikit/UIKit.framework/UIKit' for architecture x86_64 Both architectures are x86_64, so how can it tell the framework is specifically for the iOS simulator, I removed all references to iOS in things like Info.plist, even tried deleted everything but the UIKit binary, but the same error came up. Is there something in the binary it self that tells the linker which platform it can run on, rather than just the architecture? I looked at the Mach-O header but there is only fields for CPU type and subtype, and neither has a value for the simulator as expected. A: After a little bit of digging, it turns out that the platform on which the library can run on is indeed specified in the binary. In fact, you can edit the binary in your favorite Hex editor and make the linker skip this check entirely. This information is not specified in the Mach-O header (as you have already realized). Instead, it is specified as a load command type. You can see the available types by digging through the LLVM sources. Specifically, the enum values LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS look interesting. Now, find the offset for this in our binary. Open the same in MachOView (or any other editor/viewer or your choice) and note the offset: Once the offset is noted, jump to the same in a Hex editor and update it. I modified LC_VERSION_MIN_IPHONEOS (25) to LC_VERSION_MIN_MACOSX (24) Save the updates and try linking again. The error should go away. Of course, you will hit other issues when you try to actually run your example. Have fun with LLDB then :)
{ "language": "en", "url": "https://stackoverflow.com/questions/28946926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Find all the combinations that return a particular value from a function This is a variation on finding all the combinations that add to a target, with two constraints: * *We have a limited set of numbers to work with. *The numbers must result in the target number when fed into a separate function. In this case, the limited set of numbers include 25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400, etc. And the function is to add the values together and then multiply by a number based on how many numbers we had: * *If 1 number, multiply by 1. *If 2 numbers, multiply by 1.5 *If 3-6 numbers, multiply by 2 *If 7-10 numbers, multiply by 2.5 *If >10 numbers, multiply by 3 Examples: [50, 50, 50] => 300 [100, 100] => 300 Target numbers include 300, 600, 900, 1500, 3000, 3600, 4400, 5600, 6400, 7600, 9600, etc. My intuition is that this can't be done recursively, because each step doesn't know the multiplier that will eventually be applied. A: Here's a recursive example in JavaScript that seems to answer the requirements: function getNextM(m, n){ if (n == 1) return 1.5; if (n == 2) return 2; if (n == 6) return 2.5; if (n == 10) return 3; return m; } function g(A, t, i, sum, m, comb){ if (sum * m == t) return [comb]; if (sum * m > t || i == A.length) return []; let n = comb.length; let result = g(A, t, i + 1, sum, m, comb); const max = Math.ceil((t - sum) / A[i]); let _comb = comb; for (let j=1; j<=max; j++){ _comb = _comb.slice().concat(A[i]); sum = sum + A[i]; m = getNextM(m, n); n = n + 1; result = result.concat(g( A, t, i + 1, sum, m, _comb)); } return result; } function f(A, t){ return g(A, t, 0, 0, 1, []); } var A = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400]; var t = 300; console.log(JSON.stringify(f(A, t))); A: I wrote a small script in Python3 that may solve this problem. multiply_factor = [0,1,1.5,2,2,2,2,2.5,2.5,2.5,2.5,3] def get_multiply_factor(x): if x< len(multiply_factor): return multiply_factor[x] else: return multiply_factor[-1] numbers = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400] count_of_numbers = len(numbers) # dp[Count_of_Numbers] dp = [[] for j in range(count_of_numbers+1)] #Stores multiplying_factor * sum of numbers for each unique Count, See further sum_found =[set() for j in range(count_of_numbers+1)] # Stores Results in Unordered_Map for answering Queries master_record={} #Initializing Memoization Array for num in numbers: dp[1].append(([num],num*get_multiply_factor(1))) for count in range(2,count_of_numbers+1): # Count of Numbers for num in numbers: for previous_val in dp[count-1]: old_factor = get_multiply_factor(count-1) #Old Factor for Count Of Numbers = count-1 new_factor = get_multiply_factor(count) #New Factor for Count Of Numbers = count # Multiplying Factor does not change if old_factor==new_factor: # Scale Current Number and add new_sum = num*new_factor+previous_val[1] else: #Otherwise, We rescale the entire sum new_sum = (num+previous_val[1]//old_factor)*new_factor # Check if NEW SUM has already been found for this Count of Numbers if new_sum not in sum_found[count]: # Add to current Count Array dp[count].append(([num]+previous_val[0],new_sum)) # Mark New Sum as Found for Count Of Numbers = count sum_found[count].add(new_sum) if new_sum not in master_record: # Store Seected Numbers in Master Record for Answering Queries master_record[new_sum] = dp[count][-1][0] # for i in dp: # print(i) print(master_record[1300]) print(master_record[300]) print(master_record[2300]) print(master_record[7950]) print(master_record[350700.0]) Output :- [100, 100, 450] [100, 100] [25, 25, 1100] [25, 50, 3900] [1800, 5900, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400] [Finished in 0.3s] My Algo in a nutshell. Iterate over Count[2, Limit], I've considered limit = Number of Elements Iterate over List of Numbers Iterate over Sums found for previous count. Calculate New Sum, If it does not exist for current count, update. I am assuming that the number of queries will be large so that memorization pays off. The upper limit for count may break my code as the possibilities may grow exponentially.
{ "language": "en", "url": "https://stackoverflow.com/questions/61434281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple widget changes based on one button event in Kivy I'm trying to build this application which contains multiple buttons. I can bind each button event to a callback but I am not able to change the state (namely the label) of any other button except for the one that fired the event. Does anyone know how to do this? A: All you need is a reference to the other button, then you can do other_button.text = 'whatever'. The way to do this depends on how you've constructed the program. For instance, if you constructed in the program in kv language, you can give your buttons ids with id: some_id and refer to them in the callback with stuff like on_press: some_id.do_something(). In pure python, you could keep references to the button in the parent class when you create them (e.g. self.button = Button()) so that the callback can reference self.button to change it. Obviously that's a trivial example, but the general idea lets you accomplish anything you want. A: Probably not the official way, but try out the following code. It will change the text property of the buttons... Ezs.kv file: #:kivy 1.8.0 <Ezs>: BoxLayout: orientation: 'vertical' padding: 0 spacing: 6 #choose Button: id: btn_1 text: 'text before' on_press: btn_2.text = 'Whatever' on_release: self.text = 'Who-Hoo' #choose Button: id: btn_2 text: 'Press this' on_release: self.text = 'HEEYY' on_press: btn_1.text = 'text after' .py file: class Ezs(BoxLayout): class EzsApp(App): def build(self): return Ezs if __name__ == '__main__': EzsApp().run()
{ "language": "en", "url": "https://stackoverflow.com/questions/20650593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ CLI error C3767: candidate function(s) not accessible I'm new to C++ CLI coming from unmanaged C++ world. I'm getting this error: candidate function(s) not accessible when I pass a std::string as part of the method argument. Here's the exact code: Lib Project (compiled as .dll project) //Lib.h #pragma once public ref class Lib { public: Lib(void); public: void Extract( std::string& data_ ); }; //Lib.cpp #include "Lib.h" Lib::Lib(void) { } void Lib::Extract( std::string& data_ ) { data_.empty(); } LibTest Project (compiled as application.exe) // LibTest.h #pragma once ref class LibTest { public: LibTest(void); }; // LibTest.cpp #include "LibTest.h" LibTest::LibTest(void) { Lib^ lib = gcnew Lib; lib->Extract( std::string("test") ); } int main() { return 0; } Compiler Error: 1>------ Build started: Project: LibTest, Configuration: Debug Win32 ------ 1>Compiling... 1>LibTest.cpp 1>.\LibTest.cpp(7) : error C3767: 'Lib::Extract': candidate function(s) not accessible A: if you simply must access the internal methods another work around would be making the projects as Friend Assemblies like that: //Lib Project #pragma once //define LibTest as friend assembly which will allow access to internal members using namespace System; using namespace System::Runtime::CompilerServices; [assembly:InternalsVisibleTo("LibTest")]; public ref class Lib { public: Lib(void); public: void Extract( std::string& data_ ); }; //LibTest Project #pragma once #using <Lib.dll> as_friend ref class LibTest { public: LibTest(void); }; A: The problem is that std::string will compile as a internal (non public) type. This is actually a change in VS 2005+: http://msdn.microsoft.com/en-us/library/ms177253(VS.80).aspx: Native types are private by default outside the assembly Native types now will not be visible outside the assembly by default. For more information on type visibility outside the assembly, see Type Visibility. This change was primarily driven by the needs of developers using other, case-insensitive languages, when referencing metadata authored in Visual C++. You can confirm this using Ildasm or reflector, you will see that your extract method is compiled as: public unsafe void Extract(basic_string<char,std::char_traits<char>,std::allocator<char> >* modopt(IsImplicitlyDereferenced) data_) with basic_string being compiled as: [StructLayout(LayoutKind.Sequential, Size=0x20), NativeCppClass, MiscellaneousBits(0x40), DebugInfoInPDB, UnsafeValueType] internal struct basic_string<char,std::char_traits<char>,std::allocator<char> > Note the internal. Unfortunately you are then unable to call a such a method from a different assembly. There is a workaround available in some cases: You can force the native type to be compiled as public using the make_public pragma. e.g. if you have a method Extract2 such as: void Extract2( std::exception& data_ ); you can force std::exception to be compiled as public by including this pragma statement beforehand: #pragma make_public(std::exception) this method is now callable across assemblies. Unfortunately make_public does not work for templated types (std::string just being a typedef for basic_string<>) I don't think there is anything you can do to make it work. I recommend using the managed type System::String^ instead in all your public API. This also ensures that your library is easily callable from other CLR languages such as c# A: In addition to the solutions described above, one can subclass the templated type to obtain a non-templated type, and include its definition in both projects, thus overcoming some of the problems mentioned above.
{ "language": "en", "url": "https://stackoverflow.com/questions/947213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: using sass with compass - 404 css not found I'm using the followig config for compass with grunt: compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: 'app/components', relativeAssets: false }, dist: {}, server: { options: { debugInfo: true } } }, and I see that the sass is getting compiled since it shows in the .tmp/styles folder but for some reason when I call the css files from the <%= yeoman.app %>/styles filder it's not found
{ "language": "en", "url": "https://stackoverflow.com/questions/19614469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript - change r attribute of circle wrapped in #shadow-root My html tree looks as follows: <svg id="floating-button-svg" style={{fill: `${floatingButton.backgroundColor}`}}> <use id="use-tag" href=" <svg> <circle id="semi-circle" class="cls-1" cx="500" cy="500" r="50"/> </svg>" /> </svg> Afer compilation the href dissolves to data:image/svg+xml;base64,PCEtLSA8P3htbCB2ZXJzaW9uPSIxLjAiIGVuY29kaW5nPSJ1dGYtOCI/Pgo8c3ZnIHZlcnNpb249IjEuMCIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CjxjaXJjbGUgaWQ9InNlbWktY2lyY2xlIiBjeD0iNTAwIiBjeT0iNTAwIiByPSI1MDAiLz4KPC9zdmc+IC0tPgoKCjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTAwMCIgaGVpZ2h0PSI1MDAiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCI+CiAgPGRlZnM+CiAgICA8c3R5bGU+CiAgICAgIC5jbHMtMSB7CiAgICAgICAgZmlsbDogIzAwMDsKICAgICAgfQogICAgPC9zdHlsZT4KICA8L2RlZnM+CiAgPGNpcmNsZSBpZD0ic2VtaS1jaXJjbGUiIGNsYXNzPSJjbHMtMSIgY3g9IjUwMCIgY3k9IjUwMCIgcj0iNTAiLz4KPC9zdmc+Cgo=#semi-circle If anyone wants to test it, please replace the value in the href above with this link. I am trying to change the radius of the circle through document.getElementById('use-tag').setAttribute('r', '25') but instead it only gives use an attribute of r=25. Is there any way I can change the radius of the circle? I have tried to fetch it using getElementById but it just gives me null (I'm assuming because it's wrapped in a shadow root). edit: The gist of the problem here I believe is that I am trying to change the attributes of a closed shadow root which is impossible to achieve. So can someone please tell me why am I get a closed root instead of an open one? And how can I get an open one? edit: Here is a demo of this situation: https://codesandbox.io/embed/smoosh-sun-nnevd?fontsize=14&hidenavigation=1&theme=dark A: Since you have direct access to circle with id semi-circle, you can update it as the below snippet. The snippet is running under a setTimeout to show the difference. setTimeout(function() { var circle = document.getElementById('semi-circle'); circle.setAttribute('r', 60) }, 3000) <svg id="floating-button-svg" height="100" width="100"> <circle id="semi-circle" class="cls-1" cx="50" cy="50" r="40" fill="red" /> </svg> You can also do it in another way, check the snippet setTimeout(function() { var circle = document.getElementById('floating-button-svg'); circle.firstElementChild.setAttribute('r', 60) }, 1500) <svg id="floating-button-svg" height="400" width="400"> <circle id="semi-circle" class="cls-1" cx="80" cy="80" r="40" fill="red" /> </svg>
{ "language": "en", "url": "https://stackoverflow.com/questions/60392155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to replace this componentWillReceiveProps? I have a login and register component with forms that were created a while ago before these methods were deprecated, I've been looking around but cannot seem to find a solution, how would I go about refactoring this to using getDerivedStateFromProps? componentWillReceiveProps(nextProps) { if (nextProps.auth.isAuthenticated) { this.props.history.push("/dashboard") } if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } A: Since you're using componentWillReceiveProps to keep a local state in sync with props you have two alternatives: Declare your initial state based on props and use componentDidUpdate to ensure props synchronicity class Component extends React.Component{ state = { foo : this.props.foo } componentDidUpdate(prevProps){ if(this.props.foo !== prevProps.foo) this.setState({ foo : prevProps.foo }) } } This is actually triggering an extra render everytime, if you have some local state that is always equal to some prop you can use the prop directly instead. Use getDerivedStateFromProps to update the state based on a prop change, but keep in mind that you probably don't need to use it class Component extends React.Component{ static getDerivedStateFromProps(props){ return { foo : props.foo } } } A: The answer to the question you asked is probably not going to be satisfactory. :-) The answer is that if you really need to derive state from props (you probably don't, just use props.errors directly in render), you do it with the newer getDerivedStateFromProps static method that accepts props and state and (potentially) returns a state update to apply: static getDerivedStateFromProps(props, state) { return props.errors ? {errors: props.errors} : null; } or with destructuring and without the unused state parameter: static getDerivedStateFromProps(({errors})) { return errors ? {errors} : null; } But, you're saying "But that doesn't do the authentication thing...?" That's right, it doesn't, because that componentWillReceiveProps shouldn't have, either, it violates the rule props are read-only. So that part shouldn't be there. Instead, if that entry in props.history is supposed to be there, it should be put there by the parent component.
{ "language": "en", "url": "https://stackoverflow.com/questions/59143054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Axios import breaks rest of javascript file I'm using encore and yarn to set up my javascript and css in a symfony project. I want to use axios so I use: yarn add axios then I add this code to app.js import '../css/app.scss'; import axios from "axios"; console.log('test'); axios({ url: 'https://dog.ceo/api/breeds/list/all', method: 'get', data: { foo: 'bar' } }); Then yarn watch picks up the modifications and compiles it to this: (window["webpackJsonp"] = window["webpackJsonp"] || []).push([["app"],{ /***/ "./assets/css/app.scss": /*!*****************************!*\ !*** ./assets/css/app.scss ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "./assets/js/app.js": /*!**************************!*\ !*** ./assets/js/app.js ***! \**************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../css/app.scss */ "./assets/css/app.scss"); /* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_app_scss__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js"); /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__); console.log('test'); axios__WEBPACK_IMPORTED_MODULE_1___default()({ url: 'https://dog.ceo/api/breeds/list/all', method: 'get', data: { foo: 'bar' } }); /***/ }) },[["./assets/js/app.js","runtime","vendors~app~normalization"]]]); When I remove the import of Axios the console.log('test') runs but when I add the import it won't. So the import breaks the other code. Could someone explain how I import axios without trouble?
{ "language": "en", "url": "https://stackoverflow.com/questions/59863878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Css counter for list I am trying to use the counter increment in css on my ordered list but its not working This is what I want to display: 1. Acknowledgements 1.1 blah, blah .... 1.2 blah, blah .... 1.3 blah, blah .... 2. Risk Statement 2.1 blah, blah .... 2.2 blah, blah .... 2.3 blah, blah .... 3. License 3.1 blah, blah .... 3.2 blah, blah .... 3.3 blah, blah .... But this s what is happening... http://jsfiddle.net/XQKcy/ A: Demo Fiddle You were very close: body { counter-reset: listCounter; } ol { counter-increment: listCounter; counter-reset: itemCounter; list-style:none; } li{ counter-increment: itemCounter; } li:before { content: counter(listCounter) "." counter(itemCounter); left:10px; position:absolute; }
{ "language": "en", "url": "https://stackoverflow.com/questions/23267039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Global var vs Shared Instance swift What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift. A: A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this: var bar = Bar() You would then be able to access the instance from anywhere, like this: bar bar.foo() A shared instance, or singleton, looks like this: class Bar { static var shared = Bar() private init() {} func foo() {} } Then you can access the shared instance, still from anywhere in the module, like this: Bar.shared Bar.shared.foo() However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables: var bar2 = Bar() var bar3 = Bar() However, using a singleton (shared instance), the initialiser is private, so trying to do this... var baaar = Bar() ...results in this: 'Bar' initializer is inaccessible due to 'private' protection level That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced. If you want more information about this, there's a great article by KrakenDev here. A: Singleton (sharing instance) Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app. The dispatch_once function, which executes a block once and only once for the lifetime of an app. Global variable Apple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.
{ "language": "en", "url": "https://stackoverflow.com/questions/44939952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to set layout with XML in View for BaseAdapter getView() method The following Java code (from https://www.intertech.com/Blog/android-adapters-adapterviews/) is from getView(), a method implementation from a Android Adapter class, and it builds a View in Java to populate items on a List. I get how it works, but the same page says it can be built using an XML file, which makes sense to me, but I'm unable to find any examples. I understand how to use XML resource files to set Activity layout using setContentView(). But how would I invoke an XML resource file to build the View in the getView() method? @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { Context context = parent.getContext(); LinearLayout view = new LinearLayout(context); view.setOrientation(LinearLayout.HORIZONTAL); view.addView(new CheckBox(context)); TextView nameTextView = new TextView(context); nameTextView.setText(courses.get(position).getName()); nameTextView.setPadding(0, 0, 10, 0); view.addView(nameTextView); TextView parTextView = new TextView(context); parTextView.setText(Integer.toString(courses.get(position).getPar())); view.addView(parTextView); return view; } return convertView; } A: like this item_test.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="name" /> </LinearLayout> adapter @Override public View getView(int position, View convertView, ViewGroup parent) { Holder holder; // use holder if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false); holder = new Holder(convertView); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.name.setText("name"); return convertView; } public class Holder { private TextView name; public Holder(View view) { name = view.findViewById(R.id.name); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/55692877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: project using moleculer-sentry example I have been trying to use the moleculer-sentry mixing in a moleculer project. But it is not working. Does someone have an example project using this mixing? Also i have been searching answers in internet, but nothing.
{ "language": "en", "url": "https://stackoverflow.com/questions/71413946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Javascript asyc and await working in this particular code? I have implemented an async function which creates an XHR object inside a Promise, requests a data from the server and fulfills the Promise with the response received from the server async function playWordsAudio(id, type, check=false){ let file_namePromise = new Promise(function (onSuccess, onFailure){ var xhttp = new XMLHttpRequest(); xhttp.onload = function(){ if(this.readyState == 4 && this.status == 200){ if(this.responseText !== "No Data"){ file_name = this.responseText; if(check == false){ audio = new Audio('assets/uploads/wav/' + file_name); audio.play(); }else{ onSuccess(file_name); } }else{ if(check){ onSuccess('Not Found'); } } } }; xhttp.open("GET", "scripts/get_word_audio.php?id=" + id + "&type=" + type, true); xhttp.send(); }); let resultant = await file_namePromise; if(check){ return resultant; } } Later I have defined another function which calls the async function shown above function modify_object(id, type, obj){ result = playWordsAudio(id, type, true); result.then(function(value){ if(value == "Not Found"){ obj.classList.remove('fa-play'); } }); } Later in the implementation I also call the modify_object function and pass it an object for modification as described in the function. modify_object(id, type, plays[i]); In the async function I have created a Promise, on success I pass it the file_name received from the XHR response or else I pass it 'Not Found'. Here I am confused on how the await part works inside the asyc function. It returns the resultant to the caller of the async function which is result = playWordsAudio(id, type, true); If so, what does the onSuccess method in the Promise do let file_namePromise = new Promise(function (onSuccess, onFailure){ /* Some Codes */ onSuccess(file_name); /* Some more code */ onSuccess('Not Found); /* Rest of the Code */ } As I have checked by commenting out the return statement after the await statement if(check){ // return resultant; } The Promise is not fulfilled. How does each part of the implementation work as described above?
{ "language": "en", "url": "https://stackoverflow.com/questions/67992979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert ts object to data.frame and keep row- and colnames I want to convert a ts (i.e. timeseries) R object to a data.frame. The names of rows and columns of the ts object should be retained. Consider the AirPassengers data set: data(AirPassengers) I could convert this ts object to a data.frame as follows: AirPassengers <- data.frame(matrix(as.numeric(AirPassengers), ncol = 12, byrow = TRUE)) colnames(AirPassengers) <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") rownames(AirPassengers) <- 1949:1960 However, this seems to be way too complicated. Surprisingly, a google search didn't show a simpler solution. Question: Is there a simple solution how to convert ts objects to a data.frame without losing colnames and rownames? A: The underlying issue is that the output of print for a time series object is quite heavily processed by .preformat.ts. If you want to convert it to a data frame that is visually similar to the print results this should do: df <- data.frame(.preformat.ts(datasets::AirPassengers), stringsAsFactors = FALSE) Note that this will produce characters (as that is how .preformat.ts works), so be careful with the use (not sure what is the purpose of the conversion?).
{ "language": "en", "url": "https://stackoverflow.com/questions/54053314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where does setup.py install console scripts to? When I set up my package using setup.py to have a console script entry point, pip install -e . creates a cli exe in the C:\Users\...\anaconda3\envs\envname\Scripts\foo.exe. However on a separate computer the python executable is the one from the Windows Store: C:\Users\...\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n6khra8p0\python.exe This doesn't set the PATH environment variable correctly to make .exes in the Scripts folder callable from the command line, so I need the full path to the .exe to call it. Anyway I want to find the location of foo.exe on this second computer (which I don't have access to), is there a command I can instruct the second computer to run which will tell me where a console script will be located for that given sys.executable? I.e. for my computer, I expect it to print C:\Users\...\anaconda3\envs\envname\Scripts. FWIW, this is my setup.cfg: [options] py_modules = xml2csv python_requires = >=3.10 [options.entry_points] console_scripts = xml2csv=xml2csv:main
{ "language": "en", "url": "https://stackoverflow.com/questions/72643833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using the button tag, can I customize the button? I want to use a custom button image that I drew up for my application, but doing so I need to use different images for the button being focused and another for it being pressed. I came across the selector tags but for some reason it doesn't like it. Eclipse complains about a 'broken rendering library'. The error I get is this: Broken rendering library; unsupported DPI. Try using the SDK manager to get updated. And I have, I've updated every API past 10. If it matters, my target API is 15 and my compile API is 17. If I can't get this working, can I simply use the Button tag and maybe change it in the Java src code or something? A: use a custom layout like this <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/pressed"></item> <item android:state_focused="true" android:drawable="@drawable/focus"></item> <item android:drawable="@drawable/normal"></item> </selector> Also note that the the selector should be defined in this particular way else they will give problem .i.e. 1)state_pressed 2)state_focused ( work only if you scroll to that button using the hardware key) 3)drawable i.e. normal If you changed the ordering of the selector then it won't work. One easy way to remember it is visualizing a qwerty phone - first i saw the button (normal), then moved to that particular button using arrow keys (state_focused), then i pressed that button (state_pressed). Now write them backwards. A: Instead of button,create ImageView and do necessary things on click of the image. <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="Method_Name" android:src="@drawable/selector" > </ImageView> Also inorder to give different images on click and focus,create selector.xml in drawable folder and set background of imageview as selector file. selector.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/image1" android:state_focussed="true" /> <!-- Inactive tab --> <item android:drawable="@drawable/image2" android:state_pressed="true" /> <!-- Pressed tab --> </selector> Hope this will help you!
{ "language": "en", "url": "https://stackoverflow.com/questions/16826011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to show button when adding fragment? Bottom button(234) is not showing after adding fragment. I don't want to resize my fragment size. Home_Fragment.xml This is the main Fragment page. It also have profile Fragment. From Profile Fragment we are calling next fragment that is hiding bottom button (TV_Chat button name) <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> <!-- View pager to swipe views --> <Button android:id="@+id/button3" android:layout_width="125dp" android:layout_height="59dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="0dp" android:background="@color/white" android:text="" /> <com.medyc.us.customViews.CustomViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/tabLayout" android:background="@color/light_background" /> <Button android:id="@+id/tv_chat" android:layout_width="60dp" android:layout_height="60dp" android:background="@drawable/circle_blue_gradient" android:text="234" android:gravity="center" android:textSize="@dimen/twenty_sp" android:textColor="@color/white" android:textStyle="bold" android:visibility="visible" android:fontFamily="@font/helvetica" android:layout_centerHorizontal="true" android:layout_alignBottom="@+id/tabLayout" android:layout_marginBottom="@dimen/thirty_dp" /> <!-- our tablayout to display tabs --> <android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" app:tabIndicatorHeight="0dp" /> <View android:id="@+id/bottomview" android:layout_width="match_parent" android:layout_height="43dp" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" android:layout_marginBottom="50dp" /> </RelativeLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/50348828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET/GridView: Using only a subset of the data fields in the table I have a list of objects called Activity and I want to display the date, type and notes for each and every one of these activities. This is the code I'm using. <asp:GridView ID="gvTable" runat="server" AllowSorting="true" ShowHeader="true"> <Columns> <asp:BoundField DataField="ActivityDate" HeaderText="Date" HeaderStyle-CssClass="date" /> <asp:BoundField DataField="ActivityType" HeaderText="Type" /> <asp:BoundField DataField="ActivityNotes" HeaderText="Notes" /> </Columns> <PagerSettings Position="Bottom" Mode="NextPrevious" PageButtonCount="5" PreviousPageText="Older activities" NextPageText="Newer activities" /> </asp:GridView> However, all of the attributes of each object is displayed in the header. How can I force it to display only the columns that I want to use? A: gvTable.AutoGenerateColumns = false or <asp:GridView ID="gvTable" runat="server" AutoGenerateColumns="False" AllowSorting="true" ShowHeader="true"> should do the trick. A: Set the attribute on your gridview: AutoGenerateColumns="false" A: You need to set the AutoGenerateColumns property on the grid to false. A: Have you tried AutoGenerateColumns="false" in the gridview?
{ "language": "en", "url": "https://stackoverflow.com/questions/1922927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS Build Error: missing file Icon102.png I have a Xamarin Forms App running on Android and iOS. Everything works fine on a Simulator and on lokal devices. When I push the Buid to AppCenter, the Android Version gets build without a problem, but the iOS Build alsways fails with the following error: (_CoreCompileImageAssets target) -> /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png : error : File not found: /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png [/Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/O365Info.iOS.csproj] 24 Warning(s) 1 Error(s) Time Elapsed 00:01:01.73 [error]Xamarin.iOS task failed with error Error: /Library/Frameworks/Mono.framework/Versions/6_6_1/bin/msbuild failed with return code: 1. For guidance on setting up the build definition, see https://go.microsoft.com/fwlink/?LinkId=760847. [section]Finishing: Build Xamarin.iOS solution. In the first builds I didn't even had a Iconset called AppIcon.appiconset (my Iconset was named appiconset1) and the whole project didn't include a file named "Icon1024.png". I then renamed my Iconset to appioconset and included a file named "Icon1024.png", but I'm still getting the same error. No ideas, where this error might come from. Any suggestions? A: Copied From ColeX at: https://forums.xamarin.com/discussion/179775/build-error-with-missing-file-icon1024-png * *Edit csproj file to remove the bogus entries (just delete them) *Ensure that a 1024*21024 png icon (file does not have Alpha or transparent) add into Assets.xcassets *Ensure the 1024 file information included in csproj file Refer Where to find 'Missing Marketing Icon' https://forums.xamarin.com/discussion/129252/problems-with-missing-appicons-files
{ "language": "en", "url": "https://stackoverflow.com/questions/60660242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What really happens internally when an update happens on a record with indexed column in sql server I know that when a table has indexed column(s), sql server duplicates the data of these columns so that it can be accessed fast without looking through every record. And if the index is covered with other columns then all these included columns are also stored along with the indexed columns. So, I am assuming when an update happens on any of the indexed columns or included columns then it is obvious that the update should happen in both the actual record location and the index location. This point looks interesting to me because if a table is expected to have more updates than searches, then wouldn't it be overhead to have the index? I wanted to confirm on this and also would like to know the internals on what actually happens behind the screen when a update happens. A: Yes, you have it correct. There is a trade-off when adding indexes. They have the potential to make selects faster, but they will make updates/inserts/deletes slower. A: When you design an index, consider the following database guidelines: * *Large numbers of indexes on a table affect the performance of INSERT, UPDATE, DELETE, and MERGE statements because all indexes must be adjusted appropriately as data in the table changes. For example, if a column is used in several indexes and you execute an UPDATE statement that modifies that column's data, each index that contains that column must be updated as well as the column in the underlying base table (heap or clustered index). *Avoid over-indexing heavily updated tables and keep indexes narrow, that is, with as few columns as possible. *Use many indexes to improve query performance on tables with low update requirements, but large volumes of data. Large numbers of indexes can help the performance of queries that do not modify data, such as SELECT statements, because the query optimizer has more indexes to choose from to determine the fastest access method. *Indexing small tables may not be optimal because it can take the query optimizer longer to traverse the index searching for data than to perform a simple table scan. Therefore, indexes on small tables might never be used, but must still be maintained as data in the table changes. For more information have a look at the below link:- http://technet.microsoft.com/en-us/library/jj835095(v=sql.110).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/23999689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I clear an array in the state of my Redux store? I am building a small e-commerce shop and I am trying to clear my cart after a successful checkout. The cart contains cartItems which are stored in the Redux store. I am getting the console log in my function in the StripeCheckoutForm component and the action creator. I am not seeing the console log for the reducer so I suspect something is wrong with my action creator. I am not sure about best practices concerning action creators. I was wondering when, why, and how to use dispatch in the action creator. The docs for Redux aren't exactly clear for me. Here is my StripeCheckout: import React, {Component} from 'react'; import { CardElement, injectStripe } from 'react-stripe-elements'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { clearCart } from '../actions/clearCartAction'; import getTotal from '../helpers/getTotalHelper'; import { Container, Col, Form, FormGroup, Input } from 'reactstrap'; import './StripeCheckoutForm.css'; const cardElement = { base: { color: '#32325d', width: '50%', lineHeight: '30px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '18px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; const FIREBASE_FUNCTION = 'https://us-central1-velo-velo.cloudfunctions.net/charge/'; // Function used by all three methods to send the charge data to your Firebase function async function charge(token, amount, currency) { const res = await fetch(FIREBASE_FUNCTION, { method: 'POST', body: JSON.stringify({ token, charge: { amount, currency, }, }), }); const data = await res.json(); data.body = JSON.parse(data.body); return data; } class CheckoutForm extends Component { constructor(props) { super(props); this.submit = this.submit.bind(this); } state = { complete: false } clearCartHandler = () => { console.log('clearCartHandler'); this.props.onClearCart() } // User clicked submit async submit(ev) { console.log("clicked!") const {token} = await this.props.stripe.createToken({name: "Name"}); const total = getTotal(this.props.cartItems); const amount = total; // TODO: replace with form data const currency = 'USD'; const response = await charge(token, amount, currency); if (response.statusCode === 200) { this.setState({complete: true}); console.log('200!!',response); this.clearCartHandler(); } else { alert("wrong credit information") console.error("error: ", response); } } render() { if (this.state.complete) { return ( <div> <h1 className="purchase-complete">Purchase Complete</h1> <Link to='/'> <button>Continue Shopping</button> </Link> </div> ); } return ( <div className="checkout-wrapper"> <Container className="App"> <h2 className='text-center'>Let's Checkout</h2> <Form className="form"> <Col> <FormGroup> <Input type="first name" name="first name" id="exampleEmail" placeholder="first name" /> </FormGroup> </Col> <Col> <FormGroup> <Input type="last name" name="last name" id="exampleEmail" placeholder="last name" /> </FormGroup> </Col> <Col> <FormGroup> <Input type="address" name="address" id="exampleEmail" placeholder="address" /> </FormGroup> </Col> <Col> <FormGroup> <Input type="city" name="city" id="exampleEmail" placeholder="city" /> </FormGroup> </Col> <Col> <FormGroup> <Input type="prefecture" name="prefecture" id="exampleEmail" placeholder="prefecture" /> </FormGroup> </Col> <Col> <FormGroup> <Input type="zipcode" name="zipcode" id="exampleEmail" placeholder="zipcode" /> </FormGroup> </Col> <Col> <FormGroup> <Input type="email" name="email" id="exampleEmail" placeholder="myemail@email.com" /> </FormGroup> </Col> <div className="card-element"> <CardElement style={cardElement}/> </div> </Form> <button className="checkout-button" disabled={false} onClick={this.submit}>Submit</button> </Container> </div> ); } } const mapStateToProps = state => { return { cartItems: state.shoppingCart.cartItems } } const mapDispatchToProps = state => { return { onClearCart: () => (clearCart()) } } export default connect(mapStateToProps, mapDispatchToProps)(injectStripe(CheckoutForm)); Here is my action creator: import { CLEAR_CART } from './types'; // export const clearCart = (dispatch) => { // console.log('clear_action') // dispatch({ // type: CLEAR_CART, // }) // } export function clearCart() { console.log('clear_action') return { type: CLEAR_CART } } and finally my reducer: import {ADD_TO_CART} from '../actions/types'; import {REMOVE_FROM_CART} from '../actions/types'; import {CLEAR_CART} from '../actions/types'; const initialState = { cartItems: [], } export default function(state = initialState, action) { switch(action.type) { case ADD_TO_CART: console.log('ADD_reducer'); return { ...state, cartItems: [...state.cartItems, action.payload], } case REMOVE_FROM_CART: console.log('REMOVE_REDUCER', action.payload, state.cartItems); return { ...state, cartItems: state.cartItems.filter(item => item.id !== action.payload.id) } case CLEAR_CART: console.log('CLEAR_REDUCER'); return { ...state, cartItems: [] } default: return state; } } A: Action has to be dispatched like below. Let me know if it works const mapDispatchToProps = (dispatch) => { return { onClearCart: () => (dispatch(clearCart())) } };
{ "language": "en", "url": "https://stackoverflow.com/questions/53989718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Zoomable fullscreen image in portrait and landscape mode I am a beginner at programming. I have an app where you can tap into any of the images that are on display to show that image in full-screen mode and can pinch to zoom. The issue I am having is that if you rotate the phone then the image is only half visible. I'm using a scroll view to achieve the zoom functionality as that seems to be the consensus of the best way to do it. It works perfectly in portrait mode, or if I enter the fullscreen image while the app is already in landscape orientation, but If I go into the landscape while in the fullscreen image that's where it goes wrong. Here is the code: class PictureDetailViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var scrollView: UIScrollView! var routeData = IndividualRoute(numberOfRoute: UserDefaults.standard.integer(forKey: "currentRoute")) var detailPicture = UserDefaults.standard.bool(forKey: "segueFromDetailvc") var detailImage = UIImageView() override func viewDidLoad() { super.viewDidLoad() routeData.routesValues() scrollView.delegate = self selectImage() scrollView.frame = UIScreen.main.bounds scrollView.addSubview(detailImage) scrollViewContents() setupConstraints() let scrollViewFrame = scrollView.frame let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height let minScale = min(scaleHieght, scaleWidth) scrollView.minimumZoomScale = minScale scrollView.maximumZoomScale = 1 scrollView.zoomScale = minScale let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreen)) tap.numberOfTapsRequired = 2 view.addGestureRecognizer(tap) } //**************************************** //Image Setup func setupConstraints() { scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor), scrollView.centerYAnchor.constraint(equalTo: view.centerYAnchor)]) scrollView.contentSize = (detailImage.image?.size)! } func selectImage() { if !detailPicture { let foo = "\(routeData.achievements[UserDefaults.standard.integer(forKey: "currentAchievement")])" detailImage.image = UIImage(named: "\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0") } else { let foo = "\(routeData.achievements[0])" detailImage.image = UIImage(named: "\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0") print("\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0") } guard let width = detailImage.image?.size.width else { return } guard let height = detailImage.image?.size.height else { return } let frame: CGRect = CGRect(x: 0, y: 0, width: width, height: height) detailImage.frame = frame detailImage.isUserInteractionEnabled = true } //************************************** //Scrollview setup @objc func dismissFullscreen(){ scrollView.setZoomScale(1, animated: true) } func scrollViewContents() { let boundSize = UIScreen.main.bounds.size var contentFrame = detailImage.frame if contentFrame.size.width < boundSize.width { contentFrame.origin.x = (boundSize.width - contentFrame.size.width) / 2 } else { contentFrame.origin.x = 0 } if contentFrame.size.height < boundSize.height { contentFrame.origin.y = (boundSize.height - contentFrame.size.height) / 2 } else { contentFrame.origin.y = 0 } detailImage.frame = contentFrame } func scrollViewDidZoom(_ scrollView: UIScrollView) { scrollViewContents() } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return detailImage } Sorry for posting so much code but its pretty much all relevant (I think). Here are screenshots of the problem: A: Okay, I've managed to fix it! Had a little jump around with delight. I set up a new function called setupScale() that is called in viewdidload when the view is presented. I also added the viewwillLayoutSubview() override and called the setupScale() function inside it. If looks like this: private func setupScale() { scrollView.frame = UIScreen.main.bounds scrollView.contentSize = (detailImage.image?.size)! scrollViewContents() let scrollViewFrame = scrollView.frame let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height let minScale = min(scaleHieght, scaleWidth) scrollView.minimumZoomScale = minScale scrollView.maximumZoomScale = 1 scrollView.zoomScale = minScale } override func viewWillLayoutSubviews() { setupScale() } Results look perfect on my iPad and iPhone 7 in landscape and portrait.
{ "language": "en", "url": "https://stackoverflow.com/questions/47354076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EXEC master.sys.sp_MSforeachdb error when looping through databases I am getting the following the error when executing the statement: EXEC master.sys.sp_MSforeachdb 'INSERT INTO AuditDatabase.dbo.[DataDictionary] exec sp_get_extendedproperty use [?] "?"' Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'master'. Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'tempdb'. Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'model'. Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'msdb'. Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'AdventureWorks2014'. Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'TestDatabase'. Msg 102, Level 15, State 1, Line 23 Incorrect syntax near 'AuditDatabase'. If I run it without the use syntax like this: EXEC master.sys.sp_MSforeachdb 'INSERT INTO AuditDatabase.dbo.[DataDictionary] exec sp_get_extendedproperty "?"' It only loops through the AdventureWorks2014 and msdb databases. It does not loop through any other database. sp_get_extendedproperty is on master db. A: The use statement is in the wrong place. Try something like this: I exec sp_MSforeachdb 'use ? rest of statement here ' I just executed this and it worked fine: exec sp_MSforeachdb 'use ? select * from sys.objects;' If your proc is name sp_xxx and is in master it should be available in all databases.
{ "language": "en", "url": "https://stackoverflow.com/questions/29436928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Find prev element source I know this code below doesn't work, but is it possible with a call to get the "src" from the prev, <img>with a little tweak to the jquery below? HTML: <li> <img src="assets/themes/abstract/1_tbn.png" class="theme_tbn" /> <label class="theme_label">Diffuse green</label> <span> <button class="btn-publish chooseTheme">Choose Theme</button> </span> </li> Jquery: $(".chooseTheme").click(function () { var src = $(".chooseTheme").find("img"); alert(src.text()); }); A: $(".chooseTheme").click(function () { var src = $(this).closest('li').find("img").attr('src'); alert(src); }); A: $(".chooseTheme").click(function () { var src = $("li").find("img").attr('src'); alert(src); });
{ "language": "en", "url": "https://stackoverflow.com/questions/16529591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What should be passed as input parameter when using train-test-split function twice in python 3.6 Basically i wanted to split my dataset into training,testing and validation set. I therefore have used train_test_split function twice. I have a dataset of around 10-Million rows. On the first split i have split training and testing dataset into 70-Million training and 30-Million testing. Now to get validation set i am bit confused whether to use splitted testing data or training data as an input parameter of train-test-split in order to get validation set. Give some advise. TIA X = features y = target # dividing X, y into train and test and validation data 70% training dataset with 15% testing and 15% validation set from sklearn.model_selection import train_test_split #features and label splitted into 70-30 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) #furthermore test data is splitted into test and validation set 15-15 x_test, x_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5) A: Don't make a testing set too small. A 20% testing dataset is fine. It would be better, if you splitted you training dataset into training and validation (80%/20% is a fair split). Considering this, you shall change your code in this way: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) x_test, x_val, y_test, y_val = train_test_split(X_train, y_train, test_size=0.25) This is a common practice to split a dataset like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/56099495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initialize a multidimensional array of JButtons declared in a different class using get method I have to create a battleship game where there is a multidimensional array of JButtons to denote the player grid. I am supposed to initialize the JButtons in the main UI class but they need to be declared in a separate class holding the player grid. I have tried this to add the buttons: for(int i = 0; i <= 10; i++){ for(int j = 0; j <= 10; j++){ playerOnePanel.add(playerOne.getBoard()); } } But this returns a null pointer exception. The class I'm trying to reference is: public class Player { private Color shipColor; private String userName; private boolean isFirst; private JButton[][] buttonBoard = new JButton[rows][cols]; private final static int rows = 10; private final static int cols = 10; public Player(String name){ initComponents(); } private void initComponents(){ for(int i = 0; i <= rows; i++){ for(int j = 0; j <= cols; j++){ buttonBoard[i][j] = new JButton(); } } } public JButton[][] getBoard(){ return buttonBoard; } } And the code I want to use the object in is: public class BattleshipUI extends JFrame { private JMenuBar menuBar; private JMenu gameMenu; private JMenu optionMenu; private JMenuItem playerPlayer; private JMenuItem playerComputer; private JMenuItem computerComputer; private JMenuItem exit; private JMenuItem game; private JMenuItem player; private JButton deploy; private JPanel shipLayoutPanel; private JPanel playerOnePanel; private JComboBox shipCb; private JComboBox directionCb; // Data arrays for various components on the UI private String[] rowLetters = {" ","A","B","C","D","E","F","G","H","I","J"}; private String[] columnNumbers = {" ","1","2","3","4","5","6","7","8","9","10"}; private String[] ships = {"Carrier","Battleship","Submarine","Destroyer", "Patrol Boat"}; private String[] direction = {"Horizontal","Vertical"}; private static final int PLAYER_ONE = 0; private static final int PLAYER_TWO = 1; private Player playerOne; private Player playerTwo; private Player[] players = new Player[2]; private Color[] color = {Color.cyan, Color.green, Color.yellow, Color.magenta, Color.pink, Color.red, Color.white}; public BattleshipUI(){ initComponents(); initObjects(); } public BattleshipUI getThisParent(){ return this; } private void initObjects(){ playerOne = new Player("Player One"); playerTwo = new Player("Player Two"); players[1] = playerOne; players[2] = playerTwo; } private void initComponents(){ this.setTitle("Battleship"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setPreferredSize(new Dimension(500,500)); this.setMinimumSize(new Dimension(500,500)); menuBar = new JMenuBar(); gameMenu = new JMenu("Game"); optionMenu = new JMenu("Option"); menuBar.add(gameMenu); menuBar.add(optionMenu); playerPlayer = new JMenuItem("Player vs. Player"); playerComputer = new JMenuItem("Player vs. Computer"); computerComputer = new JMenuItem("Computer vs. Computer"); exit = new JMenuItem("Exit"); gameMenu.add(playerPlayer); gameMenu.add(playerComputer); gameMenu.add(computerComputer); gameMenu.add(exit); playerPlayer.setEnabled(false); computerComputer.setEnabled(false); game = new JMenuItem("Game Options"); player = new JMenuItem("Player Options"); optionMenu.add(game); optionMenu.add(player); shipLayoutPanel = new JPanel(); shipLayoutPanel.setBorder(BorderFactory.createTitledBorder("Select Ship and Direction")); shipCb = new JComboBox(ships); directionCb = new JComboBox(direction); deploy = new JButton("DEPLOY"); deploy.setEnabled(false); shipLayoutPanel.add(shipCb); shipLayoutPanel.add(directionCb); shipLayoutPanel.add(deploy); playerOnePanel = new JPanel(new GridLayout(11,11)); playerOnePanel.setMinimumSize(new Dimension(400,400)); playerOnePanel.setPreferredSize(new Dimension(400,400)); playerOnePanel.setBorder(BorderFactory.createTitledBorder("Player One")); for(int i = 0; i <= 10; i++){ for(int j = 0; j <= 10; j++){ playerOnePanel.add(playerOne.getBoard()); } } this.setJMenuBar(menuBar); this.add(shipLayoutPanel, BorderLayout.NORTH); this.add(playerOnePanel, BorderLayout.WEST); this.setVisible(true); } } Is there a way to do this? I need to use the methods and variables listed. A: You seem to initialize the players (and their boards respectively) after trying to add their board to a panel, which is impossible since you did not create the players yet. public BattleshipUI(){ initComponents(); //Here you try to add the board of a player initObjects(); //Here you initialize the players (ergo nullpointer) } private void initComponents(){ for(int i = 0; i <= 10; i++){ for(int j = 0; j <= 10; j++){ //playerOne is not instantiated yet playerOnePanel.add(**playerOne**.getBoard()); } } } private void initObjects(){ **playerOne** = new Player("Player One"); playerTwo = new Player("Player Two"); players[1] = playerOne; players[2] = playerTwo; } A: Another thing I see is: You are trying to add a multi-dimensional JButton-Array at once to the JPanel. I think this will not work (please correct me if i am wrong). You have to do this Button by Button: JButton[][] board = playerOne.getBoard(); for(int i=0;i<rowSize;i++){ for(int j=0;j<columnSize;j++){ playerOnePanel.add(board[i][j]); } } Notice: Obviously you have to get somehow the row size and column size and declare as a variable as here as rowSize and columnSize.
{ "language": "en", "url": "https://stackoverflow.com/questions/42011144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run all javascript files in a folder with NodeJS? I want to have a folder with javascript files and be able to programmatically run whatever is on them asynchronously. For example: async.each(folder_files, function(content, cb){ run_script(content); cb(); },function(err){ if(err){ console.log(err); }else{ console.log("All scripts ran succesfully :D"); } }); Is this even possible? EDIT: Just to clarify, I want to be able to change the folder contents with any number of scripts and run them through the main JS file. A: Here is a simple solution using async , but you need to put all your scripts inside scripts folder beside the main file const fs = require('fs') const exec = require('child_process').exec const async = require('async') // npm install async const scriptsFolder = './scripts/' // add your scripts to folder named scripts const files = fs.readdirSync(scriptsFolder) // reading files from folders const funcs = files.map(function(file) { return exec.bind(null, `node ${scriptsFolder}${file}`) // execute node command }) function getResults(err, data) { if (err) { return console.log(err) } const results = data.map(function(lines){ return lines.join('') // joining each script lines }) console.log(results) } // to run your scipts in parallel use async.parallel(funcs, getResults) // to run your scipts in series use async.series(funcs, getResults)
{ "language": "en", "url": "https://stackoverflow.com/questions/50558532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP code in JavaScript to get variable When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath. <?php while(has_list_regions()) { ?> <a href="javascript:show_region('<?php echo list_region_id() ?>');"></a> <?php } ?> <script type="text/javascript"> function show_region(chosen_region_id) { ; $(this).slideDown(200); ; <?PHP $clicked_tag = 'chosen_region_id'; ?> } </script> Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work. A: PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on. You can however use PHP to generate the required JS along with your content. The way you've written it won't work. For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic) function show_region(chosen_region_id) { ... $.post('yourserver.com/getclickedtag.php', {clicked_tag: chosen_region_id}, function(data) { ... }); ... } A: In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/13784380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: unique form field validation in extjs4 Is there a cleaner way to define unique form field in extjs. Below is a sample code that is checking on client UID on client creation/edition. This code is working but has some bugs - for example on client creation if you enter a value that is already present in DB validator returns true until you unfocus the field. Ext.define('AM.view.client.UniqueField', { extend: 'Ext.form.field.Text', alias : 'widget.uniquefield', vtype: 'UniqueUid', initComponent: function() { Ext.apply(Ext.form.field.VTypes, { UniqueUidMask : /[0-9]/i, UniqueUid : function(val,field) { if (val.length < 9) { Ext.apply(Ext.form.field.VTypes, { UniqueUidText: 'Company ID is too small' }); return false; } else { var paste=/^[0-9_]+$/; if (!paste.test(val)) { Ext.apply(Ext.form.field.VTypes, { UniqueUidText: 'Ivalid characters' }); return false; } else { var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'}); mask.show(); var test= 0; var store = Ext.create('AM.store.Clients'); store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}}); store.on('load', function(test) { mask.hide(); if(parseInt(store.getTotalCount())==0){ this.uniqueStore(true); }else{ Ext.apply(Ext.form.field.VTypes, { UniqueUidText: 'Company ID is already present' }); this.uniqueStore(false); } },this) return true; } }} },this); this.callParent(arguments); }, uniqueStore: function(is_error){ Ext.apply(Ext.form.field.VTypes, { UniqueUidMask : /[0-9]/i, UniqueUid : function(val,field) { if (val.length < 9) { Ext.apply(Ext.form.field.VTypes, { UniqueUidText: 'Company ID is too small' }); return false; } else { var paste=/^[0-9_]+$/; if (!paste.test(val)) { Ext.apply(Ext.form.field.VTypes, { UniqueUidText: 'Ivalid characters' }); return false; } else { var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'}); mask.show(); var store = Ext.create('AM.store.Clients'); store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}}); store.on('load', function(test) { mask.hide(); if(parseInt(store.getTotalCount())==0){ this.uniqueStore(true); }else{ this.uniqueStore(false); } },this) return is_error; } }} },this); } }); A: How about using server side validation? I answered to similar issue here: extjs4 rails 3 model validation for uniqueness Obviously you can change it to use "ajax" instead of "rest" proxy.
{ "language": "en", "url": "https://stackoverflow.com/questions/6321468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to set the initial topic assignments for scikit-learn LDA? Instead of setting the topic_word_prior as a parameter, I would like to initialize the topics according to a pre-defined distribution over words. How would I set this initial topic distribution in sklearn's implementation? If it's not possible, is there a better implementation to consider? A: If you have a predefined distribution of words in a pre-trained model you can just pass a bow_corpus through that distribution as a function. Gensims LDA and LDAMallet can both be trained once then you can pass a new data set through for allocation without changing the topics. Steps: * *Import your data *Clean your data: nix punctuation, numbers, lemmatize, remove stop-words, and stem *Create a dictionary dictionary = gensim.corpora.Dictionary(processed_docs[:]) dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000) *Define a bow corpus bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs] *Train your model - skip if it's already trained ldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=bow_corpus, num_topics=15, id2word=dictionary) *Import your new data and follow steps 1-4 *Pass your new data through your model like this: ldamallet[bow_corpus_new[:len(bow_corpus_new)]] *Your new data is allocated now and you can put it in a CSV
{ "language": "en", "url": "https://stackoverflow.com/questions/55753444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why I should add '&' before the parameter which is an unordered_map? unordered_map<int, string>::iterator findElement(unordered_map<int, string> &intString, int index){ return intString.find(index); } If I don't add the & before the intString, the code will crash. A: The & in the type for the function-parameter intString means that the function gets a reference to the passed argument, instead of a copy of it. Thus, the iterator which is returned from .find() and which it returns in turn will point into the passed argument, instead of being a dangling iterator pointing somewhere into a no longer existing copy. And accessing destroyed objects, especially if the memory was re-purposed, can have all kinds of surprising results, which is why it is called Undefined Behavior (UB).
{ "language": "en", "url": "https://stackoverflow.com/questions/49397062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Call Python google cloud endpoint api from android At this point I have created a python app-engine endpoint api called paper (as also noted in the app.yaml) file. I have placed all the jars, including the …-java-1.13.2-beta-sources.jar file, in the libs directory of my android project. How do I call one of my web services (aka endpoint methods)? As in I don't know the name of the package that would lead me to the api, which in the python backend is simply class PageApi(remote.Service):. Imagine the paper api has a method called countPages(self):. How would I call the service? I have already tried importing import com.appspot.api.services.[etc] but eclipse does not see the importing path. EDIT: I reload the api. I check that everything looks okay on api explorer. Then I found two packages that seem to be my packages -- except they contain no classes at all. import com.google.api.services.page.*; import com.google.api.services.page.model.*; If they are indeed the packages, why would the classes be missing? A: First. Once you have your projects setup correctly then the same wizard that generated your client library will copy it to your Android project and extra the source files. then you will find the packages you need in the endpoint-libs folders in your project explorer. Take a look at this post for tips on getting that working. Then you invoke an endpoint using Android code like this: final HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = new JacksonFactory(); endpointname.Builder builder = new endpointname.Builder( transport, jsonFactory, null ); builder.setApplicationName( appName ); endpointname service = builder.build(); try { response = service.methodName( parameters ).execute(); } catch (IOException e) { Log.e(...); }
{ "language": "en", "url": "https://stackoverflow.com/questions/15622779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Multipeer Connectivity Session in iOS7 I've looked into Apple's documentation but is still uncleared about one thing, the session. * *When - (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler is called, we need to pass in a session to the invitationHandler. What will happen to this session? When A invites B to join a session that A created, does B provide a new session to A as well? What is inside B's session? Is it just A alone or does it include all the peers that are currently in A's session? Should B keep track of the session that's been used to accept A's invitation? Inside this article, http://nshipster.com/multipeer-connectivity/, the tutorial creates a new session on the fly and uses it to accept the invitation, wouldn't you lose the session once the function is ended; thus losing information to connected peers? *Assuming that B, C and D are all invited by A, and now B wants to send something to C. Is it required that B needs to send the information to A first or can B send the information directly to C? *According to the Apple's documentation, a single session can only hold no more than 8 peers. Is it possible to make an array of sessions so that you can invite more than 8 people to join your device? If that is the case, does client also need to respond with an array so that it can carry more than 8 peers in its list? *Assuming A and B are now connected, and A now invites C to join. How does B know that C is now in the session? Thank you for reading such a long post. A: There's not much in the way of documentation on Multipeer Connectivity, so these answers are based on my own experiments: * *There are lots of questions inside this one question, but in a nutshell A's session(s) manage invitations that A has sent or accepted. So if B invites and A accepts, the session that A passes when accepting will then be used in the MCSessionDelegate session: peer: didChangeState: callback to say whether the connection happened. At this point the connectedPeers property of A's session will contain B (if the connection succeeded). The session that B used to send the invitation will also get the same callback once A accepts, and will contain A in connectedPeers. Neither A nor B will have any information on the other's session that managed this connection between them. And yes, if you want to send any data to the newly connected peer, you need to keep a reference to the session that handled the connection. I've yet to see any real advantage in creating a new session for each invitation. *Based on the above, B has no information on who A is connected to. So if A is connected to B,C and D, the only peer B knows about is the peer that it connected to - A. What Multipeer Connectivity offers here is the ability for B to discover C or D via A. So if the A-B connection was made over WiFi, and A-C over Bluetooth, but B does not have Bluetooth enabled, and C is on a different WiFi network to B, B and C can still discover each other through A. The process of inviting and accepting is still up to B and C to handle though. *I answered a question about session management here that may be helpful Best option for streaming data between iPhones *B doesn't know anything about A connecting to C. All B can do is discover C for itself and add C to it's own session. A: * *From quickly looking over Chris's answer it seems accurate from what I've been working on at my job. *I'm currently working on a game using multipeer connectivity and have found that: (Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C. the Multipeer Framework is a P2P framework and automatically connects everyone together. even if (as in my current project) you set it up as a Server-client model, all peers will still be connected and you can send messages between B and C without going through A. Depending on what you are doing with your app. *Go with Chris's answer *Addressed in #2 I recommend looking at the example project in the Apple Docs and carefully watch what happens in the debug area when you connect. Also, as a side note: Scenario:(A is only on wifi),(B is on wifi and bluetooth),(C is on bluetooth only) if A connects to B via wifi, and B connects to C via bluetooth, A will still be connected to C but you won't be able to send a message from A directly to C because they are on different networks. A: @SirCharlesWatson: (Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C. the Multipeer Framework is a P2P framework and automatically connects everyone together. My question is: when B automatically connected to C, will B & C receive a state change notification on the existed session? * *A: session:peer:B didChangeState(MCSessionStateConnected) *B: session:peer:A didChangeState(MCSessionStateConnected)
{ "language": "en", "url": "https://stackoverflow.com/questions/22752700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: javascript to allow me to collapse accordion that is extended I have a side navigation bar that consists of multiple accordions that when expanded shows more navigation buttons. I have a bit of JavaScript that will only allow one of those accordions to be expanded at a time. However if I click on one accordion to expand it, when I click the same accordion it remain open. I would like to get it so that I can expand and collapse the accordion without having to expand another accordion. JavaScript: var acc = document.getElementsByClassName("nav-link-bottom-main"); var i; var last; for (i = 0; i < acc.length; i++) { acc[i].onclick = function() { if (last) { last.nextElementSibling.classList.toggle("show"); } this.nextElementSibling.classList.toggle("show"); last = this; } } html: <div> <button class="nav-link-bottom-main toggle"><a href="#">Endpoint Section 1</a></button> <div class="panel"> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 1.1</a></button> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 1.2</a></button> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 1.3</a></button> </div> <button class="nav-link-bottom-main toggle"><a href="#">Endpoint Section 2</a></button> <div class="panel"> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 2.1</a></button> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 2.2</a></button> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 2.3</a></button> <button class="nav-link-bottom-sub toggle"><a class="GET-icon"><center>GET</center></a><a href="#">endpoint 2.4</a></button> </div> A: It looks like whenever if (last) condition is true and it's the same element as this, you're toggling show class twice on same element, so probably this is why it remains open (actually it closes and opens again at the same time). So try to check if you're not toggling same element like this: if (last && last != this) { last.nextElementSibling.classList.toggle("show"); } this.nextElementSibling.classList.toggle("show"); And I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/57287743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can i plot series first bar's close price of super trend (long/short)? how can i plot series first bar's close price of super trend (long/short) ? //@version=5 indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true) atrPeriod = input(10, "ATR Length") factor = input.float(3.0, "Factor", step = 0.01) [supertrend, direction] = ta.supertrend(factor, atrPeriod) bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false) A: var float first_close = 0. if barstate.isfirst first_close := supertrend A: You will have to save the close price whenever the direction changes into a variable and then you can plot that variable. Example below //@version=5 indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true) atrPeriod = input(10, "ATR Length") factor = input.float(3.0, "Factor", step = 0.01) [supertrend, direction] = ta.supertrend(factor, atrPeriod) bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false) var firstbarsclose=close if direction<0 and direction[1]>0 firstbarsclose:=close if direction>0 and direction[1]<0 firstbarsclose:=close plot(firstbarsclose,style=plot.style_stepline)
{ "language": "en", "url": "https://stackoverflow.com/questions/73097293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I tried several times but still animation is not working, please help me to fix it CSS parts Blockquote I was just making a box and apply animation over it, these are respective lines of code <style> .box { background-color:red; margin-top: 100px; width: 200px; height: 100px; position: relative; animation-name: raw; animation-duration: 2ms; animation-timing-function: ease-in; } @keyframes raw { 0% { background-color: grey; } 50% { background-color:lime; } 100% { background-color:brown; } } </style> Body Here it is a box over which I want to apply animation <body> <div class="box"> BOX </div> </body> A: You are using ms instead of s. Your animation is working, but it finishes so fast that you just can't see it. Therefore, you should give it a longer duration.
{ "language": "en", "url": "https://stackoverflow.com/questions/67900854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Export data from database to sql file with PHP I need to export data (only the data, not the tables nor database) from the database to a SQL file and save it. How to write a PHP function that does that? I want to call this function in specific circumstances when running specific queries (updating a blog post, for example). Something like: /* * Get the data from the database (already specified) and export it to a SQL file * * @param string $dir Where to store the SQL file. Must be a full path. * @return void */ function export_database_data(string $dir) { // some code that gets the data and store it in $data // don't know what to do here // create/update the file file_put_contents("$dir/data_backup.sql", $data); } Why this? (You don't need to read the following to help me solve the problem. I'm including this because I'm sure if don't include this, someone will ask it). I want to do that because I want to have a backup of the data (only the data; the tables do not matter because I already know how to handle them for backup). I'm doing this because I will use the PHP function exec to run git commands and commit the change in the SQL file. The end goal is to keep track of the data in the database, which won't be updated often. I need the data in a SQL file and I aim to use git because it is easy to access and to collaborate with others (I could not think a better solution, and creating my own tracking system would require a lot of work and time). A: You can run a mysqldump command using PHP exec function to only export data. Ex: exec('mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql'); More info: * *mysqldump data only *Using a .php file to generate a MySQL dump
{ "language": "en", "url": "https://stackoverflow.com/questions/57632218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error while unzipping JSON file (Firefox) in my Node.js application I have a route where I am fetching a big chunk of JSON data from database (Postgres) and sending it in compressed format in a response. I am using Zlib module to gzip this data. I am setting Content-Type: application/gzip and Content-Encoding: gzip before sending a response. Now all this set up works well with Chrome and Safari browsers (unzipping data successfully) but for some reason this is not working in Firefox. Request header contains Accept-Encoding: gzip, deflate. In browser(Firefox) console I see following errors Attempt to set a forbidden header was denied: Accept-Encoding and SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Can anybody please guide me what this issue is and how can I solve it? Thanks! A: Ok, I will answer my question with what worked for me. On server side, I changed the way I was compressing the data. I am using deflate method of Zlib module instead of gzip. Also changed the response header with these values. Content-Encoding: deflate and Content-Type: application/deflate I am still not sure why gzip does not work (or at least did not work for me) but because of time constraint I am going with deflate for now. Also gzip and deflate uses same compression algorithm and deflate is faster in encoding and decoding. I hope this helps and please correct me if I'm wrong at any place. Thanks! A: In modern browsers, according to https://developer.mozilla.org/en-US/docs/Web/API/Headers, For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. Forbidden header names include "Accept-Encoding".
{ "language": "en", "url": "https://stackoverflow.com/questions/46108399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the Thingsboard IoT platform's default system administrator account? What is the Thingsboard IoT platform's (https://thingsboard.io) default system administrator account after a fresh (Raspberry Pi) installation? The existing documentation only refers to default "tenant" account, which is ok on my setup. Thanks in advance. A: Default system administrator account: * *login - sysadmin@thingsboard.org *password - sysadmin Default demo tenant administrator account: * *login - tenant@thingsboard.org. *password - tenant. Demo tenant customers: Customer A user: customerA@thingsboard.org. Customer B user: customerB@thingsboard.org. Customer C user: customerC@thingsboard.org. all users have “customer” password. Take a look at demo-account documentation page for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/41832556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to Directly Upload file to other server So I have a project in which i want to upload video to dailymotion using api So i want to Upload video directly to dailymotion server without uploading it to my local server My Action [HttpPost] public async Task<ActionResult> Add(Video Videos) { var fileToUpload = @"E:\Courses\[FreeCourseLab.com] Udemy - C# Intermediate Classes, Interfaces and OOP\5. Polymorphism Third Pillar of OOP\3. Sealed Classes and Members.mp4"; return RedirectToAction("AddVideo", "Admin"); } my View @using (Html.BeginForm("Add", "Admin", FormMethod.Post, new { @class = "px-lg-4", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary("", new { @class = "text-danger" }) <div class="input-group input-group--focus mb-lg-4" style="width: 100%"> <div class="input-group-prepend"></div> @Html.TextBoxFor(m => m.Videos.File, new {@type="file" }) </div> <input type="submit" class="d-flex justify-content-center btn btn-block btn-primary" value="Create" /> }
{ "language": "en", "url": "https://stackoverflow.com/questions/57901771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C fork - how to wait for all children before starting workload? I am trying to get fork() to create multiple processes all of which do the same work. I need all of them to get created first, and then at the same time start doing work. That is, I want all of the processes to wait for all of the other ones to get created, and once they are all ready, start doing the work at the same exact time. Is this possible? Thanks. A: The simplest approach would be simply using signals, do note however that there is no way to actually guarantee that the processes will indeed run in parallel. That's for the OS to decide.
{ "language": "en", "url": "https://stackoverflow.com/questions/19210566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL orientation. (Identity rotation looking in negative z) I'm implementing a renderer that handles every translation- / view- / model- / projection-matrix (I don't use glRotate / glTranslate etc.). I have placed several blue objects along the positive z-axis and some red objects on the positive x-axis (So I should be able to see the red objects to my left and the blue ones straight ahead using identity rotation on my camera). It is right-hand-orientation, right? The problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z. I'm constructing my View matrix by taking the inverse of the cameras matrix [Rot Tr] and then I put it in a array column-wise and pass it to my shader. For the objects (World matrix) I just pass the matrix [Rot Tr] column-wise to the shader. Should I negate the translation? The projection matrix is for now constructed in the vertex shader as I am working my way through. As you can se below I'm doing position = proj*view*model*gl_Vertex; At the moment I use gl_Vertex (I use glutSolidCube after loading identity matrix as my scene objects). uniform mat4 view; uniform mat4 model; varying vec4 pos; void main() { pos = gl_Vertex; float aspect = 1.0; float fovy = 1.5; float f = 1.0 / tan(fovy * 0.5); float near = 1.0; float far = 100.0; float tt = 1.0 / (near - far); mat4 proj = mat4(f/aspect, 0.0, 0.0, 0.0, 0.0, f, 0.0, 0.0, 0.0, 0.0, (near+far)*tt, -1.0, 0.0, 0.0, 2.0*near*far*tt, 0.0); gl_Position = proj * view * model * pos; } In my fragment shader I set the color = pos so that I can see the color of the axis and the colors appears correct. I think the objects are correctly placed in the scene but with Identity matrix as rotation I'm still looking the opposite way. What could I have missed? Am I passing the correct matrices in a correct manner? A: A right-handed coordinate system always looks down the -Z axis. If +X goes right, and +Y goes up (which is how all of OpenGL works), and the view is aligned to the Z axis, then +Z must go towards the viewer. If the view was looking down the +Z axis, then the space would be left-handed. A: The problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z. Yes it is. The coordinate systems provided yb OpenGL in form for glOrtho and glFrustum are right handed (take your right hand, let the thumb towards the right, the index finger up, then the index finger will point toward you). If you modeled your matrix calculations along those, then you'll get a right handed system as well. A: Alright completely rewrote this last night and I hope you find it useful if you haven't already came up with your own solutions or someone else who comes along with a similar question. By default your forward vector looks down the -Z, right vector looks down the +X, and up vector looks down the +Y. When you decide to construct your world it really doesn't matter where you look if you have a 128x128 X,Z world and you are positioned in the middle at 64x64 how would any player know they are rotated 0 degrees or 180 degrees. They simply would not. Now you mentioned you dislike the glRotatef and glTranslatef. I as well will not use methods that handle the vector and matrix math. Firstly I use a way where I keep track of the Forward, Up, and Right Vectors. So imagine yourself spinning around in a circle this is you rotating your forward vector. So when a player wants to let's say Run Straight ahead. you will move them along the X,Z of your Forward vector, but let's say they also want to strafe to the right. Well you will still move them along the forward vector, but imagine 90 degrees taken off the forward vector. So if we are facing 45 degrees we are pointing to the -Z and -X quadrant. So strafing will move us in the -Z and +X quadrant. To do this you simple do negate the sin value. Examples of both below, but this can be done differently the below is rough example to better explain the above. Position.X -= Forward.X; //Run Forward. Position.Z -= Forward.Z; Position.X += Forward.Z; //Run Backwards. Position.Z += Forward.Z Position.X += Forward.X; //Strafe Right. Position.Z -= Forward.Z; Position.X -= Forward.X; //Strafe Left. Position.Z += Forward.Z; Below is how I initialize my view matrix. These are to only be performed one time do not put this in any looping code. glMatrixMode(GL_MODELVIEW); view_matrix[4] = 0.0f; //UNUSED. view_matrix[3] = 0.0F; //UNUSED. view_matrix[7] = 0.0F; //UNUSED. view_matrix[11] = 0.0F; //UNUSED. view_matrix[15] = 1.0F; //UNUSED. update_view(); glLoadMatrix(view_matrix); Then this is the update_view() method. This is to only to be called during a change in the view matrix. public void update_view() { view_matrix[0] = Forward[0]; view_matrix[1] = Up[1] * Forward[1]; view_matrix[2] = Up[0] * -Forward[1]; view_matrix[5] = Up[0]; view_matrix[6] = Up[1]; view_matrix[8] = Forward[1]; view_matrix[9] = Up[1] * -Forward[0]; view_matrix[10] = Up[0] * Forward[0]; } The Position vectors are matricies [12], [13], and [14] and are negated. You can choose to store these or just use matrix[12], [13], [14] as the vector for position. view_matrix[12] = -Position.x; view_matrix[13] = -Position.y; view_matrix[14] = -Position.z;
{ "language": "en", "url": "https://stackoverflow.com/questions/9448885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: uploading an array to server in swift using Alamofire This is how I'm saving the data successfully to model class when user login var isLogin: IsLogin! var loginDetail: LoginDetail! var myDetail: MyDetail! let decoder = JSONDecoder() do{ isLogin = try decoder.decode(IsLogin.self, from: response.data!) loginDetail = isLogin.success myDetail = loginDetail.user }catch{ print(error) } here is my model class where I'm saving response from the request struct IsLogin: Decodable { var success: LoginDetail } struct LoginDetail: Decodable { var user: MyDetail } struct MyDetail: Decodable { var id: Int var emergency_contacts: [EmergencyContacts]? } struct EmergencyContacts: Decodable { var user_id : Int var number : String } I want to post EmergencyContacts in another request how do I do that? This is how im trying but in response array of EmergencyContacts is always empty multipartFormData.append("\(myDetail.emergency_contacts!)".data(using: .utf8,allowLossyConversion: false)!, `enter code here`withName: "emergency_contacts") I have print all the values from model class and they are fine but guide me about how to send an array in a post request.Please suggest my some method using multipartformdara because I have been using this to send other parameters as well.below is the postman screenshot where If I send parameters like this then I can get the emergencycontacts in response 13 is the id of emergency contact
{ "language": "en", "url": "https://stackoverflow.com/questions/63713852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use a template template argument from a member templated type alias of a struct I'm trying to use a template template argument coming from a member type alias of a struct, but I can't find the right syntax: struct A { template <typename T> using type = int; }; template <template <typename> class C> struct B { // ... }; B<typename A::type> b; // Does not compile: error: template argument for template template parameter must be a class template or type alias template B<typename A::template type> b; // Does not compile: error: expected an identifier or template-id after '::' B<typename A::template <typename> type> b; // Does not compile B<typename A::template <typename> class type> b; // Does not compile A: A::type is a template, not a typename. B<A::template type> b1; // OK B<A::type> b2; // OK
{ "language": "en", "url": "https://stackoverflow.com/questions/69383065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save on Camera Photo on Custom Location? I am currently using the following code here: val cameraRequestCode = 1 val cameraPermissionCode = 1 var imageUri : Uri? = null @RequiresApi(api = Build.VERSION_CODES.M) override fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent? ) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == cameraRequestCode) { if (resultCode == Activity.RESULT_OK) { var stream: FileOutputStream? = null try { val photo: Bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri) val saveFilePath: String = getRealPathFromURI(imageUri) stream = FileOutputStream(saveFilePath) photo.compress(Bitmap.CompressFormat.JPEG, 25, stream) } catch (e: IOException) { e.printStackTrace() Toast.makeText( applicationContext, "Can't save image !", Toast.LENGTH_SHORT ).show() } finally { try { if (stream != null) { stream.close() Toast.makeText( applicationContext, "Image saved successfully !", Toast.LENGTH_SHORT ).show() } else { Toast.makeText( applicationContext, "Can't save image, try again !", Toast.LENGTH_SHORT ).show() } } catch (e: IOException) { e.printStackTrace() } } farmersPixImageView.setImageURI(imageUri) } else if (resultCode == Activity.RESULT_CANCELED) { Toast.makeText(applicationContext, "Cancelled", Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext, "Can't capture image !", Toast.LENGTH_SHORT) .show() } } } private fun getRealPathFromURI(contentUri: Uri?): String { val proj = arrayOf(MediaStore.Images.Media.DATA) val cursor: Cursor = managedQuery(contentUri, proj, null, null, null) val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() return cursor.getString(column_index) } @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add) farmersPixImageView.setOnClickListener { //if system os is Marshmallow or Above, we need to request runtime permission if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ) { //permission was not enabled val permission = arrayOf( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE ) //show popup to request permission requestPermissions(permission, cameraPermissionCode) } else { val values = ContentValues() values.put( MediaStore.Images.Media.TITLE, "${relativeFileName}_${System.currentTimeMillis()}" ) values.put( MediaStore.Images.Media.DISPLAY_NAME, "${relativeFileName}_${getDate( System.currentTimeMillis(), "MM/dd/yyyy hh:mm:ss.SSS" )}" ) values.put(MediaStore.Images.Media.DESCRIPTION, "My Photos") values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") imageUri = contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values ) val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri) startActivityForResult(cameraIntent, cameraRequestCode) } } } } I am using this because I could not get the sample from the Official Documentation to work. I previously used: values.put(MediaStore.Images.Media.RELATIVE_PATH, relativeLocation) but it is only available on Android Q onwards. I also don't know how to use imageUri to save to custom location because it using contentResolver: imageUri = contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values ) How do I save the photo on custom location using the above code?
{ "language": "en", "url": "https://stackoverflow.com/questions/62898400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Random access of multiple files and file caching This relates to some software I've been given to "fix". The easiest and quickest solution would make it open and read 10 random files out of hundreds and extract some very short strings for processing and immediately close them. Another process may come along right after that and do the same thing to different, or the same, random files and this may occur hundreds of times in a few seconds. I know modern operating systems keep those files in memory to a point so disk thrashing isn't an issue as in the past but I'm looking for any articles or discussions about how to determine when all this open/closing of many random files becomes a problem. A: When your working set (the amount of data read by all your processes) exceeds your available RAM, your throughput will tend towards the I/O capacity of your underlying disk. From your description of the workload, seek times will be more of a problem than data transfer rates. When your working set size stays below the amount of RAM you have, the OS will keep all data cached and won't need to go to the disk after having its caches filled.
{ "language": "en", "url": "https://stackoverflow.com/questions/1755786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-7" }
Q: Inverted a Responsive Size for an Image I'm attempting to use the following design on a responsive website. I'm curious if there's a way to set up some sort of inverse resizing method through jQuery / Javascript because as the viewport gets smaller, the copy will respond and get larger. I've tried using jQuery to modify the image size, but I only know enough to manually resize it at different breakpoints Here's my attempt at a solution: var viewportWidth = $(window).width(); if (viewportWidth <= 768) { $("#curlybrace").css("width", "80px"); } Is there a way to set up a dynamic scaling image? A: Try looking into CSS and media queries, seems like it would be a neater solution than trying to do this with JS. A: You would use something like this: function resizeFn() { var width = window.width(); // ... } $(function() { $(window).resize(resizeFn).trigger('resize'); }); Not possible to do an inverse with CSS, I don't think (I thought maybe through calc(), but I don't think it lets you do unit manipulations like that). Fair warning, this doesn't sound like a good design unless you're trying to make it look nuts.
{ "language": "en", "url": "https://stackoverflow.com/questions/29056531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: scraping only a particular tag without details from nested tag in that particular tag I have a page where the structure is something like <body> <article> <!--article no 1--> <h3> <h2> <h1> <a> <!--first 'a' tag--> <article> <!--article no 2--> <h1> <h2> <a> <!--second 'a' tag--> </article> </article> </body> Now what I want is I want to extract all 'a' tags inside an article but such that no 'a' tag comes from any nested that is articles = browser.find_elements_by_tag_name("article") for i in article: print(i.find_elements_by_tag_name("a") for first article now i.find_elements will return all 'a' tags inside this article tag which will also include 'a' tags inside 'article tag' that is itself nested in current article tag but i dont want that I want if i call find_elements on article no 1 'a' tags in article no 2 or in any nested article should not come A: If you want links from not nested articles, try: articles = browser.find_elements_by_tag_name('article'): for article in articles: print(article.find_elements_by_xpath('./*[not(descendant-or-self::article)]/descendant-or-self::a')) A: Parse the article element with BeautifulSoup and get all the anchor tags in ease. from bs4 import BeautifulSoup articles = browser.find_elements_by_tag_name("article") links = [] for i in articles: soup = BeautifulSoup(i.get_attribute('outerHTML'), 'html5lib') a_tags = soup.findAll('a') links.extend(a_tags) Hope this helps! Cheers! A: using BeautifulSoup, try to find all <a> under <articla> like ('article a') then use find_parents() method of beautifulsoup. If length of ('article a').find_parents('article') is bigger than 2, that might be nested like this. <article> .. <article> .. <a> so if you remove them you will get <a> that has only one <article> parent all_a = soup.findAll('article a') direct_a = [i for i in all_a if len(i)>2]
{ "language": "en", "url": "https://stackoverflow.com/questions/52160845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to automatically detect types in Specflow tables? If I have a Techtalk.Specflow.Table, is it possible to detect automatically the appropriate types of the elements in the table ? For exemple, if I have the following steps : Given the following ticket sold on the 2019-01-01 |TicketId|Owner |Amount|Seat| |0033 |John Doe |20.00 |3F | If I define my step like this [Given(@"Given the following ticket sold on the (.*)")] public void GivenTheFollowingPosition(DateTime date, Table table) { } Specflow is capable of detecting and cast the date correctly. Therefore I assume it should also be capable of doing so for the elements of the table. Do you know if it is possible to achieve it and how ? Have a nice day A: Have a look at SpecFlow Assist Helpers. There are a few helpful methods, you can try to use table.CreateInstance<T> method to convert row in your table to object for future use. You can also specify the custom mapping using TableAliases attribute, see Working Effectively with SpecFlow Tables article for details
{ "language": "en", "url": "https://stackoverflow.com/questions/56939759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can we override wsa:To value in SOAP 1.2 I want to override wsa:To element value in SOAP 1.2 message. Can I do this by adding "To" HTTP header to the request ? Could you explain the use of this wsa:To element value on the SOAP 1.2 message header ? A: No. wsa:To is a SOAP header block, not an HTTP header.
{ "language": "en", "url": "https://stackoverflow.com/questions/30248390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Postgres: is it posible to see how a Database View is constructed is it posible to see how a Database View is constructed in Postgres, to see wich query was used to create that view? A: In psql: \d+ the_view --or select definition from pg_views where viewname = 'the_view';
{ "language": "en", "url": "https://stackoverflow.com/questions/66643894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: First link of pagination shows 404 page in CodeIgniter I am working on pagination of category page. my route is $route['category/(:any)/(:num)'] = 'public_controller/category/$1'; And url to go to category page is http://localhost/ecom/category/seats but it shows 404 error page. but when I give http://localhost/ecom/category/seats/1 it works fine and pagination also works fine second and third links are also working but when I click on 1 in pagination it shoes 404 error page. my controller code is public function category($cat_slug = null,$offset = null){ $cat_id = $this->db->where('cat_slug',$cat_slug)->get('categories')->row_array(); $config['base_url'] = base_url() .'category/'.$cat_slug; $config['total_rows'] = $this->db->where('cat_id',$cat_id['cat_id'])->count_all('products'); $config['per_page'] = 4; $config['uri_segment'] = 3; $config['use_page_numbers'] = TRUE; $config['full_tag_open'] = "<ul class='pagination'>"; $config['full_tag_close'] ="</ul>"; $config['num_tag_open'] = '<li>'; $config['num_tag_close'] = '</li>'; $config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>"; $config['cur_tag_close'] = "<span class='sr-only'></span></a></li>"; $config['next_tag_open'] = "<li>"; $config['next_tagl_close'] = "</li>"; $config['prev_tag_open'] = "<li>"; $config['prev_tagl_close'] = "</li>"; $config['first_tag_open'] = "<li>"; $config['first_tagl_close'] = "</li>"; $config['last_tag_open'] = "<li>"; $config['last_tagl_close'] = "</li>"; $this->pagination->initialize($config); $data['products'] = $this->public_model->category_page($cat_slug,$config['per_page'],$offset); $id['cat_slug'] = $cat_slug; $this->load->view('public_temp/header1'); $this->load->view('public_temp/left1',$id); $this->load->view('public/category',$data); $this->load->view('public_temp/footer1'); } What can I try to resolve this? A: It shows because your router expect 2 parameter but you are giving 1 parameter seats Define your route this way $route['category/(:any)/(:num)'] = 'public_controller/category/$1/$2'; Now call your route http://localhost/ecom/category/seats/0 for category page http://localhost/ecom/category/seats/1 for first pagination if you want to separate your category route Define two route one for category page and other for category pagination For category page $route['category/(:any)'] = 'public_controller/category/$1'; For category pagination $route['category/(:any)/(:num)'] = 'public_controller/category/$1/$2'; A: So, I created a demo for your problem and this is what worked for me ↓↓ $route['category'] = 'my_controller/category'; // this route handles all the requests without any additional segments $route['category/(:any)'] = 'my_controller/category/$1'; // this route handles the requests when only one segment is present $route['category/(:any)/(:num)'] = 'my_controller/category/$1/$2'; // this route handles the requests when there are two segments(2nd parameter being a number) This is possible because Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.(Reference) I also found a similar question you might wanna take a look at. Hope this resolves your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/61878128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Case Statements with Not Exists as Part of Where Clause I'm calculating the depreciation of vehicles and need to grab the previous month's values if it exists. I've written a case statement in the where clause to see if the value exists. If it does, then I want to subtract one month and use that value to get the previous months data. If it does not exist then I want the current month's data. But it'll only do one or the other. Am I messing up where the exists is? SELECT b.* --this is month we want to compare (For example month 45) FROM #changes AS a --this has all the months (for example month 1-50) INNER JOIN work.dbo.DepreciationSchedule AS b ON b.VehicleID = a.VehicleID --If the previous months value exists in table b (Ex month 44), then take take that months value otherwise take the current value of table a (Ex month 45) WHERE b.Month = CASE WHEN EXISTS(SELECT * FROM #changes AS innerA WHERE innerA.month = a.month - 1) THEN a.Month - 1 ELSE a.Month END A: I figured it out. There were two things that I had to change. * *Add the vehicle ID to the current subquery to make sure that I only wanted those vehicles in the temp table *Change the subquery table to the depreciation schedule Select b.* --this is month we want to compare (For example month 45) From #changes As a --this has all the months (for example month 1-50) Inner Join work.dbo.DepreciationSchedule As b On b.VehicleID = a.VehicleID --If the previous months value exists in table b (Ex month 44), then take take that months value otherwise take the current value of table a (Ex month 45) Where b.Month = Case When Exists (Select * From work.dbo.DepreciationSchedule As innerA Where innerA.month = a.month - 1 and innerA.VehicleID = a.vehicleID) Then a.Month -1 Else a.Month end
{ "language": "en", "url": "https://stackoverflow.com/questions/55642271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: overloading operator== complaining of 'must take exactly one argument' I am trying to overload the operator==, but the compiler is throwing the following error: ‘bool Rationalnumber::operator==(Rationalnumber, Rationalnumber)’ must take exactly one argument My short piece of code is as follows: bool Rationalnumber::operator==(Rationalnumber l, Rationalnumber r) { return l.numerator() * r.denominator() == l.denominator() * r.numerator(); } Declaration: bool operator==( Rationalnumber l, Rationalnumber r ); Does anyone have any ideas why it's throwing the error? A: As a member operator overload it should only take one argument, the other being this. class Foo { int a; public: bool operator==(const Foo & foo); }; //... bool Foo::operator==(const Foo & foo) { return a == foo.a; } A: If operator== is a non static data member, is should take only one parameter, as the comparison will be to the implicit this parameter: class Foo { bool operator==(const Foo& rhs) const { return true;} }; If you want to use a free operator (i.e. not a member of a class), then you can specify two arguments: class Bar { }; bool operator==(const Bar& lhs, const Bar& rhs) { return true;} A: You should remove your operator== from a RationalNumber to somewhere else. As it is declared inside a class it is considered that 'this' is the first argument. From semantics it is seen that you offer 3 arguments to a compiler. A: friend bool operator==( Rationalnumber l, Rationalnumber r ); when you declare it as non-member function, it can take two arguments. when you declare it as member function, it can only take one argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/11229074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Sumproduct VBA with Loop I know this question has been asked ad nauseum in some form or other, but all of my Googling hasn't led me to a solution. I want to use Sumproduct in a VBA loop with moving criteria references. I know that Sumproduct doesn't work the same in VBA as it does in a spreadsheet. The formula I'm trying to replicate is as follows: =Sumproduct([KNA_Amt]*--([KNA_Dt]=h$25)*--([KNA_Cat]=$b47)*--([KNA_Prgm]=$D$8)) and in an worksheet, this would be dragged down 6 lines and across 12 columns. In VBA, I have the following code, which obviously doesn't work... sub CalcualteSFA() Dim r As Long Dim c As Long r = 87: c = 8 For for_col = 1 To 12 Cells(r, c) = WorksheetFunction.SumProduct([KNA_Amt]*--([KNA_Dt]=Cells(25, c))*--([KNA_Cat]=cells(r,2))*--([KNA_Prgm]=cells(8,4)) r=r+1 next r=87 c=c+1 next end sub So I know that the coding doesn't work, but can someone help me by figuring out a code that would? Thanks so much! A: Multiple formulas can be assigned at the same time, and the relative (without $) row/column references will be auto adjusted : Sub CalcualteSFA() Dim r As Range Set r = [H87:S92] r.Formula = "=Sumproduct([KNA_Amt]*--([KNA_Dt]=h$25)*--([KNA_Cat]=$b47)*--([KNA_Prgm]=$D$8))" r.Value = r.Value ' optional to convert the formulas to values End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/63688584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access to previous steep Html I am learning Elm and I seems that you make a new VirtualDOM every view "frame". view : Model -> Html Msg There is no reference to the previous generated Html value, so there is no option to update it (in a functional way). You must rebuild it from scratch. This is highly inefficient. How can you reuse the old frame and only update changed nodes (and their ancestors)? EDIT As an answers points, Elm have Html.Lazy. With it and the clever runtime you can avoid repeating most of the work and data allocation (useless garbage collector pressure is a bad thing), but at the expenses of adding a lot of cognitive load on the programmer. Reasoning about strictness/laziness on the term level (instead of on the type level) is error prone (see Haskell and seq). The perfect solution would be a view function with this signature: view : Model -> Html Msg -> Html Msg This way you have access to the previous frame VirtualDOM and you can share as much of it with the new frame data structure as you want. Is this option available? If not, why not? A: As you know, Elm uses a "virtual DOM". Your program outputs lightweight objects that describe the DOM structure you want, and the virtual DOM implementation "diffs" the current and new structure, adding, modifying, and removing elements/attributes/properties as required. Of course, there is a small performance penalty to using a virtual DOM over directly manipulating the DOM, but the difference doesn't matter in most web applications. If you find that your application has poor performance in the view function, there are several ways to improve performance, such as Html.Lazy Many other popular libraries use a virtual DOM, such as React, Angular, and Vue. Usually, it's easier to render your application with a virtual DOM (rather than "manually" manipulating the DOM), so many of the popular frameworks implement one.
{ "language": "en", "url": "https://stackoverflow.com/questions/51014268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to simply nested ternary logic in react while rendering different component I have the following logic inside a react component where, I am rendering different component based on the boolean values. This peace of code is very difficult to understand. Are there anyways, I can simply that logic: {isEnabled ? ( <> {!loading ? ( <> {items.length === 0 ? ( <> <ComponentOne/> <Container> <img src={Image} alt="Image" /> </Container> </> ) : ( <ComponentTwo/> )} </> ) : ( <div> <LoadingComponent/> </div> )} </> ) : ( <ComponentThree/> )} A: I'd probably split it up into seperate components and pass parameters down the component tree for example {isEnabled ? <IsLoadingComponent loading={loading} items={items}> : <ComponentThree/>} A: You might find it useful to split the component up into a "Loading" version and a "Loaded" version so you don't have to handle both states in the same component. Then the component basically just renders the "Loading" or "Loaded" version depending on the flag. But even without that, you can at least make that easier to debug by using if/else if etc. and assigning to a temporary variable: let comp; if (isEnabled) { if (loading) { comp = <div> <LoadingComponent/> </div>; } else if (items.length === 0) { comp = <> <ComponentOne/> <Container> <img src={Image} alt="Image" /> </Container> </>; } else { comp = <ComponentTwo />; } } else { comp = <ComponentThree />; } Then just {comp} where that nested conditional was. A: I think you are making a simple thing very complicated. What we can do instead is that make use of "&&". { isEnabled && loading && <LoaderComponent /> } {isEnabled && !items.length && <> <ComponentOne/> <Container> <img src={Image} alt="Image" /> </Container> </> } {isEnabled && items.length && <ComponentTwo/>} {!isEnabled && <ComponentThree />} A: Though I want to support the argument the others made (split into multiple components), you can already achieve a bit more readability by dropping unnecessary fragments (<></>) and/or parenthesis and by using "better"(opinion) indentation. return ( isEnabled ? loading ? <div><LoadingComponent/></div> : items.length === 0 ? <> {/* this is the only place a fragment is actually needed */} <ComponentOne/> <Container> <img src={Image} alt="Image"/> </Container> </> : <ComponentTwo/> : <ComponentThree/> ); Alternatively, early returns do help a lot with readability. For example: const SomeComponent = () => { // ...snip... if (!isEnabled) { return <ComponentThree/>; } if (loading) { return <div><LoadingComponent/></div>; } if (items.length > 0) { return <ComponentThree/>; } return ( <> <ComponentOne/> <Container> <img src={Image} alt="Image"/> </Container> </> ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/69752160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separating Command Buttons and VBA code in Excel I have an Excel worksheet with over 100 rows of data. When the user completes filling in the information in their row, there is a command button at the end of the row that automatically sends an email to a specific email account with information from the row. I've inserted several command buttons with the VB code to send the email and it works great!. The problem I'm having is that I can't separate the command buttons, i.e., each button's code should be specific to the row it is on; when I change the code with the cell location that contains the information for that command button, it changes all of the command buttons to that information. I know the answer must be really simple, but I've drawn a complete blank.I appreciate any help! Here is the code I have: Option Explicit Private Sub CommandButton2_Click() On Error GoTo ErrHandler ' SET Outlook APPLICATION OBJECT. Dim objOutlook As Object Set objOutlook = CreateObject("Outlook.Application") ' CREATE EMAIL OBJECT. Dim objEmail As Object Set objEmail = objOutlook.CreateItem(olMailItem) With objEmail .to = "[email address].com" .Subject = Range("A3") .Body = "[Message]" .Send ' SEND THE MESSAGE. End With ' CLEAR. Set objEmail = Nothing: Set objOutlook = Nothing ErrHandler: ' End Sub Each row should have this same command with only the CommandButton number changing and the .Subject = Range entry changing. I'm doing something wrong though because that doesn't work. A: I said in a comment, it's probably easier to simply color cells to look like buttons and have the users click on a cell to send the emails - then you can simply use the offset for the particular row, but if you insist on using command buttons, it's quite simple. Take your current code and put it in a new subroutine that accepts a range parameter. Then, add your buttons, and link each one to its own code with a different range. Option Explicit Private Sub CommandButton3_Click() SendEmail Range("A3") End Sub Private Sub CommandButton4_Click() SendEmail Range("A4") End Sub Private Sub CommandButton5_Click() SendEmail Range("A5") End Sub `... Sub SendEmail(TheRange as Range) On Error GoTo ErrHandler ' SET Outlook APPLICATION OBJECT. Dim objOutlook As Object Set objOutlook = CreateObject("Outlook.Application") ' CREATE EMAIL OBJECT. Dim objEmail As Object Set objEmail = objOutlook.CreateItem(olMailItem) With objEmail .to = "[email address].com" .Subject = TheRange 'Change this line .Body = "[Message]" .Send ' SEND THE MESSAGE. End With ' CLEAR. Set objEmail = Nothing: Set objOutlook = Nothing ErrHandler: End Sub If you prefer instead to use the SelectionChanged event, you can do it like this. Then, you can just update [C4:C8] if you want to add any more "buttons" Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.CountLarge > 1 Then Exit Sub If Not Intersect(Target, [C4:C8]) Is Nothing Then SendEmail Range("A" & Target.Row) 'Optionally select the subject we sent so we can re-click 'You can choose any other cell not in our event range Range("A" & Target.Row).Select End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/41021545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: R Regex with Stringr: character(0) Error I'm trying to recreate an old project. However, I'm guessing something changed in the stringr package because my code no longer works. Minimum working example (MWE): library(httr) library(stringr) library(XML) url <- "http://www.lq.com/en/findandbook.html" page <- GET(url) s <- content(page, as="text") push <- unlist(str_match_all(s, "hotelList.push?.+?}")) # stopped working Error message: > push <- unlist(str_match_all(s, "hotelList.push?.+?}")) # stopped working Error in stri_match_all_regex(string, pattern, cg_missing = "", omit_no_match = TRUE, : Syntax error in regexp pattern. (U_REGEX_RULE_SYNTAX) My fix: > push <- unlist(str_match_all(s, "hotelList.push?.+?\\}")) # stopped working > push character(0) The string, s, has lines of text. I am trying to find the lines that look like: "hotelList.push({title: \"La Quinta Inn & Suites Phoenix I-10 West\", innNumber: \"0853\", latitude:})" and grab everything between the curly braces. I suck at regular expressions, so after Googling I found the following two suggestions that also did not work. str_match_all(s, "/{(.*?)}/") str_match_all(s, "/{([^}]*)}/") Any advice is greatly appreciated. A: Remove the forward slash and escape the curly braces. str_match_all(s, "\\{([^}]*)\\}") or str_match_all(s, "\\{\\K[^}]*(?=\\})")
{ "language": "en", "url": "https://stackoverflow.com/questions/34430331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does silverlight really solve browser compatibility issues? I'm planning web application and considering silverlight as development platform. Will it help to solve browser compatibility issues? The app intended to be used on desktops only (no mobile). A: Yes, it will solve browser compatibility issues, and could work on both Mac OS and Windows with the very same code. The only drawback is that, the first time your user connect to your application, he will need to download the Silverlight plugin. Awesome you would say? Well, unfortunately some people that probably never try to do something like image processing or advanced line of business application in a browser decide that plugins are not so cool and that you would be able to do the same thing with the magic power of HTML5. We are still waiting to have the same possibility in HTML5 that we have in Silverlight or Flash, but plugins are already dead. At least as long as no big compay want to push them again. So, my advice would be: don't start a project in Silverlight. You will have problems, even if you do not target mobile. For example it becomes harder and harder to find compatible good tools (like ReSharper, NCrunch, or even just a decent unit testing library). And in further release of Windows and Mac OS, it will probably not be supported at all (IE for Windows RT already does not support Silverlight). Sorry man, Silverlight is dead, you arrive after the battle. A: If your developing your application for an Intranet, I would say Silverlight is an excellent choice. If you are developing for the Internet, use an HTML based language
{ "language": "en", "url": "https://stackoverflow.com/questions/25079470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable space character virtual keyboard iOS I want to disable the space character from the virtual keyboard on my iOS application when users edit an input text. Users should enter a nickname. So I want to remove all space characters. Thanks. A: Trying to modify the standard keyboard requires taking a dangerous path into private APIs and a broken app in future iOS versions. I think the best solution for you would be to implement the textField:shouldChangeCharactersInRange:replacementString: method of UITextFieldDelegate and replace whitespace characters with the empty string. Once this is implemented, hitting the space bar will simply do nothing.
{ "language": "en", "url": "https://stackoverflow.com/questions/10977710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using writeOGR with rpy2 I am trying to use writeOGR using R called from Python 3.8. import rpy2.robjects as ro ..... ro.r('ttops <- .....') ro.r('writeOGR(obj=ttops, dsn="T:/Internal/segmentation", layer="test", driver="ESRI Shapefile")') errors with: R[write to console]: Error in writeOGR(obj = ttops, dsn = "T:/Internal/LiDAR/crown_segmentation", : could not find function "writeOGR" Traceback (most recent call last): File "C:/Users/david/PycharmProjects/main.py", line 7, in <module> main() File "C:/Users/david/PycharmProjects/main.py", line 4, in main R_Packages().process() File "C:\Users\david\PycharmProjects\model_testing\r_methods.py", line 17, in process ro.r('writeOGR(obj=ttops, dsn="T:/Internal/segmentation", layer="test", driver="ESRI Shapefile")') File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\rpy2\robjects\__init__.py", line 416, in __call__ res = self.eval(p) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\rpy2\robjects\functions.py", line 197, in __call__ return (super(SignatureTranslatedFunction, self) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\rpy2\robjects\functions.py", line 125, in __call__ res = super(Function, self).__call__(*new_args, **new_kwargs) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\rpy2\rinterface_lib\conversion.py", line 44, in _ cdata = function(*args, **kwargs) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\rpy2\rinterface.py", line 624, in __call__ raise embedded.RRuntimeError(_rinterface._geterrmessage()) rpy2.rinterface_lib.embedded.RRuntimeError: Error in writeOGR(obj = ttops, dsn = "T:/Internal/segmentation", : could not find function "writeOGR" Am I missing something or is this a limit of rpy2? If it is a limit, what is an alternative to write shapefiles of R data using Python? A: There was a library that I did not need to define in R that was needed in Python: ro.r('library(rgdal)')
{ "language": "en", "url": "https://stackoverflow.com/questions/63001868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does readdirSync() say no such file or directory? index.js const fs = require('fs'); const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); filesystem: src -commands -stuff.js -config.json -index.js Error: Error: ENOENT: no such file or directory, scandir './commands/' at Object.readdirSync (fs.js:783:3) The folder is there, and has files in it. I tried './commands/' , './commands' , 'commands' , nothing seems to work. A: Try processing path with path module, as below const path = require('path'); const dirPath = path.resolve(__dirname, './commands'); And then pass dirPath to readdirSyncfunction. path is an internal node.js module, so you don't need to install anything A: You are on Windows. The path delimeter for Windows is \, not /. Try making your program platform agnostic with something like this: const fs = require('fs'); const path = require("path"); const commandDir = path.join(__dirname, "commands"); const commandFiles = fs.readdirSync(commandDir).filter(file => file.endsWith('.js')); console.log(commandFiles); A: With RegEx const fs = require('fs'); let searchPath = "./mydirectory"; let searchFileName = ".*myfile.*"; let searchFoundFiles = fs .readdirSync(searchPath) .filter((f) => new RegExp(searchFileName).test(f)); if (searchFoundFiles.length) { console.log("File already exists"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/59256354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I use a bitmask? How do I use it in C++? When is it useful to use? What would be an example of a problem where a bitmask is used to see how it actually works? A: Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45 unsigned long alpha = 0x45 unsigned long pixel = 0x12345678; pixel = ((pixel & 0x00FFFFFF) | (alpha << 24)); The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel. A: Bitmasks are used when you want to encode multiple layers of information in a single number. So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit. rwx --- 110 110 in base 2 translates to 6 in base 10. So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission. Pseudocode: PERM_READ = 4 PERM_WRITE = 2 PERM_EXEC = 1 user_permissions = 6 if ((user_permissions & PERM_READ) == PERM_READ) then // this will be reached, as 6 & 4 is true fi You need a working understanding of binary representation of numbers and logical operators to understand bit fields. A: Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value. An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this: RRRR RGGG GGGB BBBB You could then use bit masking to retrieve the colour components as follows: const unsigned short redMask = 0xF800; const unsigned short greenMask = 0x07E0; const unsigned short blueMask = 0x001F; unsigned short lightGray = 0x7BEF; unsigned short redComponent = (lightGray & redMask) >> 11; unsigned short greenComponent = (lightGray & greenMask) >> 5; unsigned short blueComponent = (lightGray & blueMask); A: Briefly, a bitmask helps to manipulate the position of multiple values. There is a good example here; Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it: #define LOG_ERRORS 1 // 2^0, bit 0 #define LOG_WARNINGS 2 // 2^1, bit 1 #define LOG_NOTICES 4 // 2^2, bit 2 #define LOG_INCOMING 8 // 2^3, bit 3 #define LOG_OUTGOING 16 // 2^4, bit 4 #define LOG_LOOPBACK 32 // and so on... // Only 6 flags/bits used, so a char is fine unsigned char flags; // Initialising the flags, // Note that assigning a value will clobber any other flags, so you // it should generally only use the = operator when initialising variables. flags = LOG_ERRORS; // Sets to 1 i.e. bit 0 // Initialising to multiple values with OR (|) flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING; // sets to 1 + 2 + 8 i.e. bits 0, 1 and 3 // Setting one flag on, leaving the rest untouched // OR bitmask with the current value flags |= LOG_INCOMING; // Testing for a flag // AND with the bitmask before testing with == if ((flags & LOG_WARNINGS) == LOG_WARNINGS) ... // Testing for multiple flags // As above, OR the bitmasks if ((flags & (LOG_INCOMING | LOG_OUTGOING)) == (LOG_INCOMING | LOG_OUTGOING)) ... // Removing a flag, leaving the rest untouched // AND with the inverse (NOT) of the bitmask flags &= ~LOG_OUTGOING; // Toggling a flag, leaving the rest untouched flags ^= LOG_LOOPBACK; ** WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == : ** if (flags == LOG_WARNINGS) //DON'T DO THIS ... if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way ... if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set == (LOG_INCOMING | LOG_OUTGOING)) ... You can also search C++ Tricks.
{ "language": "en", "url": "https://stackoverflow.com/questions/18591924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "77" }
Q: Xamarin.Forms custom loading gif as activity indicator I would just like to know of something is possible as I am very new to Xamarin and I am on a time limit for an assignment. I don't mind some trial and error, but don't want to waste the time if it isn't possible I want to have an animated gif as an activity indicator (it is a logo). I have it working in a WebView - is it possible, in Xamarin,Forms to have this appear as an overlay while waiting on long running methods? For example. if user clicks on a button, the app gets some info from a webservice then displays in a page. While waiting I would like to show the webview (or any other way to show an animagted gif). So I am not asking for the code, but just if it is posible. Thanks in advance A: I was able to work this out With the animated(loading) gif running in the WebView page I called a couple of async methods using following await Task.WhenAll(method1(), method2()); await Navigate.PushAsync(new NextPage(var1, var2)); The laoding gif (which is an animated logo) runs until the tasks are complete then navigates to the next page A: Using an ImageView apparently this doesn't look like its possible to playback animated Gif's as can be seen here http://forums.xamarin.com/discussion/17448/animated-gif-in-image-view. So i very much doubt the ActivityIndicator would, if it could. In the ActivityIndicator I can't see any functionality to change the content of the what is shown when it is busy. You could always create your own animated image view by creating a custom renderer instead however. It isn't particularly hard to cycle images at pre-determined gaps if you have a list of the images split up. A: GIF images can be used in Xamarin forms to show custom activity indicator, since in Xamarin forms it is not possible to show GIF images directly web-view must be used. For android image must be placed inside assets folder and Build Action must be set to AndroidAsset. For iOS image must be placed inside resources and Build Action must be set to BundleResource. AbsoluteLayout can used for placing the image to center, IsBusy property of mvvm helpers nuget can used for controlling the visibility of the activity indicator. Dependency service must used for getting the image path. You can check this https://github.com/LeslieCorrea/Xamarin-Forms-Custom-Activity-Indicator for example. A: Xamarin.Forms now supports .GIF, from version 4.4-pre3 and up on iOS, Android and UWP. Before using, first add the .GIF to the platforms projects, or as an embedded resource in the shared project and then use it like a regular image. The API on the Image control has been extended with the IsAnimationPlaying bindable property. For e.g., loader.gif is added in all platform projects, then below code make it animating. <Image Source="loader" IsAnimationPlaying="True" WidthRequest="36" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" />
{ "language": "en", "url": "https://stackoverflow.com/questions/25808010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rotativa PDF converter not rendering Flexbox correctly Using ASP.NET MVC in .NET Framework 4.8 I've been trying to render a View into a PDF. Found the Rotativa package that can do it. I've found out that it is pretty similar to wkhtmltopdf. In this case, when writing CSS Flexbox, there's certain differences. Using this site as a reference, I've been learning about the old flexbox layout (that wkhtmltopdf uses and I saw on this thread). I've done this razor page named Teste.cshtml <!DOCTYPE html> <html> <head> <title>Flexbox test</title> </head> <body> <div class="container"> <nav> Início Taco Menu Rascunhos Horas Direções Contato </nav> <div class="flex-column"> <section>Flexbox é tão fácil!</section> <section>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.</section> </div> </div> </body> </html> And this css named Teste.css: body { } .container { display: -webkit-flex; display: flex; border: 2px solid pink; } nav { width: 200px; border: 2px solid blue; } .flex-column { -webkit-flex: 1; flex: 1; } div > section { border: 2px solid yellow; } The result is correct. But when creating a PDF, it makes this. The flexbox layout isn't the same. This is my main controller: public ActionResult Index() { return new ActionAsPdf("Teste") { FileName = "teste.pdf" }; } public ViewResult Teste() { return View(); } Does Rotativa not support this flexbox code? Is there any other way to do it? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/75597028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: move values in stack to a vector in c++ I am trying to move the elements that are in the stack into a vector. I have tried the following: for(int i=0; i<vector1.size();i++) { vector1[i]=stack1.pop(); } But it keeps giving me error. A: std::stack::pop doesn't return a value You need to use std::stack::top, to get top element and then remove it from the stack like following : vector1[i]=stack1.top(); stack1.pop(); A: std::stack<T>::pop() doesn't return a value (it's a void function). You need to get the top, then pop, i.e. for(int i=0; i<vector1.size();i++) { vector1[i]=stack1.top(); stack1.pop(); } A: That's because the pop() function does not return a value. You need to use top() which returns the element at the top of the stack and then pop() to eliminate that element... for (int i = 0; i<vector1.size(); i++) { vector1[i] = stack1.top(); stack1.pop(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/28078045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Index was outside the bounds of the array about bitmap I have code which convert byte array to bitmap.. (In my Project I cannot use MemoryStream or others bitmap converter.) Here is my code. public static Bitmap ConvertBitMap(int width, int height, byte[] imageData) { var data = new byte[width * height * 4]; int o = 0; for (var i = 0; i < width * height ; i++) { var value = imageData[i]; data[o++] = value; data[o++] = value; data[o++] = value; data[o++] = 0; } ... ... .. .. } When I run application i says "System.IndexOutOfRangeException: Index was outside the bounds of the array." Here is arrayData information : data ------> {byte[614400]} imageData ---> {byte[105212]} Could you please anyone help me about fixing this issue ? How can i handle this outside bounds problem ? A: I'm not sure why this is happening, but the issue is that imageData size is not equal to width*height This code should fix it (though it might not be what you're looking for it to do) public static Bitmap ConvertBitMap(int width, int height, byte[] imageData) { var data = new byte[imageData.Length * 4]; int o = 0; for (var i = 0; i < imageData.Length ; i++) { var value = imageData[i]; data[o++] = value; data[o++] = value; data[o++] = value; data[o++] = 0; } ... ... .. .. } A: The problem here is that the length of imageData is less than height * width. Hence you eventually get an exception on this line because i is greater than imageData.Length var value = imageData[i]; Consider the sizes that you posted in the question * *data : 614400 *imageData : 105212 The size of data was calculated as height * width * 4 hence we can calculate height * width by dividing by 4 and we end up with height * width == 153600. This is clearly larger than 105212 and hence you end up accessing outside the bounds of the array
{ "language": "en", "url": "https://stackoverflow.com/questions/21861557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create button which change string value every time clicked I want to create a button which will change the string value every time I click in C#. Here is my C# code: partial class Translator2 : Page { public string from = "en"; // initial value public string to = "ja"; // initial value public async void Submit(object sender, EventArgs e) { string from1 = from; string to1 = to; string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + from1 + "&to=" + to1; public void Switch(object sender, EventArgs e) { if (from == "en" & to== "ja") { from = "ja"; to = "en"; } else if(from == "ja"& to =="en") { from = "en"; to = "ja"; } } If I click the switch button, the string value changed from ja and to en. However, if I click again, nothing changed. What is wrong with my code? A: I suggest using an enum for clarity. public enum Language { En_Ja, Ja_En } Language lang = Language.En_Ja; public void Switch(object sender, EventArgs e) { lang = lang == Language.En_Ja ? Language.Ja_En : Language.En_Ja; } A: Short Answer: The from and to fields need to be initialized by the HTTP request. Something like: partial class Translator : Page { string from, to; protected override void OnLoad(EventArgs e) { var to = Context.Request.QueryString["to"]; var from = Context.Request.QueryString["from"]; switch(from.ToUpper()) { case "EN": { this.from = "en"; break; } case "JA": { this.from = "ja"; break; } } switch(to.ToUpper()) { case "EN": { this.to = "en"; break; } case "JA": { this.to = "ja"; break; } } if(to == null) throw new Exception(); if(from == null) throw new Exception(); } } Longer Answer: This is actually a good use case for polymorphism: /* C# 7 syntax */ abstract class LanguageSetting { public static LanguageSetting English = JA.alt; public static LanguageSetting Japanese = EN.alt; public abstract LanguageSetting Alternate { get; } public abstract override string ToString(); sealed class EN : LanguageSetting { public static readonly LanguageSetting alt = new JA(); public override LanguageSetting Alternate => alt; public override string ToString() => "en"; } sealed class JA : LanguageSetting { public static readonly LanguageSetting alt = new EN(); public override LanguageSetting Alternate => alt; public override string ToString() => "js"; } } Then your Submit() and Switch methods are simply: void Submit(object Sender, EventArgs e) { string from = lang.ToString(); string to = lang.Alternate.ToString(); string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + from1 + "&to=" + to1; } and void Switch(object Sender, EventArgs e) { lang = lang.Alternate; } Finally, we initialize with something like: protected override void OnLoad(EventArgs e) { var from = Context.Request.QueryString["from"]; switch(from.ToUpper()) { case "EN": { lang = LanguageSetting.English; break; } case "JA": { lang = LanguageSetting.Japanese; break; } } if(lang == null) throw new Exception(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/45652284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to identify if certain keys are present in dictonary? I have dictonary named as Entity which look like this: Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'} Now I have to create other dictionary which will contain below value according to condition. Class = {'Signal':'<Condition>'} The condition is: * *If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated. *If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated. *If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated. How should I make the condition for the above problem? I want an output in Class dictionary like below, If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like, Class = {'Signal' : 'Medium'} A: To check if dictionary contains specific key use: 'ORG' in Entity statement which returns True if given key is present in the dictionary and False otherwise. A: You can use the .keys() function on the dictionary to check before accessing the data structure. For example: def does_key_exist(elem, dict): return elem in dict.keys() A: if all([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]): Class['Signal'] = 'strong' elif all([a in Entity for a in ('ORG', 'PERSON')]): Class['Signal'] = 'middle' elif not any([a in Entity for a in ('ORG', 'PERSON', 'MONEY')]): Class['Signal'] = 'weak' Note that, according to your question, if Entity contains only 'ORG' or only 'PERSON', no 'Signal' will be set in Class.
{ "language": "en", "url": "https://stackoverflow.com/questions/56343125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tensorflow - Read different block_lengths from multiple tfrecords with parallel_interleave? I am trying to read three different large tfrecords of different lengths, and read them all in parallel like this: files = [ filename1, filename2, filename3 ] data = tf.data.TFRecordDataset(files) data = data.apply( tf.contrib.data.parallel_interleave( lambda filename: tf.data.TFRecordDataset(data), cycle_length=3,block_length = [10,5,3])) data = data.shuffle( buffer_size = 100) data = data.apply( tf.contrib.data.map_and_batch( map_func=parse, batch_size=100)) data = data.prefetch(10) ,but TensorFlow does not allow for different block lengths per file source: InvalidArgumentError: block_length must be a scalar I could create three different datasets with different mini-batch size, but that requires 3x the resources, and that's not an option given by my machine limitations. What are the possible solutions? A: Here is the answer, I figured out how to do it within my constraints. Make datasets for each file, define each mini batch size for each, and concatenate the get_next() outputs together. This fits on my machine and runs efficiently.
{ "language": "en", "url": "https://stackoverflow.com/questions/50881103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 302 redirect while downloading Jfrog PHP private artifact Downloading (connecting...) Downloading (connecting...) Update failed (The \ "https://abc.jfrog.io/artifactory/api/composer/php-local/direct-dists/@abc/framework/abc_code.zip" \ file could not be downloaded, got redirect without Location (HTTP/1.1 302 Found)) Would you like to try reinstalling the package instead [yes]? This was working earlier suddenly stopped. In browser also working fine. Only while doing composer update or composer install * *Composer version: 1.5.6 *VagrantBox: 7.0 *PHP: 5.5 *Host OS: MacOS *Vagrant : 2.3 *VirtualBox : 7.2 *Scientific Linux release 6.5 ( CentOS ) A: This got solved by upgrading Composer version to 2. Jfrog throwing error when there is composer version 1.x while pulling Artifact. Sometime an OS doesn't easily upgrade to Composer 2 due to missing CA certificates. Can follow below steps: * *cd /etc/pki/tls/certs *check ca-bundle.crt file is there or not: file /etc/pki/tls/certs/ca-bundle.crt *sudo curl https://curl.se/ca/cacert.pem -o /etc/pki/tls/certs/ca-bundle.crt -k run this command to download the CA certificates extracted from Mozilla. *upgrade composer using following this page https://getcomposer.org/download/ : php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');" (always take the latest version from the download page as it changes from time to time)
{ "language": "en", "url": "https://stackoverflow.com/questions/74716933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add nuget package into project file without Visual Studio I am looking for solution to add/update new nuget packages to exiting project file .csproj but without Visual Studio. I gone this post here it download package it on local machine. But we want same process that Visual Studio do * *Download dll *Add reference in project file *update package.config file Is it possible that I can achieve this outside Visual Studio? A: This should be possible using Nuget.exe and the install-package etc. Powershell cmdlets. See the blog post Installing NuGet Packages outside of Visual Studio for details!
{ "language": "en", "url": "https://stackoverflow.com/questions/34654389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook graph api posting gifs as static images to pages posts I'm trying to post gif to facebook page but when it's posted as photo, gif image does not move, it posts as static jpg file. What I've already tried: The result is static image: I've tried to post gif as video: The result is better, but still it's not attached as gif What I'm trying to achieve is to post gif as gif, like you attach gif when do post manually. My expected result is like this: Is it possible to post gif like in last example using graph api? Will really appreciate any help, thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/49862861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Importing class-type global variables I'm trying to implement a configuration system contained within a module. The core configuration variable is a class instance and a global variable in this module. It seems that when I import this variable, I cannot use it as a class for some reason. Consider this minimal example: foomodule.py: class FooClass: number = 5 def bar (self): return self.number foo = FooClass foo.number = 5 main.py from foomodule import foo print foo.bar() Running main.py results in a cryptic error message: Traceback (most recent call last): File "main.py", line 2, in <module> print foo.bar() TypeError: unbound method bar() must be called with FooClass instance as first argument (got nothing instead) But I am calling it with a FooClass instance which I'd think should be the self argument like it usually is. What am I doing wrong here? A: You only bound foo to the class; you didn't make it an instance: foo = FooClass # only creates an additional reference Call the class: foo = FooClass() # creates an instance of FooClass In Python you usually don't use accessor methods; just reference foo.number in your main module, rather than use foo.bar() to obtain it. A: In your example foo is just an alias for FooClass. I assume that your actual problem is more complicated than your snippet. However, if you really need a class method, you can annotate it with @classmethod decorator. class FooClass(object): number = 5 @classmethod def bar(cls): return cls.number To use your the class you could do: from foomodule import Foo Foo.bar() Or you can access the class member directly Foo.number
{ "language": "en", "url": "https://stackoverflow.com/questions/26830381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google App Invites: iOS App and Android app with different package names/bundle IDs - how can they be linked with goo.gl/App Invites? I an app for both iOS and Android that I need to link via App Invites - but they have different package names/bundle IDs that represent the same service - how do I link them with goo.gl / the app-invite system? The android package name differs from the iOS bundle ID because the Android key was lost by the previous developer, unfortunately. Thanks! A: You can send invites between android and iOS. They are linked using the developer console (console.developers.google.com). Both the android app and the iOS app need to be in the same console project. If there is only one of each, then when sending across platforms it's unambiguous which to choose and you can just send an invite. The app invite service will send the proper short links(goo.gl/...) to install/launch the proper app per platform. If there are multiple instances of a iOS and/or Android apps in the console project, then the client ID must be sent with the invite using Api call setOtherPlatformsTargetApplication(...) so that app invite service knows which of the console apps should be selected. For same platform, i.e. android to android, the app selected will match the app that sent the invitation, so same platform is not ambiguous.
{ "language": "en", "url": "https://stackoverflow.com/questions/31319819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to error Cannot bind to the new display member. Parameter name: newDisplayMember This is my code and when called this function return error: Cannot bind to the new display member.Parameter name: newDisplayMember Code: public void FillDrpKala() { string SQL = "SELECT [kID],[kName] FROM tblKala ORDER BY kName"; DataSet ds = new DataSet(); using (SqlConnection cn = new SqlConnection(objCon.StrCon)) { using (SqlDataAdapter adapter = new SqlDataAdapter(SQL, cn)) { cn.Open(); try { adapter.Fill(ds); } catch (SqlException e) { MessageBox.Show("There was an error accessing your data of Kala. DETAIL: " + e.ToString()); } } } cmbKala.DataSource = ds.Tables[0]; cmbKala.DisplayMember = "mName"; cmbKala.ValueMember = "mID"; } A: Your column names are mixed up. Instead of cmbKala.DisplayMember = "mName"; cmbKala.ValueMember = "mID"; Try this: cmbKala.DisplayMember = "kName"; cmbKala.ValueMember = "kID";
{ "language": "en", "url": "https://stackoverflow.com/questions/23759163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split-path powershell This must be very simple but yea I want to split-path "E:\Somefolder\ps\pow.ps1" So by using Split-path "Path" -Parent I get the parent path i.e."E:\Somefolder\ps" but I only want "E:\Somefolder" Any suggestions? A: well! well! I was able to do it using following line: Split-Path (Split-path $MyInvocation.InvocationName -Parent)
{ "language": "en", "url": "https://stackoverflow.com/questions/41627621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Kinect.Toolbox custom TemplatedGestureDetector initialisation I'm working on an application to control various systems using a Kinect, and I'm having trouble setting up custom gestures. I'm using the Kinect Toolbox library, and I've run into a chicken-and-egg problem with the TemplatedGestureDetector. What I want to do is simple enough: * *Get the name of the new gesture from the user *Record the user making the new gesture *Create a TemplatedGestureDetector from the recorded gesture *Register a handler for the OnGestureDetected event It's proving less straightforward than it look, though. My main problem is that the constructor for TemplatedGestureDetector needs a stream to a file containing (as far as I can make out) a serialised path... but I can't see any way of creating such a file, and if I create a new (empty) file and give it a stream to that, then I get an error when it tries to deserialise a path out of it. To get around this, I've added a separate constructor which takes a List<RecordedPath>, which is what the stream was being deserialised to anyway, and then recorded my own paths to pass to that. This runs without error, but doesn't seem to ever trigger the detection event, making me think that perhaps I've missed something. Could anyone walk me through the process? I haven't been able to find any useful documentation anywhere; the Kinect Toolbox library is a nice piece of work but the developers' decision to leave the Codeplex documentation page blank is very disappointing.
{ "language": "en", "url": "https://stackoverflow.com/questions/22744944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel table object: How to increment numbers when value changes in another column? I have a range of cells in Table format in excel. How to increment numbers in a table column when value changes in each group with a formula? I tried using the formula B2=COUNTIF($A$2:A2,A2) which creates a number sequence that restarts for every change in another column. This works well for tables with fixed number of rows. The problem arrives when adding new rows to the table since the range shifts to adjust to the table range. Example for row 2: FROM COUNTIF($B$2:B2;B2) to COUNTIF($B$2:B3;B2) instead of keeping COUNTIF($B$2:B2;B2) unchanged. How to avoid such behaviour when adding new rows? Desired result: A: Since it's a table, I'd suggest structured references like: =COUNTIF(Table1[[#Headers],[Product]]:[@Product],[@Product]) A: I don't get the same results as you do -- when I insert a row, the criteria cell changes. In any event, since this is a Table, you can use structured references: B2: =COUNTIF(INDEX([Product],1):@[Product],@[Product]) A: David, if your cells are not formatted as an Excel Table, this formula can do the job: =COUNTIF(INDIRECT("A1:A" & COUNTA(A:A)),A1)-COUNTIF(INDIRECT("A"&ROW() & ":A" & COUNTA(A:A)),A1)+1
{ "language": "en", "url": "https://stackoverflow.com/questions/70800670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JPA insert rows in multiple transaction, limit the maximum row numbers in a single transaction I would like to insert every 1000 row in a separate transaction. So if there are 3000 row than it should insert it in 3 different transaction. I don't use Spring. import com.company.UserDAO; import javax.inject.Inject; import javax.transaction.Transactional; public class Round{ UserDAO userDao; @Inject public Round(UserDAO userDao){ this.userDao = userDao; } @Transactional @Scheduled(every = "10s") void schedule() { Synchronization synchronization = new Synchronization(); synchronization.setUserDAO( userDao ); synchronization.synchronize(); } } public class Synchronization{ UserDAO userDao; public void synchronize(){ List<User> newUsers = Arrays.asList( new User(a1), new User(a2), ..., new User(a170.000); for( User user : newUsers){ saveCreate( user ) } } saveCreate(User user){ userDao.create(user); // which is calling somewhere the: getEntityManager().persist(entity); } } How can I create new transaction for every 1000 row? 1, Flush and clear the entityManager at every 1000 row. Will it create a new transaction? int i = 0; for( User user : newUsers){ saveCreate( user ) i++; if( i % 1000 == 0 ){ userDao.getEntityManager.flush(); userDao.getEntityManager.clear(); } } 2, Make the saveCreate method @Transactional , instead of the schedule() ? 3, create new class, with new method which is annotated with @Transactional, and create new intance from it, when there are more than 1000 row ? Transaction tr = new Transaction; int i = 0; for( User user : newUsers){ i++; tr.singleTransaction( user ); if( i % 1000 == 0 ){ tr = = new Transaction; } } public class Transaction{ @Transactional public void singleTransaction( User user){ saveCreate( user ); } } 4, something else ? Thank you in advance! A: Write a method which will insert 1000 records and mark it as @Transactional(propagation = Propagation.REQUIRES_NEW) @Transactional(propagation = Propagation.REQUIRES_NEW) public void saveData(List<Object> data).. Then, call that method few times, whenever the method is called, new transaction will be created.
{ "language": "en", "url": "https://stackoverflow.com/questions/62246986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to auto insert data into database using the values from another table? I have 2 tables. this is the incomes table income_id date_income total_amount 1 2022-05-22 14 2 2022-05-22 15 3 2022-05-21 20 4 2022-05-21 25 and this is the total_income table total_inc_id income_id date_income total total_income_amount 1 1 2022-05-22 2 29 However I want to count rows with the same date from table1 and store inside table 2 like above automatically whenever i add income. How can i achieve this?
{ "language": "en", "url": "https://stackoverflow.com/questions/72360019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why push notification directed to specific iOS device from Web API through Firebase FCM does not arrive? I'm working with a remote web API developer, currently we're working to send push message from the server to iOS and Android device. We send our device token via OAuth API. (For iOS, device token is gotten from registering remote service with APNS service at AppDelegate launch). The weird thing is, Android can get the push notification, but iOS devices don't. But when I tried using the Firebase console -> grow -> notification -> New Message -> and target all the iOS device, all the iOS device registered to the push notification receive the push notification. Can you help me point out where the problem is? The web server is using nodeJs. Things I have done, which I did according to this tutorial: * *create new apps in Firebase project. *supply the same product bundle id to the app. *import google plist to the Xcode project. *supply development and production certificate .p12 to the app. *install Firebase/Core and Firebase/Messaging through Cocoapods. *use this code to register for remote notification (have tried both in target deployment iOS version 9.0 and 10.0, both yields the same result): func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) // For iOS 10 data message (sent via FCM Messaging.messaging().delegate = self } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() FirebaseApp.configure() return true } From all this preparation, if I run the app in real iOS device, and then lock it, any message I broadcast to iOS device in the Firebase iOS app will shown in the lock screen notification. But not message from the web API that's directed toward the account logged in the app (which is directed to all the android and iOS device that logged in using that account -- it's shown on the android devices, but not on iOS devices). I'm new to FCM. I usually use APNS. I probably don't know much about the terms to fix the server side as I don't understand nodeJs much, so if you have some suggestion about the server side, please be elaborate, so I can discuss it with the web API dev. Thanks for your help. A: Turns out what I need to send to the server is not APNS token, but Firebase token, found in here: https://firebase.google.com/docs/cloud-messaging/ios/client#monitor-token-generation
{ "language": "en", "url": "https://stackoverflow.com/questions/48198866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dependency injection of EF context in WebJobApp I'm trying to create my first webjobapp that requires the use of Entity Framework. I am trying to inject my context into the builder of the app, but I'm getting an error: Cannot bind parameter 'db' to type ApplicationDbContext. Make sure the parameter Type is supported by the binding There are several examples on the web but the versions of the Azure WebJob appear to have changed quickly and I can't find one that works for the version I'm using. These are the package versions I'm using: Webjobs 3.0 EF.NET Core 7.0 Targeting .NET 7.0 Here is my code: class Program { static async Task Main() { var builder = new HostBuilder(); builder.ConfigureWebJobs(b => { b.AddTimers(); b.AddAzureStorageCoreServices(); }); builder.ConfigureLogging((context, b) => { b.AddConsole(); }); builder.ConfigureAppConfiguration((hostContext, configApp) => { configApp.SetBasePath(Directory.GetCurrentDirectory()); configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_"); configApp.AddJsonFile($"appsettings.json", true); configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true); }); builder.ConfigureServices(services => { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("My full connection string")); services.AddTransient<IEmailSender, EmailSender>(); }); var host = builder.Build(); using (host) //{ await host.RunAsync(); } } } public class Functions public static void Sendemails([TimerTrigger("0 0 20 * * SUN-THU")] TimerInfo timer, ILogger logger, ApplicationDbContext db) { var mylist = db.Users.ToList(); } } I tried to configure the services using the following code instead of the above code. When inspecting the builder I can see that the services were added to the builder. But inspecting the host after the call to builder.Build(), The services do not show up in the host container. var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); ..... builder.ConfigureServices((context, sc) => sc= serviceCollection); var host = builder.Build(); using (host) { await host.RunAsync(); } } ..... private void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"))) } Project File <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <None Remove="appsettings.Development.json" /> <None Remove="appsettings.json" /> </ItemGroup> <ItemGroup> <Content Include="appsettings.Development.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <ExcludeFromSingleFile>true</ExcludeFromSingleFile> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> <Content Include="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <ExcludeFromSingleFile>true</ExcludeFromSingleFile> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.1" /> <PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.33" /> <PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" /> <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.OpenApi.Configuration.AppSettings" Version="1.5.0" /> <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SendGrid" Version="3.0.2" /> <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.1" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> <PackageReference Include="SendGrid" Version="9.28.1" /> </ItemGroup> </Project> A: Initially Even I got the same error. Done few changes in Program.cs . My Program.cs: using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; class Program { static async Task Main() { var builder = new HostBuilder() .ConfigureWebJobs(b => { b.AddTimers(); b.AddAzureStorageCoreServices(); }) .ConfigureLogging((context, b) => { b.AddConsole(); }) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.SetBasePath(Directory.GetCurrentDirectory()); configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_"); configApp.AddJsonFile($"appsettings.json", true); configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true); }) .ConfigureServices(services => { services.AddDbContext<ApplicationDbContext>( options => options.UseSqlServer("MyDefaultConnection")); services.AddTransient<ApplicationDbContext, ApplicationDbContext>(); }); var host = builder.Build(); using (host) { await host.RunAsync(); } } } If you are running locally, cross check the local.settings.json file once. My local.settings.json : { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet" } } My appsettings.json: { "ConnectionStrings": { "AzureWebJobsStorage": "Storage Account Connection String" } } Also have a look at SO Thread once. References taken from MSDoc. A: I do the steps from the beginning. 1- public class ApplicationDbContext: IdentityDbContext<User, Role, Guid> { public ApplicationDbContext(DbContextOptions options) : base(options) { } } 2-add in appsettings.json "ConnectionStrings": { "SqlServer": "Data Source=;Initial Catalog=SpaceManagment;User ID=sa;Password=654321;MultipleActiveResultSets=true;TrustServerCertificate=True;Connection Timeout = 60" }, 3- add in program.cs builder.Services.AddDbContext<ApplicationDbContext>(options => { options .UseSqlServer(settings.SqlServer); //Tips // .ConfigureWarnings(warning => warning.Throw(RelationalEventId.QueryClientEvaluationWarning)); });
{ "language": "en", "url": "https://stackoverflow.com/questions/75093005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to fix 'SnowballStemmer' object has no attribute 'StemWords? This is the code: import nltk from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer(language='english') stem = [] lines2 = ["test"] for words in lines2: stem.append(stemmer.stem(words)) print(stem) The error: line 82, in <module> stem.append(stemmer.StemWords(words)) AttributeError: 'SnowballStemmer' object has no attribute 'StemWords' I am very glad for any kind of help to solve this problem. Thank you in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/70381229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gitlab: Can't clone repo over SSH I've installed Gitlab version 5.1 on my server (Centos 6.4 64bit). After a lot of hiccups, I now can clone, pull and push... but only over HTTP. Anytime I try an SSH clone, this error occurs: $ git clone git@git.server:my-project.git Cloning into 'my-project'... FATAL: R any my-project my-user DENIED by fallthru (or you mis-spelled the reponame) fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. This DENIED by fallthru error apparently is no stranger to Google and Stackoverflow, but most of them is Gitolite-related, which is not the case here, as Gitlab has dropped Gitolite as per v5. So what am I missing here? This is my first time working with Gitlab, so please be gentle. A: OK, after upgrading to 5.2 the problem's gone.
{ "language": "en", "url": "https://stackoverflow.com/questions/16517378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: gfortran is not working on Mac OS X 10.9 (Mavericks) Recently, I updated my OS X to 10.9 (Mavericks); unfortunately, gfortran stops working although I updated Xcode command line to 5.1.1 for OS X Mavericks. Similar question has been asked sometime ago, here, but I don't think so the issue is sorted out. here is what I did: first I removed the existing gfortran bash-3.2$ sudo rm -r /usr/local/gfortran /usr/local/bin/gfortran Then I downloaded gfortran-4.9-bin.tar, and unzip it and installed successfully bash-3.2$ gunzip gfortran-4.9-bin.tar bash-3.2$ sudo tar xvf gfortran-4.9-bin.tar -C / bash-3.2$ which gfortran /usr/local/bin/gfortran but when I start running my codes , I got the following errors, e.g. bash-3.2$ gfortran boolean1.f90 Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 collect2: error: ld returned 1 exit status I would be immensely grateful if anyone could guide me to solve this problem. A: Just for the record. I suggest to install gfortran from packages that are available from here: https://gcc.gnu.org/wiki/GFortran macOS installer can be found here: http://coudert.name/software/gfortran-6.3-Sierra.dmg Just install most recent release (using dmg file) and everything should be fine ! fort_sample.f90 program main write (*,*) 'Hello' stop end Compilation and execution goes smooth > gfortran -o fort_sample fort_sample.f90 > ./fort_sample Hello
{ "language": "en", "url": "https://stackoverflow.com/questions/23501128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Grunt error task "default" not found When trying to run grunt, I get an error message: Warning: Task "default" not found. Use --force to continue. Aborted due to warnings. I have already found several posts on this topic, and in each of them the problem was a missing comma. But in my case I have no idea what's wrong, I think I didn't miss any comma (btw, this content was copy/pasted from the internet). module.exports = (grunt) => { grunt.initConfig({ execute: { target: { src: ['server.js'] } }, watch: { scripts: { files: ['server.js'], tasks: ['execute'], }, } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-execute'); }; What could be the problem? A: You didn't registered the default task. Add this after the last loadNpmTask grunt.registerTask('default', ['execute']); The second parameter is what you want to be executed from the config, you can put there more tasks. Or you can run run existing task by providing the name as parameter in cli. grunt execute With you config you can use execute and watch. See https://gruntjs.com/api/grunt.task for more information. A: If you run grunt in your terminal it is going to search for a "default" task, so you have to register a task to be executed with Grunt defining it with the grunt.registerTask method, with a first parameter which is the name of your task, and a second parameter which is an array of subtasks that it will run. In your case, the code could be something like that: ... grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-execute'); grunt.registerTask("default", ["execute", "watch"]); ... In this way the "default" task will run rispectively the "execute" and the "watch" commands. However here you can find the documentation to create tasks with Grunt. Hope it was helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/49379258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenXML - continue writing to next worksheet (million row hit) According to Microsoft specifications .xlsx files have limit of 1,048,576 rows PER worksheet. In theory, as I see It, that means we could write file even with 2 million of rows - with two worksheets in same workbook. I'm using OpenXML package with SAX approach, which (imho) is still best for writing large Excel files. I also extended my solution to write .xlsx file directly from DataReader in order to avoid any Out Of memory exception, because our users usually export very large amount of data. That being said, I'm facing an issue when users want to export data larger than 1,048,576 rows - as .xlsx limit is (yes, they actually export that amount). Currently they can do It with 2 steps by creating separate .xlsx files, but I'm wondering If that could be done in a single file? For the code part: I've set a variable which checks row number (row_number) and if it hits 1 million then a new worksheet should be created, in order to continue writing data from same DataReader to the next sheet. However I'm facing issues when creating new sheet, as my data is being written by OpenXmlWriter, which already holds a Sheetpart instance for sheet1. As I see it, maybe this would work If I could pass a reference of sheet2 to OpenXmlWriter: int row_number = 0; using (var Excel_doc = SpreadsheetDocument.Create(file_path, SpreadsheetDocumentType.Workbook)) { var workbookPart = Excel_doc.AddWorkbookPart(); Excel_doc.WorkbookPart.Workbook = new Workbook { Sheets = new Sheets() }; var sheetPart = Excel_doc.WorkbookPart.AddNewPart<WorksheetPart>(); //Add sheet Sheets sheets = Excel_doc.WorkbookPart.Workbook.GetFirstChild<Sheets>(); string relationshipId = Excel_doc.WorkbookPart.GetIdOfPart(sheetPart); uint sheetId = 1; if (sheets.Elements<Sheet>().Count() > 0) { sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1; } Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = "Sheet " + sheetId }; sheets.Append(sheet); using (var XML_write = OpenXmlWriter.Create(sheetPart)) { XML_write.WriteStartElement(new Worksheet()); XML_write.WriteStartElement(new SheetData()); //Writing data using DataReader... using (OracleDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { XML_write.WriteStartElement(new Row()); for (int i = 0; i < reader.FieldCount; i++) { row_number++; } XML_write.WriteEndElement(); //End of row //If 1 million row exceeded then proceed writing to next sheet - here is where I'm stucked if (row_number>1000000) { sheetId +=1; Sheet sheet1 = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = "List " + sheetId }; sheets.Append(sheet1); XML_write.WriteEndElement(); XML_write.WriteEndElement(); XML_write.WriteStartElement(new Worksheet()); XML_write.WriteStartElement(new SheetData()); row_number=0; } } } XML_write.WriteEndElement(); XML_write.WriteEndElement(); XML_write.Close(); } } While writing .xlsx file this code terminates with an error: Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment I would be more than happy If anyone has a solution to this, or a suggestion to make It work. P.S.: Something similar already exists in some solutions - e.g. Toad for Oracle, which exports into .xls file on multiple sheets after hitting max 65k rows. So probably It can be done. A: Seems like you need to swap the order of the loops, basically. Open your connection, then create a sheet and use it until a counter hits 1 million, then close it and create another. Here's some basic pseudocode. count = 0 sheet = new writer = new writer(sheet) using (reader) { foreach (row in reader) { if (count % 1,000,000 == 0) { writer.close sheet = new writer = new writer(sheet) } writer.write(reader.read) count++ } } writer.close
{ "language": "en", "url": "https://stackoverflow.com/questions/57159067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: chrome not working with jquery remove Can anyone explain why this jsfiddle does not work in chrome, but works flawlessly in Firefox? here's the link: http://jsfiddle.net/Bu33n/ Here's the code just in case jsfiddle is inaccesible: <div class="container"> <div class="scheduleSet" id="remove19s"> <p>I am a schedule19</p> </div> <div class="scheduleSet" id="remove5s"> <p>I am a schedule5</p> </div> <div class="phoneSet" id="remove19p"> <p>I am a phone19</p> </div> <div class="phoneSet" id="remove5p"> <p>I am a phone5</p> </div> <a href="javascript:void(0);" onclick="Location.removeMe('remove19p');">Remove me</a> <a href="javascript:void(0);" onclick="Location.addMe();">Add me</a> </div> JS: Location.removeMe = function (data) { var stuff = ""; stuff = data; $('div').remove('#' + stuff); return false; }; Location.addMe = function () { $('.container').append("<div class='phoneSet' id='remove19p'>" + "<p>I am a replacement phone19</p>" + "</div>"); } A: You need to assign a new Object to Location for it to work in Chrome Location = new Object(); A: Rather than Google Chrome not working here, what's happening is that Firefox is overlooking your undefined Location namespace for some reason. Make sure you've defined it and your functions belong to it, or just use your functions this way (which seems more appropiate for your situation): function removeMe(data) { ... } function addMe() { ... } And in the onclick attributes of your links, onclick="removeMe('remove19p'); return false;" and onclick="addMe(); return false;" respectively. A: try this : function removeMe(data) { $('div').remove('#' + data); return false; }; function addMe() { $('.container').append("<div class='phoneSet' id='remove19p'>" + "<p>I am a replacement phone19</p>" + "</div>"); } AND HTML : <a href="javascript:void(0);" onclick="removeMe('remove19p');">Remove me</a> <a href="javascript:void(0);" onclick="addMe();">Add me</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/18026985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Height of the division in CSS3 I am trying out forms in HTML. Fiddle For the div #status, the CSS rules are- #status{ margin:auto; width:50%; border:2px solid red; background:white; height:40%; } But I cannot understand why the height of divison does not get altered by height rule in the CSS. More over If I try out- #status{ margin:auto; width:50%; border:2px solid red; background:white; height:40px; } JSFiddle This leaves the text on the bottom while div is placed at some random place. Could some help with placing this division below E-mail ID field so that text appears inside it? Also, which rule in my CSS is responsible for this positioning of div. A: You're inserting the div under elements that are floating. You need to add clear: both to your #status CSS rules: #status { margin: auto; width: 50%; border: 2px solid red; background: white; height: 40%; /* or 40px, which will look slightly different. Your choice. */ clear: both; } Updated Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/36239225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OSX: How to force multiple-file-copy operation to plough through errors This is so wrong. I want to perform a large copy operation; moving 250 GB from my laptop hard drive to an external drive. OSX lion claims this will take about five hours. After a couple of hours of chugging, it reports that one particular file could not be copied (for whatever reason; I cannot remember and I don't have the patience to repeat the experiment at the moment). And on that note it bails. I am frankly left aghast. That this problem persists in this day and age is to me scarcely believable. I remember hitting up against the same scenario 20 years back with Windows 3.1. How hard would it be for the folks at Apple (or Microsoft for that matter) to implement file copying in such a way that it skips over failures, writing a list of failed operations on-the-fly to stderr? And how much more useful would that implementation be? (both these questions are rhetorical by the way; simply an expression of my utter bewilderment; please don't answer them unless by means of comments or supplements to an answer to the actual question, which follows:). More to the point (and this is my actual question), how can I implement this myself in OS X? PS I'm open to all solutions here: programmatic / scripting / third-party software A: I hear and understand your rant, but this is bordering on being a SuperUser-type question and not a programming question (saved only by the fact you said you would like to implement this yourself). From the description, it sounds like the Finder bailed when it couldn't copy one particular file (my guess is that it was looking for admin and/or root permission for some priviledged folder). For massive copies like this, you can use the Terminal command line: e.g. cp or sudo cp with options like "-R" (which continues copying even if errors are detected -- unless you're using "legacy" mode) or "-n" (don't copy if the file already exists at the destination). You can see all the possible options by typing in "man cp" at the Terminal command line. If you really wanted to do this programatically, there are options in NSWorkspace (the performFileoperation:source:destination:files:tag: method (documentation linked for you, look at the NSWorkspaceCopyOperation constant). You can also do more low level stuff via "NSFileManager" and it's copyItemAtPath:toPath:error: method, but that's really getting to brute-force approaches there.
{ "language": "en", "url": "https://stackoverflow.com/questions/10325489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery .html( data here ) seems to "re-size" the response text Consider the following code. It's an anchor tag with an id called leader-module-total that - when pressed - calls a PHP script and displays the echos done in the PHP code inside an id called leader-module. Basic enough. However, each time I do this, I need to "shrink" it using the last piece of code in this snippet. My question is, how come? Am I doing something wrong here? $('#leader-module-total').click(function() { //load an image to show while processing $('#leader-module').html( '<div class="ajaxLoader"></div>' ); //process the php script -- btw, is this valid i.e. calling it using / //and not fully qualified with http://mydomain/page-to-be-called $.get('/ajax-leader-module-response.php', { timeframe: 'total' }, function(data){ $('#leader-module').html( data ); } ); //this is my question: why is this necessary??? //I need to make it smaller than it was for it to display normally. $('#leader-module').css('font-size', '0.9333em'); return false; }); A: I think it is inheriting styles from the parent tag. Please check the parent elements for any font size style.
{ "language": "en", "url": "https://stackoverflow.com/questions/1404676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TextField with Keyboard in cocos2d ! I am trying to develop a iphone app by using cocos2d. I create a alert view with a text field. when I touch the text field then comes the keyboard. But I want that when the alert is open, in the same time textfield will be selected and keyboard comes(without any touch). how can it posible ? sorry for my bad English. A: [myTextField becomeFirstResponder] will probably do what you want. A: That would be a little tricky to do. The controls in iPhone use the concept of "first responders" Any events will be handled by the first responder in the controller. Now, when an alert view is displayed, it becomes the first responder so it can respond to button clicks. When a text field is selected by the user, the keyboard gets the control. So I guess what you want to achieve can be done by making the text field the first responder after showing the alert ([txtField becomeFirstResponder]) But I have no idea how the alert view's responses will be handled then. You won't be able to click the OK button on the alert view till the keyboard is dismissed and you resign the first responder of the text field. ([txtField resignFirstResponder]) (This is just a guess, you will have to check the final behavior) A: [myTextField becomeFirstResponder] works -- I tested it.
{ "language": "en", "url": "https://stackoverflow.com/questions/483264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access: Dynamically set Query criteria to Is Null or Is Not Null First time posting a question, but I've been benifiting from some great advice here over the last few weeks while building my database, thanks all. In Access I have a "search" form with multiple combo-boxes that a query references to generate a report that meets the varius search criteria. I have hit one problem however. I want to be able to set the critera in one field of the query to Is Null or Is Not Null dependant on one of the comboboxes in my form. eg: Combo box has two options "Home" and "Away". If "Home" is selected I want this to insert Is Null into the query criteria, and Is Not Null if it's "Away". Currently I'm managing it in a rather clunky fashion with two separate queries, one for each option (but a separate button to launch the "search"). Solution would need to be Access 2007 compatible. I'm a relative beginner with VBA, learning by doing based on forum searches etc. Thanks in advance! A: Set your combo box to have two columns, hide the second column but bind to it. To do this, set the following properties: * *Column Count = 2 *Column Widths = 2cm; 0cm *Bound Column = 2 *Row Source Type = Value List *Row Source = Home; Is Null; Away; Is Not Null Now your combo box shows Home / Away to the user, but returns Is Null / Is Not Null to the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/26153699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cloud PaaS that supports socket programming What are the cloud PaaS that supports the opening of a socket? I browsed about various cloud services of which the GAE doesnot support socket. What are the other PaaS (both free and paid service)? Note: languages are java,.NET mainly and any other language A: Socket is now supported since 1.7.2 by signing up trusted tester
{ "language": "en", "url": "https://stackoverflow.com/questions/15360779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Prevent LongListMultiSelector from "auto scrolling" when inserting items at the beginning I am using a LongListMultiSelector to show messages. Newest messages are at the botton - like in a messenger. I know have a button in the ListHeaderTemplate, that allows me to load earlier messages and insert them at the top at the list (ObservableCollection.Insert(0, item);). Inserting works, but it looks like that the list scrolls automatically to the last inserted item - it actually does not scroll, but it feels like it scrolls, because after the insert, the new item is displayed, but i rather looking for a solution that keeps the item visible that was the first before the new items where inserted and that i have to do another vertical scroll to the new top to reach the list header again. Any clues? EDIT 1 consider, oldFirstItem is the current first item, then I insert a new item in front of the item. now the new item, becomes the first item, and since the scroll position does not change, the new item is visible: it feels like the list scrolls to the new inserted item, but it only pushed items 1 to n down. what i want is, that it pushes all new items up - into the area that the user does not see - and oldFirstItem at the top of the items that are visble. using ScrollTo makes that list jump. EDIT 2 I added a picture trying to show what I want to achieve. The area above the red line is not visible. A: If I see... you can use ScrollTo method. yourLongListMultiSelector.ScrollTo(yourNewInsertedItem); A: To get you going, I tried something but could not get it a 100% Here is a working basic page template which in fact does what you require with messages <phone:PhoneApplicationPage > <ScrollViewer x:Name="Scroll" VerticalAlignment="Bottom" Height="500" ScrollViewer.VerticalScrollBarVisibility="Disabled"> <StackPanel VerticalAlignment="Bottom" > <toolkit:LongListMultiSelector x:Name="DataList" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Disabled" VerticalAlignment="Bottom" VirtualizingStackPanel.VirtualizationMode="Recycling"></toolkit:LongListMultiSelector> </StackPanel> </ScrollViewer> </phone:PhoneApplicationPage> This keeps new messages down, pulling the list up. The scrolling is now disabled. You can easily enclose ScrollViewer in grid and add the button above (like in your picture) Now the code that would go into the button click Scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden; Scroll.ScrollToVerticalOffset(DataList.ActualHeight); Unfortunately this scrolls the list up BUT if you trigger the second line of code again for example via button click, ScrollToVerticalOffset works. So for some reason ScrollToVerticalOffset is not working right away-after changing VerticalScrollBarVisibility. If you can get this last part figured out, I believe your question would be solved A: The thing that prevents your desired effect is the ListHeader control is at top when you insert item at top. You can do some tricky code to bypass it: var temp = MyLongListMultiSelector.ListHeader; //also works with ListHeaderTemplate MyLongListMultiSelector.ListHeader = null; MyObservableCollection.Insert(0, item); MyLongListMultiSelector.ListHeader = temp; Or you can make a fake header item and handle the add top event like: MyLongListMultiSelector.Remove(fakeHeaderItem); MyObservableCollection.Insert(0, item); MyObservableCollection.Insert(0, fakeHeaderItem); A: you can easily achieve this via adding new items to top of the observable collection obsData.Insert(0,newItem) Reference
{ "language": "en", "url": "https://stackoverflow.com/questions/20074723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how do i fit background image to any screen? HTML <!doctype html> <html> <head> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <title>Coming Soon</title> <link href="css/Main.css" rel="stylesheet"> </head> <body> <section class="content"> <div style="width:500px; margin:0 auto; top:25%; position:relative"> <img src="img/logo.png"> <img src="img/line.png"> <p class="header large-2 white padding-top-triple">Coming This Fall 2015</p> <p class="white padding-top"><span class="header">Email: </span> <a href="mailto:Jethwa96@hotmail.co.uk"> <my-email data-user="Jethwa" data-domain="jedesigns.uk"></my-email> </a> </p> </div> </section> </body> </html> CSS /* Typography */ .header { font-family: "futura-pt", Arial, Helvetica, sans-serif; font-weight: 700; font-size: 1.0em; margin: 0; padding: 0; text-transform: uppercase; letter-spacing: 0.1em; } p { font-family: "futura-pt", Arial, Helvetica, sans-serif; font-weight: 400; font-size: 1.0em; margin: 0; padding: 0; text-transform: uppercase; letter-spacing: 0.1em; } /* Sizes */ .large-5 { font-size: 5.0em; } .large-4 { font-size: 4.0em; } .large-3 { font-size: 3.0em; } .large-25 { font-size: 2.5em; } .large-2 { font-size: 1.5em; } .large-15 { font-size: 1.3em; } @media screen and (min-width: 768px) { .large-5 { font-size: 5.0em; } .large-4 { font-size: 4.0em; } .large-3 { font-size: 3.0em; } .large-25 { font-size: 2.5em; } .large-2 { font-size: 2.0em; } .large-15 { font-size: 1.5em; } } /* Colours */ .white { color: #fff; } .black { color: #000; } /* Spacing */ .padding-top { padding-top: 2em; } .padding-top-double { padding-top: 2em; } .padding-top-triple { padding-top: 1em; } .padding-bottom { padding-bottom: 1em; } /* Links */ a:link, a:visited, a:active { color: #fff; text-decoration: none; } a:hover { color: #fff; text-decoration: underline; } /* General */ body { width: 100%; height: 100%; margin: 0; padding: 0; text-align: center; background: #fff; } *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* Structure */ .content { width: 100%; position: relative; height: 1200px; margin: 0 auto; border: 3px solid #fff; background: url(http://jedesigns.uk/img/hd-sunset-river-HD-1200x1920.jpg) no-repeat; } .content img { max-width: 100%; } my-email::after { content: attr(data-domain); } my-email::before { content: attr(data-user)"\0040"; } I need to know how to fit the background image fully on any screen device so its responsive to any device. i have tried many ways but it didn't worked so hopefully the people of stack overflow can help :) A: You need to use background-size:coverbut propely. That means give 100% height to your .content(and add it to all the parents including html) basically: html, section {height:100%;} body { width: 100%; height: 100%; margin: 0; padding: 0; text-align: center; background: #fff; } *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* Structure */ .content{ width: 100%; position: relative; height: 100%; margin: 0 auto; border: 3px solid #fff; background:url(http://jedesigns.uk/img/hd-sunset-river-HD-1200x1920.jpg) no-repeat; background-size:cover; background-position:center, bottom; } .content img { /* max-width: 100%;*/ } and I also removed the styles you add inline. .content img is wrong css as you don't have any <img>in the html to call. JSFIDDLE
{ "language": "en", "url": "https://stackoverflow.com/questions/32628126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Thunder Client math operations Thunder Client doesn't seem to support math operations in its tests. Is there any way I could make it calculate a multiplication like this? A: You can perform math operations using filters you can use {{quantityCols | multiply("pageSize")}} documentation here https://github.com/rangav/thunder-client-support/blob/master/docs/filters.md#multiply
{ "language": "en", "url": "https://stackoverflow.com/questions/74183097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }