text
stringlengths
70
452k
dataset
stringclasses
2 values
First time attempting to use dependency with Cabal Run init command in local SparkSetup folder : cabal init This creates following files : SparkSetup.cabal : -- Initial SparkSetup.cabal generated by cabal init. For further -- documentation, see http://haskell.org/cabal/users-guide/ name: SparkSetup version: <IP_ADDRESS> -- synopsis: -- description: -- license: license-file: LICENSE author: user maintainer: user -- copyright: -- category: build-type: Simple -- extra-source-files: cabal-version: >=1.10 executable SparkSetup -- main-is: -- other-modules: -- other-extensions: build-depends: base >=4.7 && <4.8 -- hs-source-dirs: default-language: Haskell2010 Setup.hs : import Distribution.Simple main = defaultMain I then modify my Setup.hs file to include Network.Download module from https://hackage.haskell.org/package/download Setup.hs : import Network.Download import Distribution.Simple main = defaultMain And then run commands : cabal sandbox init cabal install -j But receive error : Resolving dependencies... Notice: installing into a sandbox located at C:\Users\Users\Google Drive\SparkSetup\.cabal-sandbox Configuring SparkSetup-<IP_ADDRESS>... Failed to install SparkSetup-<IP_ADDRESS> Last 10 lines of the build log ( C:\Users\users\Google Drive\SparkSetup\.cabal- sandbox\logs\SparkSetup-<IP_ADDRESS>.log ): Configuring SparkSetup-<IP_ADDRESS>... setup-Cabal-<IP_ADDRESS>-x86_64-windows-ghc-7.8.3.exe: No 'main-is' field found for executable SparkSetup cabal: Error: some packages failed to install: SparkSetup-<IP_ADDRESS> failed during the configure step. The exception was: ExitFailure 1 How to include the download package (https://hackage.haskell.org/package/download) in my project ? Update : SparkSetup.cabal : -- Initial SparkSetup.cabal generated by cabal init. For further -- documentation, see http://haskell.org/cabal/users-guide/ name: SparkSetup version: <IP_ADDRESS> -- synopsis: -- description: -- license: license-file: LICENSE author: user maintainer: user -- copyright: -- category: build-type: Simple -- extra-source-files: cabal-version: >=1.10 executable SparkSetup main-is: SparkSetup.hs -- other-modules: -- other-extensions: build-depends: base >=4.7 && <4.8, download -- hs-source-dirs: default-language: Haskell2010 SparkSetup.hs : main = putStrLn "Hello, World!" Run cabal install gives error : setup-Cabal-<IP_ADDRESS>-x86_64-windows-ghc-7.8.3.exe: Bad header file: download.h The header file contains a compile error. You can re-run configure with the verbosity flag -v3 to see the error messages from the C compiler. cabal: Error: some packages failed to install: SparkSetup-<IP_ADDRESS> depends on download-0.3.2 which failed to install. download-0.3.2 failed during the configure step. The exception was: ExitFailure 1 Update 2 : C:\Users\Adrian\Google Drive\SparkSetup>cabal install -v3 Using a sandbox located at C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox Searching for ghc in path. Found ghc at C:\Program Files\Haskell Platform\2<IP_ADDRESS>\bin\ghc.exe ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc.exe",["--numeric-ver sion"]) C:\Program Files\Haskell Platform\2<IP_ADDRESS>\bin\ghc.exe is version 7.8.3 looking for tool ghc-pkg near compiler in C:\Program Files\Haskell Platform\2<IP_ADDRESS>\bin found ghc-pkg in C:\Program Files\Haskell Platform\2<IP_ADDRESS>\bin\ghc-pkg.exe ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["--version "]) C:\Program Files\Haskell Platform\2<IP_ADDRESS>\bin\ghc-pkg.exe is version 7.8.3 ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc.exe",["--supported-l anguages"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc.exe",["--info"]) The package database already exists: C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\x86_64-windows-ghc-7.8.3-packages.conf.d Reading available packages... Reading available packages... Reading installed packages... ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["dump","-- package-db=C:\\Users\\Adrian\\Google Drive\\SparkSetup\\.cabal-sandbox\\x86_64-w indows-ghc-7.8.3-packages.conf.d","-v0"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc.exe",["--print-libdi r"]) Reading installed packages... ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["dump","-- global","-v0"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["dump","-- package-db=C:\\Users\\Adrian\\Google Drive\\SparkSetup\\.cabal-sandbox\\x86_64-w indows-ghc-7.8.3-packages.conf.d","-v0"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc.exe",["--print-libdi r"]) Reading available packages... Choosing modular solver. Resolving dependencies... [__0] trying: feed-<IP_ADDRESS>/installed-4ff... (user goal) [__1] trying: base-<IP_ADDRESS>/installed-7c4... (dependency of feed-<IP_ADDRESS>/installe d-4ff...) [__2] trying: rts-1.0/installedbuil... (dependency of base-<IP_ADDRESS>/installed-7c4 ...) [__3] trying: integer-gmp-<IP_ADDRESS>/installed-d42... (dependency of base-<IP_ADDRESS>/i nstalled-7c4...) [__4] trying: ghc-prim-<IP_ADDRESS>/installed-95d... (dependency of base-<IP_ADDRESS>/inst alled-7c4...) [__5] trying: time-1.4.2/installed-102... (dependency of feed-<IP_ADDRESS>/installed- 4ff...) [__6] trying: deepseq-<IP_ADDRESS>/installed-7fa... (dependency of time-1.4.2/install ed-102...) [__7] trying: array-<IP_ADDRESS>/installed-a62... (dependency of deepseq-<IP_ADDRESS>/inst alled-7fa...) [__8] trying: Win32-<IP_ADDRESS>/installed-698... (dependency of time-1.4.2/installed -102...) [__9] trying: bytestring-<IP_ADDRESS>/installed-016... (dependency of Win32-<IP_ADDRESS>/ installed-698...) [_10] trying: old-time-<IP_ADDRESS>/installed-a22... (dependency of feed-<IP_ADDRESS>/inst alled-4ff...) [_11] trying: old-locale-<IP_ADDRESS>/installed-09b... (dependency of feed-<IP_ADDRESS>/in stalled-4ff...) [_12] trying: tagsoup-0.13.3/installed-d1b... (user goal) [_13] trying: text-<IP_ADDRESS>/installed-1ba... (dependency of tagsoup-0.13.3/instal led-d1b...) [_14] trying: containers-<IP_ADDRESS>/installed-080... (dependency of tagsoup-0.13.3/ installed-d1b...) [_15] trying: time-locale-compat-<IP_ADDRESS>/installed-712... (user goal) [_16] trying: utf8-string-1/installed-8df... (user goal) [_17] trying: xml-1.3.14/installed-97a... (user goal) [_18] trying: SparkSetup-<IP_ADDRESS> (user goal) [_19] next goal: download (dependency of SparkSetup-<IP_ADDRESS>) [_19] trying: download-0.3.2 [_20] done Notice: installing into a sandbox located at C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox Ready to install download-0.3.2 Extracting C:\Users\Adrian\AppData\Roaming\cabal\packages\hackage.haskell.org\download\0.3. 2\download-0.3.2.tar.gz Waiting for install task to finish... to C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540... Updating download.cabal with the latest revision from the index. Configuring download-0.3.2... Using external setup method with build-type Simple creating C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540\download-0.3.2\dist\dist- sandbox-8472864c\setup creating C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540\download-0.3.2\dist\dist- sandbox-8472864c creating C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540\download-0.3.2\dist creating C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540\download-0.3.2\dist\dist- sandbox-8472864c creating C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540\download-0.3.2\dist\dist- sandbox-8472864c\setup Reading installed packages... ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["dump","-- global","-v0"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["dump","-- user","-v0"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc-pkg.exe",["dump","-- package-db=C:\\Users\\Adrian\\Google Drive\\SparkSetup\\.cabal-sandbox\\x86_64-w indows-ghc-7.8.3-packages.conf.d","-v0"]) ("C:\\Program Files\\Haskell Platform\\2<IP_ADDRESS>\\bin\\ghc.exe",["--print-libdi r"]) Using Cabal library version <IP_ADDRESS> Using C:\Users\Adrian\AppData\Local\Temp\download-0.3.2-1540\download-0.3.2\dist/dist- sandbox-8472864c\setup\setup.hs as setup script. Found cached setup executable: C:\Users\Adrian\AppData\Roaming\cabal\setup-exe-cache\setup-Cabal-<IP_ADDRESS>-x86_6 4-windows-ghc-7.8.3.exe C:\Users\Adrian\AppData\Roaming\cabal\setup-exe-cache\setup-Cabal-<IP_ADDRESS>-x86_6 4-windows-ghc-7.8.3.exe configure --verbose=3 --builddir=dist/dist-sandbox-8472864c --ghc --prefix=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox --bindir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\bin --libdir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox --libsubdir=x86_64-windows-ghc-7.8.3\download-0.3.2 --libexecdir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\download-0.3.2 --datadir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox --datasubdir=x86_64-windows-ghc-7.8.3\download-0.3.2 --docdir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\doc\x86_64-windows-ghc-7.8.3\download-0.3.2 --htmldir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\doc\x86_64-windows-ghc-7.8.3\download-0.3.2\html --haddockdir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\doc\x86_64-windows-ghc-7.8.3\download-0.3.2\html --sysconfdir=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\etc --global --package-db=C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\x86_64-windows-ghc-7.8.3-packages.conf.d --extra-prog-path=C:\Users\Adrian\AppData\Roaming\cabal\bin --constraint=xml ==1.3.14 --constraint=tagsoup ==0.13.3 --constraint=feed ==<IP_ADDRESS> --constraint=bytestring ==<IP_ADDRESS> --constraint=base ==<IP_ADDRESS> --disable-tests --disable-benchmarks Redirecting build log to {handle: C:\Users\Adrian\Google Drive\SparkSetup\.cabal-sandbox\logs\download-0.3.2.log} Failed to install download-0.3.2 Last 10 lines of the build log ( C:\Users\Adrian\Google Drive\SparkSetup\.cabal- sandbox\logs\download-0.3.2.log ): function) cbits/download.h:90:1: error: unknown type name '__BEGIN_DECLS' cbits/download.h:93:6: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token cbits/download.h:124:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'typedef' cbits/download.h:125:1: error: unknown type name 'auth_t' setup-Cabal-<IP_ADDRESS>-x86_64-windows-ghc-7.8.3.exe: Bad header file: download.h The header file contains a compile error. You can re-run configure with the verbosity flag -v3 to see the error messages from the C compiler. cabal: Error: some packages failed to install: SparkSetup-<IP_ADDRESS> depends on download-0.3.2 which failed to install. download-0.3.2 failed during the configure step. The exception was: ExitFailure 1 Looks like the download package relies on system headers providing a __BEGIN_DECLS macro. I guess this has never been tested on windows. @melpomene can you advise what OS I should use for Haskell dev. Ubuntu ? I would use some kind of Linux, yes. I don't know which distribution is best for Haskell, though. Using Linux is probably a bit smoother, but a large majority of things work just fine on Windows (I guess you were just unlucky with this download package). If you can't get download to work, http-conduit-downloader looks helpful. As for Linux distros, typically it doesn't matter much as you will get packages via cabal or stack anyway. I like Arch because new GHCs reach it quickly. You usually do not touch Setup.hs at all. Instead, add download to the build-depends field in your .cabal files. Furthermore, the .cabal file is incomplete: Uncomment the main-is field and put in the filename of your main module, e.g. main-is: SparkSetup.hs Breithner so line build-depends: base >=4.7 && <4.8 should be build-depends: base >=4.7 && <4.8 && download ? base >=4.7 && <4.8, download please see question update, the download package is not installing ?
common-pile/stackexchange_filtered
How can i know the root div when clicked on a element I have got section element with class "secclass" in two div's <div id="69" class="activateUiHTML" data-role="collapsible"> <div class="prd-items-detials"> </div> <div style="" class="Topping-details" id="69"> <section id="topping_tsection_69"> <aside> <h6 class="tdHeading">Quantity 1</h6> <img src="images/arrow-topping.png"> <section class="secclass"><a data-id="69" topping_id="17" id="69_ZZ_0_ZZ_0" topp_name="Honey with Carmel 10 ML" top_cost="30" class="tpActive" qt_val="69_ZZ_0_ZZ_0">Honey with Carmel 10 ML</a></section> </aside> </section> </div> </div> And also under this <div id="addtoordersdiv69"> <div class="prd-items-detials"> </div> <div style="" class="Topping-details" id="69"> <section id="topping_tsection_69"> <aside> <h6 class="tdHeading">Quantity 1</h6> <img src="images/arrow-topping.png"> <section class="secclass"><a data-id="69" topping_id="17" id="69_ZZ_0_ZZ_0" topp_name="Honey with Carmel 10 ML" top_cost="30" class="tpActive" qt_val="69_ZZ_0_ZZ_0">Honey with Carmel 10 ML</a></section> </aside> </section> </div> </div> I have got a listener registered for the section element with its class secclass My question is when clicked on the section element how can i know if it belongs to the first div or second div ?? $(document).on("click", ".secclass a", function(e) { }); I have tried it this way $(document).on("click", ".secclass a", function(e) { if($(this).hasClass("activateUiHTML")) { alert('from activehtmlui'); } else { alert('from myorders'); } }); But it isn't working . You are using id="topping_tsection_69" multiple times, use class instead You can check the length of parent div with class="activateUiHTML" like below $(document).on("click", ".secclass a", function(e) { if($(this).closest(".activateUiHTML").length > 0) { alert('from activehtmlui'); } else { alert('from myorders'); } }); You can use sth like: $(document).on("click", ".secclass a", function(e) { console.log($(this).closest('.Topping-details').parent('div').index()); }); but i would use a class to those divs like .module and then use jQuery like: $(this).closest('.module').index(); Test it here on jsfiddle. Also be careful because you use twice id="69" and id="topping_tsection_69" in your code and id should be unique. Prefer data attributes like data-id="69" or data-id="topping_tsection_69". For the First div i get [div#69.activateUiHTML, prevObject: jQuery.fn.jQuery.init[1], context: a#69_ZZ_0_ZZ_0, jquery: "1.9.1", constructor: function, init: function…] , can i extract activateUiHTML from this ?? Do you still want the index of the parent divs? Now you have it. Did you check your console? My code returns their index like 0 or 1 accordingly. $(document).on("click", ".secclass a", function(e) { var $divPar = $(this).parents("div"); alert($divPar.attr("id")); }); by analysing $divPa you could find the result as you desire Hi Sarath with this i get the same value from both the div's . can i work out this way $(this).hasClass("activateUiHTML")?? then put a specifisc class (like mainDiv) on both divs. And rewrite the code as $(document).on("click", ".secclass a", function(e) { var $divPar = $(this).parents("div.mainDiv"); if($(this).hasClass("activateUiHTML")) alert("1st div"); }); Hope this will work for you now. Sorry for the careless typings. All the best.
common-pile/stackexchange_filtered
Building ICU with NDK For last couple of days I've been trying to figure out how to implement ICU library for Android support. I stuck on very begining, trying to compile ICU sources with NDK. I got them from here: https://android.googlesource.com/platform/external/icu/ I put it in my jni location and added in my Android.mk file this line: include $(call all-subdir-makefiles) and added to local flags: -DSQLITE_ENABLE_ICU I'm getting a lot of errors trying to build it (on Windows machine). Here is my output: c:/ndk/build/core/build-binary.mk:457: warning: overriding commands for target ` "----my android project location----"//obj/local/armeabi/objs/icui1 8n/smpdtfst.o' c:/ndk/build/core/build-binary.mk:457: warning: ignoring old commands for target `"----my android project location----"//obj/local/armeabi/objs/icu i18n/smpdtfst.o' c:/ndk/build/core/build-binary.mk:457: warning: overriding commands for target ` "----my android project location----"//obj/local/armeabi/objs/icui1 8n_static/smpdtfst.o' c:/ndk/build/core/build-binary.mk:457: warning: ignoring old commands for target `"----my android project location----"//obj/local/armeabi/objs/icu i18n_static/smpdtfst.o' [armeabi] Compile thumb : icui18n <= decContext.c [armeabi] Compile thumb : icui18n <= ucln_in.c [armeabi] Compile thumb : icui18n <= ulocdata.c [armeabi] Compile++ thumb: icui18n <= indiancal.cpp [armeabi] Compile++ thumb: icui18n <= dtptngen.cpp [armeabi] Compile thumb : icui18n <= decNumber.c [armeabi] Compile thumb : icui18n <= utmscale.c [armeabi] Compile++ thumb: icui18n <= dtrule.cpp In file included from "----my android project location----"//jni/ic u/icu4c/source/i18n/../common/unicode/unistr.h:31:0, from "----my android project location----"//jni/ic u/icu4c/source/i18n/../common/unicode/locid.h:34, from "----my android project location----"//jni/ic u/icu4c/source/i18n/unicode/calendar.h:37, from "----my android project location----"//jni/ic u/icu4c/source/i18n/indiancal.h:18, from "----my android project location----"//jni/ic u/icu4c/source/i18n/indiancal.cpp:10: "----my android project location----"//jni/icu/icu4c/source/i18n/.. /common/unicode/std_string.h:33:18: fatal error: string: No such file or directo ry #include <string> ^ compilation terminated. make.exe: *** ["----my android project location----"//obj/local/arm eabi/objs/icui18n/indiancal.o] Error 1 make.exe: *** Waiting for unfinished jobs.... In file included from "----my android project location----"//jni/ic u/icu4c/source/i18n/../common/unicode/unistr.h:31:0, from "----my android project location----"//jni/ic u/icu4c/source/i18n/../common/unicode/strenum.h:14, from "----my android project location----"//jni/ic u/icu4c/source/i18n/../common/unicode/uenum.h:24, from "----my android project location----"//jni/ic u/icu4c/source/i18n/unicode/ucal.h:12, from "----my android project location----"//jni/ic u/icu4c/source/i18n/unicode/udat.h:16, from "----my android project location----"//jni/ic u/icu4c/source/i18n/unicode/datefmt.h:26, from "----my android project location----"//jni/ic u/icu4c/source/i18n/dtptngen.cpp:15: "----my android project location----"//jni/icu/icu4c/source/i18n/.. /common/unicode/std_string.h:33:18: fatal error: string: No such file or directo ry #include <string> ^ compilation terminated. make.exe: *** ["----my android project location----"//obj/local/arm eabi/objs/icui18n/dtptngen.o] Error 1 "----my android project location----"//jni/icu/icu4c/source/i18n/dt rule.cpp: In member function 'UBool icu_54::DateTimeRule::operator==(const icu_5 4::DateTimeRule&) const': "----my android project location----"//jni/icu/icu4c/source/i18n/dt rule.cpp:85:22: error: cannot use typeid with -fno-rtti (typeid(*this) == typeid(that) && ^ "----my android project location----"//jni/icu/icu4c/source/i18n/dt rule.cpp:85:38: error: cannot use typeid with -fno-rtti (typeid(*this) == typeid(that) && ^ make.exe: *** ["----my android project location----"//obj/local/arm eabi/objs/icui18n/dtrule.o] Error 1 and here is my main Android.mk file located in jni directory: LOCAL_PATH:= $(call my-dir) include $(call all-subdir-makefiles) include $(CLEAR_VARS) LOCAL_MODULE:= sqlitenative LOCAL_SRC_FILES := sqlite3.c sqlite3_native.cpp # NOTE the following flags, # SQLITE_TEMP_STORE=3 causes all TEMP files to go into RAM. and thats the behavior we want # SQLITE_ENABLE_FTS3 enables usage of FTS3 - NOT FTS1 or 2. # SQLITE_DEFAULT_AUTOVACUUM=1 causes the databases to be subject to auto- vacuum # SQLITE_HAS_CODEC enables crypto support for database LOCAL_CFLAGS += -DHAVE_USLEEP=1 \ -DSQLITE_DEFAULT_JOURNAL_SIZE_LIMIT=1048576 \ -DSQLITE_THREADSAFE=1 \ -DNDEBUG=1 \ -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 \ -DSQLITE_DEFAULT_AUTOVACUUM=1 \ -DSQLITE_TEMP_STORE=3 \ -DSQLITE_ENABLE_FTS3 \ -DSQLITE_ENABLE_FTS3_PARENTHESIS \ -DSQLITE_ENABLE_COLUMN_METADATA \ -DSQLITE_ENABLE_ICU \ -DHAVE_STRCHRNUL=0 LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog -lc LOCAL_C_INCLUDES += $(call include-path-for, system-core)/cutils LOCAL_SHARED_LIBRARIES += libicuuc \ libicui18n \ libutils LOCAL_SHARED_LIBRARIES += libicuuc-host libicui18n-host LOCAL_STATIC_LIBRARIES := liblog libutils libcutils include $(BUILD_SHARED_LIBRARY) include $(BUILD_HOST_SHARED_LIBRARY) The source tree from googlesource is to be built by lunch command. This environment is similar, but significantly different from NDK. You must rewrite the Android.mk files. But is it possible to build it on Windows machine? I would not encourage you to spend your time on this, if you are not proficient with cygwin, make, and ndk. It is much easier to compile the library under Ubuntu, in a virtual box. Actually, you don't see a strong reason in building this library on your own: it is already part (albeit unofficial) of any Android installation. You can simply assume that libicui18n.so and libicuuc.so are present in /system/lib and use them! You can build ICU for Android using the NDK's standalone toolchain, configure && make. You'll have to pass some flags that you likely get away with not passing for a host build, but it works. Minor update: Please do not link against "unofficial" Android system libraries. They can -- and will -- change at any time. Additionally, Google will begin marking symbols private with Android N+. See http://android-developers.blogspot.com/2016/06/improving-stability-with-private-cc.html Possible duplicate of Include ICU in Android NDK Project
common-pile/stackexchange_filtered
Why does pygame show a black window? Imports #Imports import pygame, sys, time, random from pygame.locals import * Display pygame.init() #initializes pygame window pygame.display.set_caption('Parkour') #titlebar caption Bg=pygame.display.set_mode((800,600),0,32) #sets main surface """--------------------------------------------------------------------------""" Event loop gameActive = True while gameActive: #print (event) for event in pygame.event.get(): if event.type == pygame.QUIT: gameActive = False pygame.quit() quit() Background (ISSUE) Yeah I'm a beginner, but shouldn't this fill the screen then update it? Bg is true so it should constantly run right? #Background Bg = True while Bg: screen.fill((0,0,255)) pygame.display.flip() Please put all your code snippets together to make a [mre] for others to run. Furthermore the variable Bg is the Surface which is associated to the window: Bg=pygame.display.set_mode((800,600),0,32) #sets main surface Do not use the same variable name for a boolean state: Bg = True I recommend to change the name of the display surface (e.g. screen), because you've used this name in screen.fill((0,0,255)), too: screen = pygame.display.set_mode((800,600),0,32) #sets main surface Of course you have fill the background and to update the display in the main application loop. The main application has to handle the events clear the display draw the scene update the display continuously in every frame. e.g.: #Imports import pygame, sys, time, random from pygame.locals import * pygame.init() #initializes pygame window pygame.display.set_caption('Parkour') #titlebar caption screen = pygame.display.set_mode((800,600),0,32) #sets main surface # main application loop gameActive = True while gameActive: # handle the events in the event loop for event in pygame.event.get(): if event.type == pygame.QUIT: gameActive = False # clear the display screen.fill((0,0,255)) # draw the scene # [...] draw things here # update the display pygame.display.flip()
common-pile/stackexchange_filtered
Prestashop 1.6 Cart recovery after 3DSecure redirect I am building a payment gateway module based on the Authorize.net (aim) module. The issue is that after 3DSecure validation, it redirects back to the website, but the cart is not in context, I think. Before I am redirecting, I am saving the cart id to the session. It throws the following error: "Cart cannot be loaded or an order has already been placed using this cart" This is triggered by: if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) on line 188 of classes/PaymentModule.php How can I load/reload the cart? Thanks Jacques In many payment modules, Prestashop create order before bank redirect with missing payment status and wait bank confirmation to update order. If you want still regenerate cart, you can do that with the submitReorder functionnality in ParentOrderController. $oldCart = new Cart(Order::getCartIdStatic($id_order, $this->context->customer->id)); $duplication = $oldCart->duplicate(); if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) { $this->errors[] = Tools::displayError('Sorry. We cannot renew your order.'); } elseif (!$duplication['success']) { $this->errors[] = Tools::displayError('Some items are no longer available, and we are unable to renew your order.'); } else { $this->context->cookie->id_cart = $duplication['cart']->id; $context = $this->context; $context->cart = $duplication['cart']; CartRule::autoAddToCart($context); $this->context->cookie->write(); if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { Tools::redirect('index.php?controller=order-opc'); } Tools::redirect('index.php?controller=order'); } how do I save the order before redirect - Google isn't being helpful
common-pile/stackexchange_filtered
Terminology - Changing the behaviour of a function but not it's name Consider this situation: there is a method getFoo(). It now becomes appearent that the method as-is is not useful or even encourages faulty code to be written upon it. A breaking change (e.g. returning a collection instead of a single item) must be made but the name of the method is still fine. Do such changes have a special term? If yes: which? Also: what is the best way do deal with such changes; how to warn users about them (since there is no function you could deprecate)? As far as I understand "deprecation", it is meant to signify that a function/method will be completely removed in some future version of the software/API. There is likely no well-defined name for such a situation because it is a bad idea to do so. Names are not a finite resource, so creating a different name for a method that does a different thing should not be a big deal. @BobDalgleish that may be the case in some programming languages and frameworks, but not all. For example Ruby on Rails makes these kinds of changes fairly frequently; in Rails 5 for example this happened: https://eileencodes.com/posts/actioncontroller-parameters-now-returns-an-object-instead-of-a-hash/ This seems to be a deliberate design decision, as the creator has said "Whenever I stumble across something I don't like, I change it." https://interviews.slashdot.org/story/16/08/30/1759216/the-slashdot-interview-with-ruby-on-rails-creator-david-heinemeier-hansson How is this opinion-based? There's either a term for it or there isn't... smh If you think about the new version as being a different method that happens to do the same thing, but has a different interface, then that's essentially deprecation of the old version. This is called a breaking change to the API, or a change which is not backward compatible. How acceptable such a change it is depends on the degree of control you have over the code which uses this specific method, it is not necessarily a "bad idea" in general. Deprecated means in its general sense to disapprove something or to give it little value. In the software context, it means to discourage the use of a feature. In the Java Community, for example, deprecated has indeed frequently the meaning of a future removal. But this is not the only reason: ... the API has been superseded by another API, the API is obsolete, the API is experimental and is subject to incompatible changes, ... According to this interpretation, incompatible changes could also be covered by the term deprecation. So there is not really a need for a new term. But regardless of how you call this change in the API, this is not a good practice, unless you're still in preprelease (release 0 in the semver API versionning scheme): Keeping the same function name with a different interface forces the users of the API to do the change timely with your new API publication. They have no way to adapt their code in advance, but as soon as you release the new API they have to quickly update every call. This is very inflexible ! Your users may have to block a release cycle for your adaptations. Keeping the old function with the old signature, but deprecated, and introduce the new function with the new signature under a new name, allows you to let both versions coexist temporarily. The users can then migrate their code to the new API at their own pace over several of their releases. This is much more user friendly (and professional). Of course, if the language supports overloading and accepts the same name with both signatures and without ambiguity, you may let both deprecated and new function coexist under the same name. Keeping the same function name with a different interface **forces the users of the API to do the change timely** with your new API publication. This is also true for deprecated methods that will be removed. The time frame the users have to change their code to remove the usage of the deprecated methods is exactly the same (my assumption is that the "repurposed" methods will remain unchanged during the "buffer" interim before ultimately changing). So I don't see any validity to this point. @istrasci So essentially what you're doing is deprecating a method, then, at the time you remove it, introducing a new method with the exact same name but a different functionality and return type? Still sounds like really bad idea. @istrasci It is true that you can inform well in advance in both cases. But with the same name, it is a hard switch: before your release your user cannot anticipate-not even a poc; once you’ve released the user must do the necessary to switch. If it’s a big system with hundred of modules using your API, it’s a heavy constraint. With the new name, you can offer a tolerance period, deciding when you introduce, and when you remove, temporarily offering both and let users in control Just think of this as deprecating an older version of the method (in terms of interface). No need for a new term.
common-pile/stackexchange_filtered
What's the closest RAW build possible to the Gray Mouser in 5e? I am of course referring to the legendary figure of Fritz Lieber's Lankhmar series (one of the things Gary Gygax said was his inspiration to invent D&D). I am assuming this character is so off-the-hook awesome that I cannot see any way to make him using strictly RAW, but what's the closest we can get? Some things to keep in mind: His acrobatics, stealth and persuasion are incredible (especially acrobatics) His swordsmanship is fantastic, in a finesse-sort-of-way (rapier?), and when combined with a successful acrobatic move he can hit almost anything He is devastating with a sling, e.g. can knock someone out or do great damage (a thing which seems outside the RAW in 5e) He has a custom-made bodysuit that enhances stealth, and he is very hard to hit in melee (almost un-hittable!) despite that he has no armor or shield beyond this He has some low-level arcane spellcasting abilities While he is not immune to being charmed, he is fairly resistant to it Those are the essentials, and here are nice-to-haves: Race is human Magic is limited mainly to illusions (less magic than an Arcane Trickster has) Acrobatic-based swordplay (to-hit improves somehow when using acrobatics) Can use a sling effectively at longer range, compared to a typical character There may be other features I am overlooking from Lieber's material, but those are the high points. What's the closest you could come in RAW? I've re-cast the question. Please consider taking it off hold? This is one of just a few characters who inspired the whole game, for crying out loud, and I want to ask how to make the character. There has to be some form of the question that is fit for this forum. Please help improve the question rather than close it, for heaven's sake. @BigJamey If you include more about the character within the post itself, and describe what you need in a bit more specific terms than "this character," it's probably a workable character build question. A human Fighter/Rogue (Arcane Trickster) of at least 8th level total, perhaps level 14 or higher According to the Q&A with Gary Gygax, part 5 forum thread in 2004: The Thief was based on Jack of Shadows (Zelazny) and Cugel (Vance) with a touch of REH’s Conan, rather than solely on the Gray Mouser. Mouser was too good a swordsman to serve as the pure model. However, Gygax was talking about the D&D of his era, and the rules have changed much since then. Based on your requirements, the Rogue class (which in Gygax's D&D was called the Thief) with the Arcane Trickster subclass is a suitable match: Acrobatics, stealth and persuasion: All three of these are literally class skills for the rogue. The rogue's Expertise ability at 1st and 6th level allows their proficiency bonus to be doubled for these skills, and Reliable Talent (11th level) also extends this ability. Fantastic swordsmanship: The rogue is proficient with the rapier, as well as shortswords and longswords. D&D 5e no longer gives the fighter a higher base attack bonus than the rogue, so this class imposes no penalty. Optional acrobatic swordplay: Tricky to model in D&D, but the most readily available solution is to drop at least a single level in fighter and adopt the Dueling fighting style which grants +2 to damage while fighting in his unique style with no shield. A level 3 fighter (Battle Master) gains unique and clever maneuvers, but this may be pushing it. I'm not aware of any official feat or option in this particular edition of D&D that specifically gives a combat bonus for using the Acrobatics skill. Devastating with a sling: The rogue has sling proficiency (as a simple weapon) and can gain Sneak Attack if he has advantage on the attack roll, even if he is not hidden from the opponent. A high level rogue can deal substantial damage with sneak attack. The optional requirement of long range with a sling can be met with the Sharpshooter feat, which extends range and the ability to hit through cover. Currently, there's no rule which allows a nonlethal knockout with a ranged weapon (although any character may do this with a melee weapon). Custom bodysuit and unhittable: He would require magic items for this in D&D: magical leather armor, a cloak of displacement, and a naturally very high or magically-enhanced Dexterity. For a high-level character, these magic items are plausible. Uncanny Dodge (5th level rogue ability) halves damage from attackers the rogue can see. To meet the optional requirement of the character being human, with the human starting ability score bonus and ability score improvement at every 4th rogue level, he could still have superhuman Dexterity. (If you're willing to forgo the human requirement, an elf would also have naturally increased Dexterity.) Low-level spellcasting: The Arcane Trickster roguish archetype gains 1st level arcane spells at level 3, 2nd level spells at level 7, and 3rd level spells at level 13. This is low level magic for the character level, if we assume the character is below 18th level. Mainly illusions: An arcane trickster who only chooses illusions, even if the class doesn't enforce this, is still a valid build. The first level spell silent image creates illusion with no sound; second level minor image alllows image or sound; the third level major image adds other sensory effects and the illusion can move around. If major image is beyond his ability then he should not be above 12th level; otherwise, level 14 or 15 would be possible. Charm resistance: A high-level character with high Wisdom would have high saves, and magic items may enhance that further. If it's not required to make the character a human, an elf of any sort or half-elf is resistant but not immune to being charmed. To meet the human optional requirement while still resisting charms, he could spend his first feaat (variant human feat at 1st level ability) on Resilient to increase his Wisdom by 1 (which may already be high to begin with) and grant proficiency in Wisdom saves. If Gray Mouser is really high level, the 15th level rogue ability Slippery Mind gives proficiency in saving throws, but he could of course just take the Resilient feat at an earlier level. On a historical note, according to Dragon Magazine #70 (February 1983), Gray Mouser would be a a very high level multiclass fighter/thief. This is consistent with Gygax's opinion that Gray Mouser is like a Thief but better at swordfighting. Thanks to @DavidCoffron, @KorvinStormast, @DarthPseudonym and @sharur for suggestions in the comments. You may also want to add that a variant human could gain the Resilient (Wisdom) feat to bolster it's Wisdom saves too. (Or just through class leveling since rogues get an extra ASI). This makes Fey Ancestry less important I would suggest, being a long time fan of Lieber's Swords and Sorcery duo from Lankhmar, that making Mouser an Elf is utterly at odds with the character. (Your mechanical points all considered; they are well thought out ...) vHuman is the better idea It's also worth mentioning that a rogue has Expertise for up to 4 skills by 6th level, which can account for being a ridiculously good acrobat/etc., beyond the realm of normal characters; Uncanny Dodge (and later, Elusive) may account for being nigh-unhittable thanks to acrobatics; and Slippery Mind contributes to being hard to charm. Depending on how much magic you want, it might fit better to go with the Thief archetype and use the Magic Initiate feat or a level dip to gain some minor spellcasting. Good answer but I agree with all the above comments. (1) ideally he's human, not elf, so another way of being charm-resistant is good. (2) Arcane Trickster is actually more magic than he needs; the Mouser mainly just uses illusions for deceit and distraction, but has good concentration maintaining them in melee, which fits with beefing up Wis, and a wiz-dip or the MI feat. (3) Per the Gygax quote, yeah, he's too-good a swordsman, and the main "essence" I feel is still missing here is how his swordsmanship improves when he adds his acrobatics. (4) Lieber's Mouser has longer range with a sling. @BigJamey Concentration uses Constitution not Wisdom. You might want to include these specific goals (human/less magic/acrobatic based swordplay/long range) in the question @DavidCoffron Yes good catch. I added a few more features in the question. @BigJamey: The War Caster feat gives advantage on concentration checks, so combined with a high AC making him had to hit in the first place, that might do it. And/or make his armor or some other magic item a custom item that gives a bonus to concentration checks (not Constitution saves in general, if the Mouser isn't supposed to be physically tough). Also, the requirement of "He is devastating with a sling, e.g. can knock someone out or do great damage (a thing which seems outside the RAW in 5e)" and optional requirement of "Can use a sling effectively at longer range, compared to a typical character" can be fulfilled with the Sharpshooter Feat, which is a RAW option that allows for longer effective range and bonus damage (and ignoring less than full cover). Perhaps a multiclass is the answer. Rogue/Bard might be appropriate. Here's what I would do to try and create a character like this. First off: play a Variant Human, and start with the Sharpshooter feat. This will give you that extra range and damage with the sling. Begin as a Rogue, eventually choosing the Swashbuckler subclass from Xanathar's Guide to Everything. Take Expertise in Acrobatics and Persuasion at level 1, and in Stealth and another ability of your choice at level 6. This will give you excellent acrobatics, stealth, and persuasion. At level 4, take the Resilient feat, choosing to give yourself Proficiency in Wisdom saves, increasing your resistance to most Charm effects. Your sling and swordsmanship abilities will be represented by the ever-increasing damage of your Sneak Attack. Melee Sneak Attacks are made more easily thanks to the Swashbuckler level 3 ability Rakish Audacity, which lets you Sneak Attack if your target is the only creature (ally or enemy) within 5 feet of you. A Rapier will probably be your melee weapon of choice. There is some room for flexibility, but you will probably want to end up with at least 13 levels in Rogue to gain the Swashbuckler ability Elegant Maneuver. This allows you to use a Bonus Action on your turn to gain advantage on the next Acrobatics check you make during the same turn. This will raise your already Expertised Acrobatics ability even higher. To improve your swordsmanship and grant some Arcane spellcasting, I would also take several levels of Bard. By taking 6 levels of Bard and choosing the College of Swords (also from Xanathar's Guide to Everything), you can gain several benefits for this build. At level 3, you gain the Dueling fighting style, to further enhance your swordsmanship. You also gain the Blade Flourish ability, which allows you to use Bardic Inspiration to improve your attacks and can be used to represent your superior swordsmanship when combined with acrobatic skill. At level 6, you gain the Extra Attack feature, which will improve your melee capabilities even further. You also gain the ability Countercharm which allows you to use our Action to gain advantage on saving throws against Charm or Fear until the end of your next turn. This (on top of the Resilient feat mentioned earlier) fits in with being "fairly resistant" to Charm effects. From 6 Bard levels, you will also gain access to Illusion spells up to third level. You have the option to choose other spells as well, but if you want to focus on Illusions, that's your prerogative. Your bodysuit could take the form of the Rare magic item Glamoured studded leather. This is +1 studded leather armor that can change its appearance when you use a command word. If that's not stealthy enough for you, it could be paired with the uncommon Cloak of Elvenkind which gives advantage on Stealth checks. A rare Cloak of Displacement, which gives disadvantage to incoming attacks might also be a viable option. All of these are in the DMG. In the end, you're probably going to end up with a level 13 Rogue/level 7 Bard or level 14 Rogue/level 6 Bard. I would recommend the latter as it gives the useful Rogue ability Blindsense. The levels can be taken in any order that makes the most sense to you. I believe this build covers most of your main and optional criteria. Kensei Monk, with some other investment for magic As a Kensei Monk, you gain access to several things that address your concerns. Notably, the base class Monk gets: Wisdom and Dexterity to AC. As long as his "bodysuit" isn't considered real armor, he will be extremely difficult to hit, despite being nearly naked. They naturally have an aptitude for Athletics, Stealth, and Acrobatics, and Persuasiveness can be almost obtained with an optimized Insight skill. Persuasion can be obtained via a background. They can spend a Ki point to grant them the Dodge, Disengage, or Dash action at the cost of a Ki point while doubling his jump distance (referencing his acrobatic prowess). They have enhanced mobility, and can even run up walls and across water at later levels. They eventually get proficiency in all saving throws at level 14, and the ability to remove any Charm or Fear effect on them by spending an action at level 7. A naturally high Wisdom score (optimized with a monk) will also increase your chance to resist these effects in the first place. As for the Kensei subclass specifically: They can choose to select specific weapons to specialize in, which can include a Rapier and a Sling. These specialized weapons gain increased damage and powers, making even a Sling a dangerous weapon, especially considering it's ammunition is simply a rock. They are naturally proficient in both melee and ranged combat, and can enhance both with powerful effects. A simple sling can deal 2d4 + 8 (13) magical damage per hit and add your Martial Arts die (1d4-1d10) once per turn. It would have + 8 to hit, and you can reroll a missed attack once per turn. For magic There're two options, depending on how far you want to go. For combat support, 3 levels into Arcane Trickster would get you some necessary illusion spells that would improve your interactions when out of combat, while also giving you a 2d6 sneak attack die each turn. Alternatively, a Magic Initiate (Wizard or Bard) feat will require less investment and grant you things like Minor Illusion, Prestidigitation, Fog Cloud or Disguise Self. Your options would be very limited, though, and wouldn't grow beyond this point. For Range As you're looking to be a human, being a Variant Human, investing in Sharpshooter, will provide the range enhancement you're looking for, and will also work well with other options, such as darts or a longbow. For those downvoting, please let me know what I can do to improve this post. I'd really appreciate your constructive feedback.
common-pile/stackexchange_filtered
multiple variables in routes. A route isn't leading to the controller defined blade I have "show" and "edit" two routes. It's showing two different url. But "edit" route is using the 'show' blade, which is the SAME as the "show" route. How to lead the "edit" route to the 'edit' blade? here is the web.php: Route::get('/{user}/{course}', 'CoursesController@show')->name('course.show'); Route::get('/{user}/edit_{course}', 'CoursesController@edit')->name('course.edit'); here is the controller: public function edit(Course $course) { return view('courses.edit', compact('course')); } public function show(Course $course) { return view('courses.show', compact('course')); } here is the index blade: <a class="btn btn-xs btn-primary" href="{{ route("course.show", [auth()->user()->username, $course->title. $course->id] ) }}"> VIEW </a> <a class="btn btn-xs btn-info" href="{{ route("course.edit", [auth()->user()->username, $course->title. $course->id]) }}"> EDIT </a> Do you have the files views/courses/edit.blade.php and views/courses/show.blade.php? If so, I'm not sure what the problem is clearly. Are you passing in the correct request? you edit and show methods must receive the id of the model in order the model binding can work properly. https://laravel.com/docs/7.x/routing#implicit-binding change the order of the two routes solved the issue. Thanks guys. Change the order or your routes in your routes files web.php Route::get('/{user}/edit_{course}', 'CoursesController@edit')->name('course.edit'); //This one goes first. Route::get('/{user}/{course}', 'CoursesController@show')->name('course.show'); Your show route is working as a wildcard if you invert the order as shown the edit route will catch it first when the second variable begins with edit_. Yaasss you are absolutely right. Thanks a lot victoryoalli!!!
common-pile/stackexchange_filtered
Curl of gradient of potential in electrostatic We know, curl of E is zero (this field is conservative). Again E=-grad V. So, we get curl of (-grad V)=0, i.e. curl of gradient of potential is zero. Is there any condition on potential? Have you taken a course on multivariable calculus? Try to manually compute (i.e. write it out in it's explicit form) the gradient of some potential $V$, and then compute its curl. This is more than sufficient to find out if some condition is needed on $V$. (If you are stuck, check out the theorems on: https://en.wikipedia.org/wiki/Symmetry_of_second_derivatives) So there is two conditions: Laplace equation No, not the Laplace equation. Write out grad($V$) as $(\frac{\partial{V}}{\partial{x}},..,..)$ and then compute its curl. I have got somethu Mind updating your question with the same? As hrithik says curl of a gradient of is always zero. Let V=V(x, y, z). The gradient of V ie $\nabla V= \frac{\partial V} {\partial x} \hat{i} +\frac{\partial V} {\partial y} \hat{j} +\frac{\partial V} {\partial z} \hat{k} $. Now the curl of grad v is ie $\nabla × \nabla V$ now you got a determinate. Upon solving that $\frac{\partial} {\partial y} ({\frac{\partial V} {\partial z}) \hat{i}} - \frac{\partial} {\partial z} ({\frac{\partial V} {\partial y}) \hat{i}} - \frac{\partial} {\partial x} ({\frac{\partial V} {\partial z}) \hat{j}} + \frac{\partial} {\partial z} ({\frac{\partial V} {\partial x}) \hat{j}} + \frac{\partial} {\partial x} ({\frac{\partial V} {\partial y}) \hat{k}-\frac{\partial} {\partial y} ({\frac{\partial V} {\partial x}) \hat{k}}}$ now basically $\frac{\partial} {\partial y} ({\frac{\partial V} {\partial z}) } = \frac{\partial} {\partial z} ({\frac{\partial V} {\partial y}) }$ as well $\frac{\partial} {\partial x} ({\frac{\partial V} {\partial z})}$ = $ \frac{\partial} {\partial z} ({\frac{\partial V} {\partial x})} $ and $\frac{\partial} {\partial x} ({\frac{\partial V} {\partial y})} = \frac{\partial} {\partial y} ({\frac{\partial V} {\partial x})} $ so curl of gradient of V or any other function is always zero. So no charactesic of V is needed except for it should exist ie the electric field should be Conservative.
common-pile/stackexchange_filtered
Simplifying units in pint without changing the magnitude Working with python-pint, let's suppose I have a quantity defined as <Quantity(1.0, 'gram * kilopascal / joule')> which is equivalent to kilogram/m3. Now, when I try to get that using to_base_units i get: den.to_base_units() <Quantity(1000.0, 'gram / meter ** 3')> which is fine, except I wished the magnitude was still 1, and the units were, instead, <Quantity(1.0, 'kilogram / meter ** 3')>, for user-friendliness purposes. Is there a way to achieve that? By the way, this happens with many different units throughout my program and there's no (easy) way to know which are the correct units for it to be converted to, which prevents me from using convert_to method. In this case it should change from 1000 gram to kilogram, for example, but in the next case it can be from 0.001 meter to 1 milimeter and so on. I know that pint 0.7 (I'm still using 0.6) has a new system option, but I also couldn't solve it with that. Cheers Is there a .convert_to(unit) method that you could call like q.convert_to('kilogram / meter ** 3') That's a good idea for this case specifically, but this happens with many different units and there's no (easy) way to know which are the correct units for it to be converted to. I'll make that fact more explicit in my question. You need to redefine base mass unit from gram to kilogram. GitHub issue may be helpful. This is interesting, but I think this would eventually return <Quantity(0.001, 'kilogram')> for one gram, wouldn't it? I'd like to avoid any quantities from have magnitudes different from 1 (except, of course, when it's not possible). First of all, gram is no longer treated as a base unit in Pint 0.8.1. Instead, Pint treats the kilogram as a base unit which is according to the SI standard: >>> x = 0.1*ureg['g kpascal / J'] >>> print(x.to_base_units()) 0.1 kilogram / meter ** 3 Second, I think you may have mixed up two things, getting a quantity in base units, and getting a convenient prefix. to_base_units() is not about getting a convenient prefix, but about getting the quantity in terms of base units (m, s, kg, A, K, mol and cd in the SI system). If you want a convenient prefix you may want to consider to_compact(): >>> print(x.to_base_units().to_compact()) 100.0 gram / meter ** 3
common-pile/stackexchange_filtered
How can I change all input values to uppercase using Jquery? I want to change all my form values to uppercase before the form is submitted. So far I have this but it's not working. $('#id-submit').click(function () { var allInputs = $(":input"); $(allInputs).value.toUpperCase(); alert(allInputs); }); allInputs.val().toUpperCase() Learn about .val() @LifeInTheGrey val() only gets the value of the fist element sorry, i should have put more context. if you're using jQuery, you should use jQuery .val() instead of vanilla JS .value. that's all i was trying to get across, sorry for the confusion. hence comment, not answer. Try like below, $('input[type=text]').val (function () { return this.value.toUpperCase(); }) You should use input[type=text] instead of :input or input as I believe your intention are to operate on textbox only. $(allInputs) should actually be $(":input"), no need to double $ use css : input.upper { text-transform: uppercase; } probably best to use the style, and convert serverside. There's also a jQuery plugin to force uppercase: http://plugins.jquery.com/plugin-tags/uppercase NOTE: this will just display the text in uppercase, it wont convert the values to be saved that way. @GustavoReyes as this answer says, you really need to do the conversion at the server anyway. You can't be certain that the client-side code will be run. $('#id-submit').click(function () { $("input").val(function(i,val) { return val.toUpperCase(); }); }); FIDDLE Use css text-transform to display text in all input type text. In Jquery you can then transform the value to uppercase on blur event. Css: input[type=text] { text-transform: uppercase; } Jquery: $(document).on('blur', "input[type=text]", function () { $(this).val(function (_, val) { return val.toUpperCase(); }); }); thanks i change the input[type="text"]..for class="uppercase"... works for me You can use each() $('#id-submit').click(function () { $(":input").each(function(){ this.value = this.value.toUpperCase(); }); }); "This works like a charm" until it comes across a select element.
common-pile/stackexchange_filtered
how to calculate offset.left position to display image on link hover I have a JavaScript function that when a user does a mouse-over a thumbnail, a larger preview of the image pops up. The JavaScript calculates the top and left offset position to either display the preview on the right or left of the screen, depending on the screen size. The function works when the object passed is an image. My goal is to use the same function as a template, and have it work but instead that using a thumbnail for the hover event, just use a link. So the user does a mouse over the link, and the image preview pops up. My problem is that the offset left position is not being calculated when using IE8 or IE11, Firefox and Chrome work fine. The image is always being displayed on the right size of the screen. But this only happens on IE. I guess, I am not sure, but perhaps IE treats the and tag differently to calculate offset? Here is a copy of the jquery function: function linkOverShow(a, strSKU) { $("#pUpImg").attr("src", "/images/items/" + strSKU + ".jpg"); var offset = $(a).offset(); if (offset.left - 350 < 0) { $('#pUp').css('top', (offset.top - 125)).css('left', (offset.left + 100)); } else { $('#pUp').css('top', (offset.top - 125)).css('left', (offset.left - 350)); } $("#pUp").show(); } On IE, the code only goes to the line: $('#pUp').css('top', (offset.top - 125)).css('left', (offset.left + 100)); I am hoping to fins someone in this forum that can offer some ideas as to why this is happening, and possibly offer some recommendations to try to solve the issue. I hope also I am asking this question correctly. Any help is greatly appreciated. Thank you much. How exactly off are they? A few pixels or millions and millions off? To test you should use the console and output it in there $('#pUp').offset(); When I use firebug on FF offset.left has 351.5.When in IE using the developer tools, offset.let contains 349 which makes the image be displayed 449 pixels to the right. This is when using a 1680x1050 monitor. Yep, this is sadly because the browsers handle elements different. So line-height: 10px will come out slightly differently on FF/Chrome to what IE does. Welcome to developing. My suggest, make sure you have a reset file in your CSS Hi Jamie, thank you for your reply. I am not sure what is a reset CSS file. Yes dealing with browser compatibility is a bit frustrating at times. This might help :) http://www.cssreset.com/ I don't think I can go this route. I think I will have to keep tweaking the function the route to go. Thank you for the recommendation though.
common-pile/stackexchange_filtered
How much amount of arbitrary data can be included in Beacon PDU? We're trying to emulate a beacon on a Android device and would like to include some 50 bytes of application data in payload? We found that with AltBeacon format this is not possible? How can it be done with help of AltBeacon lib for Android? Moreover, what are primary and secondary beacon advertisements? What is role of GattBeacon in this context and when and how should it be used? There are two basic types of BLE beacon advertisements: Manufacturer advertisements (iBeacon, AltBeacon, Gimbal) GATT Service Advertisements (Eddystone, UriBeacon, GattBeacon) They differ mainly by the bluetoorh PDU type, but in both cases the number of bytes that can be transmitted are similarly limited. It is 23 bytes for manufacturer advertisements (not counting the two byte manufacturer code). With Bluetooth 4.x, you just won't get close to 50 bytes in a single packet. Bluetooth 5.0 is expected to increase this at some point in the future. None of the beacon layouts let you go beyond this limit. GattBeacon is merely a generic example layout of a beacon based on GATT Service advertisements, and is not meant for practical use. What are primary and secondary beacon advertisement? When and how they should be used? I'm not sure what you mean by primary and secondary in this context. Can you point me to where you are seeing those terms used?
common-pile/stackexchange_filtered
How would I solve this ODE? My ODE looks as follows: $(f(x))^2 + f(x)f'(x) x = c$ Any ideas if or how I could solve this? I do know how to solve it for c=0 but Im not sure what the idea is for c $\neq$ 0 Thanks. $\textbf{Hint:}$ $$ ff' = \frac{1}{2}\dfrac{d}{dx}f^2 $$ does this help? $\textbf{update}$ $$ f^2 +xff' = f^2 +\frac{x}{2}\left(f^2\right)' = c $$ make the sub $v = f^2$ $$ \frac{x}{2}v' + v = c $$ thus solutions of the form $$ v = c + \frac{\lambda}{x^2} = f^2 \implies\\ f = \pm\sqrt{c + \frac{\lambda}{x^2} } = \pm\frac{\sqrt{cx^2+\lambda}}{x} $$ It doesnt help with the c right? I could do it with 0 instead of c. But how do you get rid of the c? You forgot the factor $x$ in the original ODE. yep of course. Silly me!!
common-pile/stackexchange_filtered
Using Postgre and MySQL Side by Side on a Mac I'm thinking of checking out Postgre and was curious: Can you run MySQL and Postgre simultaneously on a Mac? I'm currently using MAMP Pro, which includes PHP and MySQL. It would be cool if I could install Postgre on my laptop, create a Postgre database and duplicate some of my MySQL tables there. Then I could create a test page with connections to both databases (MySQL and Postgre) and post similar queries targeting Postgre and MySQL side by side. Would this be easy to do, or are there some technical challenges or dangers I should be aware of? It's usually abbreviated "Postgres". Yes, you can run both Postgres and MySQL on your Mac without conflicts. There are several ways install Postgres on a Mac. You can use a package manager like Homebrew or MacPorts. But the simplest seems to be to download it as a normal app and it should work with MAMP just fine.
common-pile/stackexchange_filtered
Start my soul-bolts "start my soul-bolts" (Melville, White Jacket) - an expletive by a 19th-century sailor. Rather specific, but maybe somebody can come up with an equivalent. (Where's the 'nautical' S.E. site, anyway?) Some context is needed. About to arrive home the speaker vows to stay ashore for the rest of his life. The expletive is similar to 'I'll eat my hat, if..." or rather "you bet!" Your soul bolts are those (metaphorical) thing that fasten your soul to your body. If you were to remove them or rip them out, your immortal soul would flee your body... aka you would die. He’s saying “if I’m lying, let God kill me here and now”. Start, I don’t know.. get moving, get initially loosened, somehow make more likely they’ll come free. Side note: there was a kind of punishment aboard ship involving being whipped by a special rope.. that rope was sometimes known as a starter (as in starting a horse with a whip), a teaser, or a toagy. Start also means to jump with surprise (be startled); in an old wooden ship the twisting of the timbers in a heavy sea always brought the risk that a bolt would spring out, and often that was noisy and frightening. I'd translate 'start' simply as 'break loose' or 'unfasten' and the expression as 'strike me dead, if...' (I ever set foot on a plank again). @A.Berg That is correct What are you asking? For somebody to explain what the term means—or for an alternative expression? If you're looking for an alternative expression, explain what you think the term means. @A.Berg Yes, as in ... and then it was that we discovered that they had belonged to a French schooner, in the same trade, which had started a plank, and had gone down like a shot, ... And he embarked, was suddenly attacked by some monstrous fish, probably a thorn-back whale, who gave it such a terrible stroke with his tail as started a plank. Robert Louis Stevenson deployed "shiver my soul" a few years later in Treasure Island
common-pile/stackexchange_filtered
using self-signed certificates with requests in python Situation : The target site (a pre-prod URL, say https://my-pre-prod-site.com/login, for example) is using a self-signed certificate. From the browser, the site is accessible over https without any issues (the self-signed certificate warning is suppressed by adding the certificate to the trust store in the browser) Problem Statement : A simple python script that makes a get call to the target site using requests fails with either of the below errors in different situations : requests.exceptions.SSLError: [Errno 0] _ssl.c:344: error:00000000:lib(0):func(0):reason(0) or requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) The simple script used (on the python prompt) is : import requests res = requests.get('https://my-pre-prod-site.com/login') **Things already tried ** I do NOT want to skip the ssl verification. Hence, verify = false is not an option for me. I have already used the below with the same error res = requests.get('https://my-pre-prod-site.com/login', verify = os.path.join(os.getcwd(),'test.pem') where test.pem is a pem file created by concatenating the output of the below commands in that order : openssl rsa -in ~/Desktop/CertPath/private.key -check and openssl x509 -pubkey -noout -in ~/Desktop/CertPath/certificate.pem The script is run from ~/Desktop/CertPath so getcwd() gives the right path to the certificate. I tried another test.pem file as well where the order of concatenation was reversed. It still throws the same error. Have tried passing the .pem file holding the public key and the .key file holding the private key, separately (individually) as well, with the same error as the outcome. Environment details if it helps OS - ElCapitan Mac Requests - 2.9.0 Python - 2.7.10 OpenSSL being used by Python - 'OpenSSL 0.9.8zg 14 July 2015' Note - The openssl version does not seem to be an issue. Because even with an updated version of openssl, the errors are the same - tested on Ubuntu with Python 2.6 that uses the Openssl 1.x As a workaround, maybe you can use Let's Encrypt? And your dev configuration will be closer to your prod. This question is old but In case someone wonders off here. You are putting the private key and public key in you test.pem. This is wrong. What verify param requires is certs which it can trust. res = requests.get('https://my-pre-prod-site.com/login', verify = os.path.join(os.getcwd(),'test.pem') The test.pem is supposed to contain the list of all the Trusted Certificates. But what you're providing in your test.pem is your public and private key. You're ~/Desktop/CertPath/certificate.pem file itself should go into it. Try this: res = requests.get('https://my-pre-prod-site.com/login', verify = '~/Desktop/CertPath/certificate.pem') In order to specify certificate for SSL verification you can use : requests.get('https://my-pre-prod-site.com/login', cert=os.path.join(os.getcwd(),'test.pem')) have tried that already. Does not work. The same error persists.
common-pile/stackexchange_filtered
Setting up liquibaseSchemaName for Liquibase with MS-SQL Server I am using Liquibase with SQL Server (Microsoft SQL Server 2016) and Spring Boot. By default, Liquibase uses the dbo schema for the databasechangelog and databasechangeloglock tables. However, I want to use a different schema for these tables. Here are my Liquibase properties in the application.properties file: spring.liquibase.enabled=true spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml According to the documentation, liquibaseSchemaName properties can be used to set a specific schema name, but it doesn't work in the application.properties file. Is there a way to specify the schema where Liquibase creates the databasechangelog and databasechangeloglock tables? Aside... mainstream support for SQL Server 2016 ended three years ago and extended support will end in 2026. You should already be migrating your applications to a newer version. Have you looked into spring.liquibase.default-schema and spring.liquibase.parameters.schema yet? yep, We are on migration process. Liquibase integration is already part of migration to SQL Server 2019. I can't override spring.liquibase.default-schema for sql server, it always chooses dbo schema which is the default schema of connection also spring.liquibase.parameters.schema parameter is not working.
common-pile/stackexchange_filtered
Divided party on a deserted island My gaming group (and some NPCs) are shipwrecked on a deserted island. I'd like the characters cooperate to survive in this hostile environment, because I want to make the game world really dangerous (so they have to cooperate or die). But two players ("lone wolves") have broken away from the group and entered the jungle alone. Now, I have always encouraged the betrayal and division among the players, but not so soon. If I offer to these "lone wolves" challenges appropriate to their abilities, they hardly feel the need for a group. But if I do otherwise, they will likely die at 1st level. Furthermore, I will have to tell two stories in the same session. Does anyone have any suggestions? I have to force the meeting of the two groups or leave the "lone wolves" to die in the jungle. why did they split off? Don't answer in comments. Show the "lone wolves" exactly how dangerous it is. Have one of the them stumble into a trap-like jungle plant. (Imagine something like a giant Venus Flytrap or a Hangman's Tree.) Make it so that the character CANNOT escape by themselves, but the plant can't kill them quickly. Maybe it dissolves a held character for 1d4 hp every minute (rather than every round). Maybe it has to kill by suffocation. The point is, they know they are stuck and can't escape, but they have some time. As the character is thrashing around in vain and yelling for help, the rest of the party comes to the rescue. (You could even have the other lone wolf character hear the struggle and join in.) Together, all the PCs can take down the menace. Hopefully, that gives the recalcitrant players the hint that they have to work together or they will die. You could also use a group of creatures (like apes or actual wolves) that are too scared to attack a large party, but will gladly pick off lone stragglers. Alternatively, maybe one of the lone wolves stumbles on the den of a large creature (say an Ogre, Giant, Dragon etc.) that's certain death for everybody on the island, unless they work together to kill it. The pack animals is a great idea. They're only 1st level? Well then, they won't be set back by much compared to the other PCs when they die. Kill 'em! Well, not deliberately, but do let the jungle be deadly enough to pose the level of threat you've already decided on, and let the "tough lone wolf" types die if they take on challenges they can't handle and the dice kill them. If they survive, great, if not, not much loss. Build up the danger as they progress, though, by telegraphing the the threats before they're unavoidable. A player is much more likely to accept a death that they deliberately, knowingly courted than one that just pounces out of a tree and eats their head without warning. When they make fresh characters (other shipwreck survivors that washed up on a different, nearby shore), perhaps they won't make lone-wolves this time. I don't think you even need to telegraph over-much. Like, what do you expect when you've been shipwrecked on a jungle island and leave the group? Have you tried talking to the 'lone wolf' players out of game? If you didn't make it clear to the group that you would be expecting them to work together as a group (especially if, as you say, you've stuck to a policy of encouraging inter-party strife in previous games), they might not be aware of your expectations. It's generally a good idea before starting a game that the GM informs the players "Right, the premise of this scenario is that you'll be volunteering to help save some people out of a sense of civic obligation - so, no Chaotic Evil characters, alright?", or "This scenario assumes that you're the crew of a merchant ship, so make sure your characters know how to swim, or have some sort of suitable skill set." etc. If you're running a game that sets specific expectations to the player characters, it's always better to make it clear up front, so the players can make their characters accordingly. Failing that, take the players in question aside and explain the situation. Chances are that they'll be willing to either adjust their characters' attitude, or roll up new ones. Or, if they insist on playing loners, then suggest that A) their odds of survival in-game will be tragically low, and B) the game will suffer if you're forced to split your attention between two or more permanent fractions. Suggest that they could stay with the main party, but play up their loner personalities, and let it influence their interactions with the other characters. Perhaps they could lead scouting parties into the jungle, or go on their own. Assuming that these characters have suitable wilderness survival skills (hunting, tracking, foraging, stealth etc.), they could spend a lot of time skirmishing through the undergrowth, going on hunting trips and bringing back food and supplies that'll keep the group alive. Unless they're playing city-dwelling urbanite wizards, who've never stepped foot outside their ivory tower before. In that case, they're just screwed. On a related note: What alignment are the characters in question? If they're any kind of Lawful or Good, and their wilderness survival skills are vastly to those of the members of the main group - this is presumably the case, since they feel confident enough to go off on their own - you should gently point out to them the moral implications of leaving the 'big city folk' on their own, without anyone to help them survive in the jungle. Maybe you could suggest that, if they're really keen on trying to survive on their own, that you could play a different game at a later occasion, something that is designed to allow the players a chance to survive independently. There are several story-telling indie RPGs that would be much better suited for this sort of endeavour, or perhaps a board game or a tactical miniatures wargame. You may want to introduce troupe-style play where the players have their main character and a series of minor characters (typically represented as NPC classes). You can thus "split the party" by having some PCs lead these minor characters as they do certain tasks: scout, gather water/ fire wood, build shelter. The main PC would be someone better and more important while the NPCs assist. Killing one of these NPCs will not hurt the PCs as badly, but players will learn how dangerous it is. You just need to rotate the attention from one group to another. If the PCs decide they will stay together, run a group of these weaker characters together, they will quickly understand the dangers. This also gives you a series of ready-made replacements characters the players already know. "With the death of Sir Jon, squire Timmy really stepped up." Let them make their own story as they go, if their lone wolves they more than likely don't like working with the group for a reason. Just make sure the encounters are hard enough and that all the people are having fun.
common-pile/stackexchange_filtered
Disabling Custom Appearance For MFMessageComposeViewController When the user inputs a name into the recipients portion of MFMessageComposeViewController, the recipients bar, turns black and vanishes. The user can still send a message, input text and do all the other stuff, they just can't see the recipients bar. I have a feeling that this may (or may not) be because the navigation bar of the MFMessageComposeViewController is customized (background image and custom font). 1. My navigation bar's custom appearance is set for the entire app, how do I disable it for the MFMessageComposeViewController? 2. Could there be any other reason for this glitch? Is it an iOS7 bug? So yes, the problem here was because I was using the UIAppearance proxy for UINavigationBars. So what solved this problem? Rather than trying to change MFMessageComposeViewController, which is more of an app on its own, I customized my own app. Rather than using [UINavigationBar appearance], I used [UINavigationBar appearanceWhenContainedIn:[SomeNavigationController class], nil] I think this is really simple if you can do this, because trying to customize MFMessageComposeViewController can be pretty annoying. Everything above applies for MFMailComposeViewController. i cant change the text color, i tried doing this: [[UINavigationBar appearanceWhenContainedIn:[MFMailComposeViewController class], nil] setBarTintColor:[UIColor whiteColor]]; [[UIBarButtonItem appearanceWhenContainedIn:[MFMailComposeViewController class], nil] setTintColor:[UIColor whiteColor]]; [[UIBarButtonItem appearanceWhenContainedIn:[MFMailComposeViewController class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal]; I don't think iOS allows you to change the colour of the MFMailComposeViewController (since it is a system-based view controller) directly using appearanceWhenContainedIn I faced same problem and here is my solution- Before presenting your message composer( [self presentViewController:messageComposer animated:YES completion:nil]; ) set [[UINavigationBar appearance] setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; and in delegate method - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result { UIImage *backgroundImage = [UIImage imageNamed:@"Navigation Bar"]; [[UINavigationBar appearance] setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault]; [self dismissViewControllerAnimated:YES completion:nil]; } Thats all!!
common-pile/stackexchange_filtered
Android BufferedReader.Read(CharBuffer target) I have a problem with the BufferedReader in Android. I am sing a server to receive and send data. For the receiving, I use a BufferedReader and the method Read(CharBuffer target). As long as I receive simple Strings there is no problem. But if I receive a sequence like: 0xEB 0x58 0x35 0x3F 0x82 0x3A 0xCC 0x66 0x6F 0x6C ...every Byte which has the highest bit set appears in the CharBuffer as 0xFFFD. Any idea why this happens? Sounds like encoding/endianess issues http://en.wikipedia.org/wiki/Endianness http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html To solve the problem I decided to get the data from the socket directly using client.getInputStream().read(bytebuf) where clientis the socket object receiving the data.
common-pile/stackexchange_filtered
Did George Biddell Airy write a paper "On Certain conditions under which a Perpetual Motion is possible"? George Biddell Airy was an English mathematician. He was Astronomer Royal from 1835 to 1881 According to the Bessler Wheel web-site (a site dedicated to investigationg perpetual motion machines, Airy wrote the paper titled On certain Conditions under which a Perpetual Motion is possible, published in Cambridge Philosophical Transactions, December 14, 1829. They provide scans of the paper: It is well known that perpetual motion is not possible with any Laws of force with which we are acquainted. The impossibility depends on the integrability per se of the expression Xdx + Ydy + Zdz: and as in all the forces of which we have an accurate knowledge this expression is a complete differential, it follows that perpetual motion is incompatible with those forces. But it is here supposed that, the law of the force being given, the magnitude of the force acting at any instant depends on the position, at that instant, of the body on which it acts. If however the magnitude of the force should depend not on the position of the body at the instant of the force's. action, but on its position at some time preceding that action, the theorem that we have stated would no longer be true. It might happen that, every time that the body returned to the same position, its velocity would be less than at the preceding time: in this case the body's motion would ultimately be destroyed. On the contrary it might happen, that the body's velocity in any position I am skeptical that this was originally written by Airy because of its impenetrable style and it is apparently nonsense. Was this paper written by Airy? The claim that George Biddell Airy wrote a paper titled “On certain Conditions under which Perpetual Motion is possible” which was published in the Transactions of the Cambridge Philosophical Society is true. The full text of the (short) paper can be read on Google Books. The claim that this is a “rigorous mathematical proof of the theoretical possibility of perpetual motion” is a stretch. Airy's paper is an investigation into a mathematical model. Airy does not claim that perpetual motion is physically possible. He merely investigates under what conditions one particular mathematical model would lead to a situation where a “machine might move with uniform velocity, and might at the same time do work: which is commonly understood to be the meaning of the term perpetual motion”. Note that this isn't exactly what perpetual motion means in modern terms: perpetual motion is about creating energy. Airy's definition only takes some forms of energy into account (kinetic energy in the motion of the machine, and the “work” performed by the machine, but not necessarily, for example, electromagnetic forces). Airy analyses a physical system and states that it obeys a certain mathematical equation. He analyses the possible solutions and concludes that, under a certain assumption (“on the supposition that g is small”) I shall only remark that if c√e be less than π, the arc of vibration increases continually. Airy does not claim that it is physically possible for c√e to be less than π and that this would be compatible with the assumption that g is small. Furthermore, even if the arc of vibration increases continually, this might not be perpetual motion. It is possible that the analysis was missing some of the forces through which energy can be transferred. Airy does not clearly state whether he believes that the analysis of forces is complete. "Airy does not claim that perpetual motion is physically possible." As I expected... But the style of the paper is (I will say it again) impenetrable. And the “rigorous mathematical proof of the theoretical possiblity of perpetual motion” is... [insert here some appropriate adjective]. @Martín-Blas Pérez Pinilla: "Impenetrable style" is perhaps an artifact of the reader. I find the quoted excerpt quite clear, at least as academic writings go. @Martín-BlasPérezPinilla how many academic papers from ~1830 have you read? Academic writing tends to be dense even today, and going further back in time tends the make the language even more flowery/dense/odd @mbrig, none! See my comment -> Nate Eldredge. Giles, I've posted a question in Physics SE. The c√e assumption is not so remarkable, and it is mostly saying that the driving force does not depend on something too far into the past (assuming a periodic-ish solution, that it only looks up to a half of a cycle in the past). The much bigger assumption is that there is a way for a system to have a force proportional to a previous position -- likely it takes external energy to apply a force like this through time. I have a short analysis over at https://physics.stackexchange.com/a/555549/265876 Airy's official autobiography, edited by his son Wilfrid and published in 1896, contains an appendix listing every paper that Airy ever published, along with when and where he published them. On certain Conditions under which a Perpetual Motion is possible is listed partway down page 374: So yes, George Biddell Airy really did write that paper. This doesn't mean that he believed perpetual motion was actually possible - he said as much at the start of the section you quoted: It is well known that perpetual motion is not possible with any Laws of force with which we are acquainted. By "certain conditions", he's referring to hypothetical changes to the Laws of forces, not to any actual real-world force. Looking at the excerpt quoted in the question, it is entirely possible that the paper is abn investigating in to the mathematical forms of laws that could lead to perpetual motion, rather than a claim that any such laws actually exist or are possible. I don't know what the paper actually says, but a conclusion of "perpetual motion requires forces with these properties, and electromagnetism doesn't have those properties, so you can't get perpetual motion using electromagnetism" could well be consistent with the title. Thanks for your effort. I will accept the other answer because is more focused on my doubts. @PhillS actually electromagnetism has these kinds of forces (only the backreaction prevents perpetual motion). Note that Airy does not claim that perpetual motion is possible - it seems he's just having a bit of fun playing with the math to see what would have to happen to allow perpetual motion. I must confess that I didn't actually read the paper - it wasn't necessary to do so in order to establish whether Airy wrote it, which was OP's primary concern. I've heavily revised the last section of my answer to properly address its contents, as per your comments.
common-pile/stackexchange_filtered
how to prevent data from sending if user press F5 or refresh in asp.net? I had asp.net form app I have a bug when the user click F5 or refresh it will enter the data from last data entry .is their is away to Prevent sending data if user click click F5 or refresh? @aelnajjar at least look before here! http://stackoverflow.com/questions/3759572/avoid-form-re-submit and http://stackoverflow.com/questions/2526568/asp-net-prevent-form-submission-twice this has been asked so many times! It's easy to reset a page to it's initial state in ASP.NET by redirecting to itself. Here are 3 ways you can do it: Response.Redirect(Request.Path); In which the path to the request is presented in the following form: /MyApp/MyFile.aspx Response.Redirect(Request.RawUrl); In which not only is the path exposed, but also any querystring parameters like: /MyApp/MyFile.aspx?foo=bar Response.Redirect(Request.Url.ToString()); In which not only is the path and querystring parameters exposed, but made available as an absolute reference in the form: MyServer/MyApp/MyFile.aspx?foo=bar A common solution to this is called Post Redirect Get (PRG), where the browser is immediately redirected to a HTTP Get page after any post. See Post Redirect Get in asp.net for a web forms implementation. There are multiple ways to prevent this from happening. The simplest is to Response.Redirect to a another page, which can be refreshed without consequence. // process form post Response.Redirect("anotherpage.aspx");
common-pile/stackexchange_filtered
Change background image opacity on hover in angular and scss i have angular component with dynamic background-image fetched from server: <div class="picture" [style.background-image]="'url(' + this.category.photo + ')'" > <div class="seeDetails"> join group <button>see details</button> </div> </div> After putting mouse over .picture class .seeDetails appear with text and button inside it, in CSS it looks like this: .picture { width: 400px; height: 300px; } .seeDetails { display: none; } .picture:hover { opacity:0.2; .seeDetails { display: block; animation-name: fadeIn; animation-duration: 0.5s; } @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } i want to set background image opacity to 0.2 after hover, but it also set text and button opacity to 0.2. I have read about solution with pseudoelement ::before https://coder-coder.com/background-image-opacity/ but i can't figure out how to use it in this case with :hover. Does this answer your question? How do I give text or an image a transparent background using CSS? (There is a little bit simpler solution with ::before/::after, but you would have to move the dynamic background url to css to make it work.) You should have: <div class="container"> <div class="background" [style.background-image]="'url(' + this.category.photo + ')'"> </div> <div class="seeDetails"> join group <button>see details</button> </div> </div> div.container { position: relative; > div.background { position: absolute; inset: 0; background-size: cover; } &:hover > div.background { opacity: 0.2; } > div.seeDetails { display: block; animation-name: fadeIn; animation-duration: 0.5s; } } Note: inset does not work everywhere. You should create a mixin: @mixin inset($size: 0) { inset: $size; top: $size; left: $size; right: $size; bottom: $size; } And use it as: div.container { // ... > div.background { position: absolute; @include inset(0 !important); background-size: cover; } // ... } this works! but now fade in animation stopped working
common-pile/stackexchange_filtered
Golang create multireader of bytes.Buffer array I need Create MultiReader of slice []*bytes.Buffer buffer_slice := ... (type []*bytes.Buffer) When i write io.MultiReader(buffer_slice) I get the error: cannot use buffer_slice (type []*bytes.Buffer) as type io.Reader in argument to io.MultiReader: []*bytes.Buffer does not implement io.Reader (missing Read method). But function signature MultiReader(readers ...Reader) Reader I understand that the transmit array is meaningless, the actual question: besides the trivial cycle, there are no more options? P.S. Sorry for my bad english. See https://golang.org/doc/faq#convert_slice_of_interface. The types are different, but the reasons are the same. Your slice should be type []io.Reader b1 := &bytes.Buffer{} b2 := &bytes.Buffer{} buffers := []io.Reader{b1, b2} multi := io.MultiReader(buffers...) Thanks for the advice, now everything is fine!
common-pile/stackexchange_filtered
Does Debug.LogAssert gets deleted in Unity once I build the game? Does Debug.LogAssert(expression) gets deleted in Unity once I build the game? I was not able to find it here. I feel like it should get deleted, but still I can not assure myself in it (no reliable source was found by me). So, I would be grateful for the source provided which would assure me in it or point me out, that it is not the case. Yes, Debug.Assert gets removed from non-development builds by default. It's possible to change this setting - see the Unity documentation on BuildOptions.ForceEnableAssertions: BuildOptions.ForceEnableAssertions Include assertions in the build. By default, the assertions are only included in development builds. As a side note, there are also interesting posts here with varied opinions on whether asserts should be included with a release build: When should assertions stay in production code? and Should there be assertions in release builds
common-pile/stackexchange_filtered
ubuntu 13.04 cant read windows 8 partition anymore I freshly installed ubuntu 13.04 on my Windows 8 PC. Dual booting it, I created a symbolic link while on ubuntu to my windows based Dropbox directory. The link worked fine while the computer was still on. I shut it down normally with a full shut down and when I turned it back on and it booted automatically into ubuntu, it didn't work anymore. I could no longer read the windows partitions and the link wasn't working. The error message I got said that it was because Windows was not shut down properly. I rebooted into windows and turned it off again to test it, but it didn't work. Any ideas what went wrong? My guess is that the partition for windows 8 isn't mounted. If it's not mounted, you can't access it. You can test this out by opening nautilus and clicking on the drive for windows 8 and then trying the link you made. You'll need to mount that partition every time you turn on your computer or create a script to run everytime on boot to mount that parition.
common-pile/stackexchange_filtered
How to get value with JXPathContext if xmlns specified? final SAXBuilder builder = new SAXBuilder(); final Document xml = builder.build( file ); final Element root = (Element) xml.getRootElement(); Element child = root.getChild("Header", Namespace.getNamespace("http://www.editeur.org/icedis/claims")); final XPathContext ctx = XPathContext.create(root); This is the code I have. XPathContext is just wrapper around JXPathContext. As you see, 'child' variable using construction with Namespace and it won't work if I remove it. But now I'm trying to get value from XML with XPath like this ctx.getValue("/Header/SentDateTime") And, ofcourse it always return null. It seems that solution is simple, but I can't find it in the internet. If I delete xmlns from XML file, everything will work, but this isn't an option. So how should I work with this xml? Also, short version of XML file: <?xml version="1.0" encoding="UTF-8"?> <ICEDISClaimMessage version="0.1" xmlns="http://www.editeur.org/icedis/claims"> <Header> <Sender> <SenderIdentifier> <SenderIDType>06</SenderIDType> <IDValue>1234567890128</IDValue> </SenderIdentifier> <SenderName>Apogee Agency</SenderName> </Sender> <Addressee> <AddresseeIdentifier> <AddresseeIDType>06</AddresseeIDType> <IDValue>2345678901237</IDValue> </AddresseeIdentifier> </Addressee> <MessageNumber>111</MessageNumber> <SentDateTime>20101001</SentDateTime> <MessageNote>Sample file 1: a claim made by an agent to a publisher for a journal issue not yet delivered</MessageNote> </Header> </<ICEDISClaimMessage> You need to use an XPath expression with a namespace context. It would have to look something like this: final XPathContext ctx = XPathContext.create(root); ctx.addNamespaceMapping("ns", "http://www.editeur.org/icedis/claims"); ... = ctx.getValue("/ns:Header/ns:SentDateTime"); NB: I don't know whether JXPath supports namespaces, and if it does, how it is set up. And, by the way, it looks like you are using JDOM (SAXBuilder). In that case I would recommend using the JDOM built in XPath functions instead of building a wrapper.
common-pile/stackexchange_filtered
my security code for php profile user and admin script i use the session hash code that represent the user_agent and user_ip also i use session_set_cookie_params to set remember in login script . How is my security status ? and it is not better to use setcookie instead set_session_cookie_params in remember me ? What features should I use for better security ? sorry for my bad english horrible security... consider a million AOL users, all coming from the same NAT gateway, all running the same version of the aol browser, all getting the exact SAME session hash... An IP address does not uniquely identify a user. How is my security status? -- Bad. Second part ?? , how is the security situation? setcookie or set_session_cookie_params ? What is your suggestion for the improvement of security ? If I use a crypt for the session and will then be recorded in a database and for remember me also use a random crypt ، in this situation ، Now how about the security situation ? As mentioned in the comments, you don't really have a secure setup going on. There are endless things to account for regarding security, but a good start would be to account for the following: Session Hijacking / Fixation SQL Injection XSS (Cross-Server Scripting) Brute Force attacks A good beginner resource at first would be to check out phpacademy. I've linked this a couple times also. I think it's a decent example of a PDO login system, which will help you avoid SQL Injection Attacks. Assuming you have access to your php.ini file, you may want to look into what these commands do. They may or may not fit your needs, but they can be helpful to avoid Session Hijacking / Fixation by not allowing the PHPSESSID variable to be passed via URL and also making it inaccessible via JavaScript. session.use_only_cookies = 1 session.cookie_httponly = 1 session.use_trans_sid = 0 Brute Force attacks can be mitigated by using proper hashing. To Look into bcrypt or scrypt for more detail. You can also check out this discussion for a little more information on this. I've already done all the things you said, I just want to know three things: 1 . for Remember me what function should be used for, Setcookie or session_set_cookie 2 .And that for security reasons, do not use the crypt for a cookie or to use 3 .I use the crypt for session and I generated the session to database or not . Not that simple, see this. 2) The PHPSESSID generated is already a random set of numbers, so using crypt on it isn't really going to increase security much. Instead, look into SSL and create a "secure cookie" if there is a lot of sensitive data going on. I'm not sure I understand your 3rd point... If you're talking about storing the Session id in the database, then that's not necessary. The session id validates a user machine to the server. for 3 ، i talk about session_hash ? If you use session_start(), it automatically generates the cookie named PHPSESSID with a high-entropy value. You don't have to create a session hash value yourself. i convert phpsessid to my session_name . If you're creating variables you'll have to elaborate on their purpose. I imagine you mean you created a session variable like $_SESSION['session_name']. What do you use this variable for? i mean session_name();
common-pile/stackexchange_filtered
Headless Browser and scraping - solutions I'm trying to put list of possible solutions for browser automatic tests suits and headless browser platforms capable of scraping. BROWSER TESTING / SCRAPING: Selenium - polyglot flagship in browser automation, bindings for Python, Ruby, JavaScript, C#, Haskell and more, IDE for Firefox (as an extension) for faster test deployment. Can act as a Server and has tons of features. JAVASCRIPT PhantomJS - JavaScript, headless testing with screen capture and automation, uses Webkit. As of version 1.8 Selenium's WebDriver API is implemented, so you can use any WebDriver binding and tests will be compatible with Selenium SlimerJS - similar to PhantomJS, uses Gecko (Firefox) instead of WebKit CasperJS - JavaScript, build on both PhantomJS and SlimerJS, has extra features Ghost Driver - JavaScript implementation of the WebDriver Wire Protocol for PhantomJS. new PhantomCSS - CSS regression testing. A CasperJS module for automating visual regression testing with PhantomJS and Resemble.js. new WebdriverCSS - plugin for Webdriver.io for automating visual regression testing new PhantomFlow - Describe and visualize user flows through tests. An experimental approach to Web user interface testing. new trifleJS - ports the PhantomJS API to use the Internet Explorer engine. new CasperJS IDE (commercial) NODE.JS Node-phantom - bridges the gap between PhantomJS and node.js WebDriverJs - Selenium WebDriver bindings for node.js by Selenium Team WD.js - node module for WebDriver/Selenium 2 yiewd - WD.js wrapper using latest Harmony generators! Get rid of the callback pyramid with yield ZombieJs - Insanely fast, headless full-stack testing using node.js NightwatchJs - Node JS based testing solution using Selenium Webdriver Chimera - Chimera: can do everything what phantomJS does, but in a full JS environment Dalek.js - Automated cross browser testing with JavaScript through Selenium Webdriver Webdriver.io - better implementation of WebDriver bindings with predefined 50+ actions Nightmare - Electron bridge with a high-level API. jsdom - Tailored towards web scraping. A very lightweight DOM implemented in Node.js, it supports pages with javascript. new Puppeteer - Node library which provides a high-level API to control Chrome or Chromium. Puppeteer runs headless by default. WEB SCRAPING / MINING Scrapy - Python, mainly a scraper/miner - fast, well documented and, can be linked with Django Dynamic Scraper for nice mining deployments, or Scrapy Cloud for PaaS (server-less) deployment, works in terminal or an server stand-alone proces, can be used with Celery, built on top of Twisted Snailer - node.js module, untested yet. Node-Crawler - node.js module, untested yet. ONLINE TOOLS new Web Scraping Language - Simple syntax to crawl the web new Online HTTP client - Dedicated SO answer dead CasperBox - Run CasperJS scripts online Android TOOLS for Automation new Mechanica Browser App RELATED LINKS & RESOURCES Comparsion of Webscraping software new Resemble.js : Image analysis and comparison Questions: Any pure Node.js solution or Nodejs to PhanthomJS/CasperJS module that actually works and is documented? Answer: Chimera seems to go in that direction, checkout Chimera Other solutions capable of easier JavaScript injection than Selenium? Do you know any pure ruby solutions? Answer: Checkout the list created by rjk with ruby based solutions Do you know any related tech or solution? Feel free to edit this question and add content as you wish! Thank you for your contributions! dont know if thats what you want, but i like that module for crawling webpages, inspecting the dom and so on: https://npmjs.org/package/crawler. it uses jsdom, and you can jQuery as selector-engine. this one (which uses crawler) looks interesting too: https://npmjs.org/package/snailer I've had a lot of success with the node-phantom module. It's pretty straight forward and fairly well documented. It does support javascript injection. I am sure you are aware that GhostDriver is an implementation of Selenium-Webdriver that uses phantomJS You might also find this helpful: http://blog.screen-scraper.com/2010/06/28/comparison-of-web-scraping-software/ For visual scraping and comparisons: PhantomCSS and PhantomFlow Webdriver.io also has a CSS regression plugin called WebdriverCSS for visual scraping and comparison http://github.com/briankircho/browserjet Check this out, https://github.com/christian-bromann/awesome-selenium I'm working on https://testingbot.com which has all the latest and older browsers, you can use selenium webdriver and test on any browser you like There's also a list of solutions at https://github.com/dhamaniasad/HeadlessBrowsers USE import.io . This one is really cool - https://github.com/graphcool/chromeless If Ruby is your thing, you may also try: https://github.com/chriskite/anemone (dev stopped) https://github.com/sparklemotion/mechanize https://github.com/postmodern/spidr https://github.com/stewartmckee/cobweb http://watirwebdriver.com/ (Selenium) also, Nokogiri gem can be used for scraping: http://nokogiri.org/ there is a dedicated book about how to utilise nokogiri for scraping by packt publishing watir is a thousand times easier than the libraries above. For python "webbot" library offers rich features for easy web automation. http://triflejs.org/ is like phantomjs but based on IE While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. That sounds good normally, yet this question is itself a collection of resources. A link with a short description to be incorporated in the list fits the format and makes sense. A kind of JS-based Selenium is Dalek.js. It not only aims for automated frontend-tests, you can also do screenshots with it. It has webdrivers for all important browsers. Unfortunately those webdrivers seem to be worth improving (just not to say "buggy" to Firefox).
common-pile/stackexchange_filtered
Unable to get a list by name with a hyphen Trying to upload a file to a folder in a SP Online where the title is "Forms - May" and set some of the fields. I can't seem to get the list or any of the fields. The list and the folder definitely exist. I can get other lists and folders without hyphens which is why I'm assuming this is the problem - is there a special way I need to handle this? I have tried to load the list into the client context which also breaks it. The specific error occurs when I try to get the fields in the list. This is wrapped in a try/catch and the exception I get is File Not Found Web web = clientContext.Web; List forms = web.Lists.GetByTitle("Forms - May"); string destination = "Forms - May/Folder1"; FileCreationInformation flciNewFile = new FileCreationInformation(); var targetFolder = clientContext.Web.GetFolderByServerRelativeUrl(dest); var uFolder = targetFolder.Files.Add(flciNewFile); Microsoft.SharePoint.Client.File uploadFile = targetFolder.Files.Add(flciNewFile); var listItem = uploadFile.ListItemAllFields; Field field = forms.Fields.GetByInternalNameOrTitle("FieldInternalName"); clientContext.Load(field, f => f.TypeAsString); clientContext.ExecuteQuery(); //breaks Does encoded list name work? i.e. Forms%20-%20May The error was in the destination. Editing the following lines worked: List forms = web.Lists.GetByTitle("Forms - May"); string destination = "Forms May/Folder1"; //kept 2 spaces Looks like you can have a hyphen in the folder though... The following also works List forms = web.Lists.GetByTitle("Forms - May"); string destination = "Forms May/Folder1 - May"; Hi @cooper If you solved the problem stated in your original question, you should mark this answer as accepted answer to help future visitors. Hi @cooper i'm facing the same issue , cant able to add - symbol in folder name as well as cant get the folder by serverrelativeurl where the folder has the - symbol , i tried your code but it doesn't help me out can you give the clear idea on this
common-pile/stackexchange_filtered
my javascript file will not link to my index.html file and i see nothing wrong with it. What is wrong with it? here is my index= https://github.com/25garcial/calculator/blob/main/index.html here is my JavaScript= https://github.com/25garcial/calculator/blob/main/script.js I don't know what is wrong with the code and i have asked my teacher and he does not know either. Always check the browser console for errors before posting questions. You never defined a g variable, so an error is thrown and none of the JS runs. You also might consider looking for a new teacher if he/she was not able to spot this trivial (and easily debugged) problem. Replace script tag in your index file with this : <​script​ ​src="​script.js​"​>​</​script​> At the bottom of the body tag in index.html file link your Javascript file with a script tag: <script src="./yourfilename.js"></script> To link your script try using: <script src="script.js"></script> For more informations see : https://www.w3schools.com/tags/att_script_src.asp Also note: You can use the defer attibute if you want your script to load after the HTML parsing and loading rather than putting it at the end of your body. <script src="script.js" defer></script>
common-pile/stackexchange_filtered
Issue with initial focus while scanning QR-code with ZBar I created an app which uses ZBar to scan QR-codes. While testing I noticed that there are problems with auto-focus. When I aim my iPad at a QR-code prior to starting the scan, it shows a green rectangle around the QR-code and it doesn't scan. I need to reaim the iPad on another object to focus on, and then aim back at the QR-code. If I don't aim at a QR-code prior to scanning it works. I just need to aim at the QR-code from the moment the Zbar view is launched. I'm using minimum iOS 6 and iPads 2 and 3. I used the code as described on the website of ZBar so nothing special to note there. I'm thinking that it's a problem with ZBar itself. Are there other people experiencing this problem or have a solution for this? actually I never found a solution. The solution provided is to check it on other devices. I don't have other devices and knowing it works on other devices doesn't really solve the problem :). imeet your same problem,ithink it is not device reson,ithink the lib have problem @Stephan Celis I also phase this type of problem ... good question. :) If you got solution then share it. I think it's a bug in the library of ZBar. Didn't find a solution though @Stephan Celis Thanks for Replay Did you try it on some other iPad devices? Maybe it's problem only with your iPad. What about iPhone? My scanner is also based on Zbar - https://itunes.apple.com/us/app/qr-scan/id568762816?ls=1&mt=8 you can try it if it works as you want.. We were facing same issue with Zbar, we solved it by putting a 2 sec delay before dismissing model view.
common-pile/stackexchange_filtered
Terrence Tao Real Analysis exercise: Prove that all Cauchy sequences $(a_n)$ are bounded I've been struggling for one and a half hours trying to think of a proof for this Lemma, I haven't made any progress at all. It's in Terrence Tao's lectures notes for his Real Analysis course (week 2, lemma 9). "Prove that all Cauchy sequences $(a_n)$ are bounded". If any could give me a hint that would be really helpful, thanks.In particular, something I am having an issue with is that most proofs I have seen involve the Max function which hasn't been defined by Tao yet.This makes me think it's not the easiest way of doing it. Since $(a_n)$ is cauchy, there exists some $n \in \mathbb N$ so that $d(a_n,a_m)<\epsilon$ for all $m \geq n$, in which case $a_m \leq a_n \pm \epsilon$ for all $m \geq n$. So, either the the sequence is bounded by the maximum/minimum of the first $n$ elements of the sequence, or it is bounded by $a_n \pm \epsilon$
common-pile/stackexchange_filtered
Network extension log I have sample Go example like this: import "github.com/jedisct1/dlog" func Hi() { dlog.Init("HI", dlog.SeverityNotice, "DAEMON") dlog.Noticef("Hi ") } I build this project to with Go mobile, and call it from an iOS app, and everything is OK. I can see log in debug panel of Xcode. But when I link it with network extension and call the 'hi' function, I can't see any thing in console or xcode debug panel. How can I show logs when build Go framework to iOS and run in network extension? The logs from Network extensions do not go to Xcode console. to see the logs from Network extension you have to follow the bellow steps. 1. Open the console application. 2. Select your iOS device running the network extension you will see all the logs from your device. 3. Filter the logs by Network extension target name now you will see the logs only from your network extension. Thank you, this is very helpful for my debugging. Just a quick note, remember to use OSLog instead of print so that you can see the logs in the console application. Note: Only log levels notice, warning, error, fault, and critical in OSLog will be displayed in the console, while debug, info, and trace won't.
common-pile/stackexchange_filtered
iOS 7 UISearchBar UISearchBarIconSearch I am having an issue with iOS 7. The code [searchBar setImage:[UIImage imageNamed:@"icon_search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; brings different icon sizes on iOS 6 and iOS 7. The image size is 29x29 and 58x58@2x and under iOS 6 it's displayed properly, but in iOS 7 it's twice or even more times smaller. What could be the issue? Thanks! Have you found a solution to this? I'm facing the same issue this seems to work for me: UIImage* image = [UIImage imageNamed:@"icon_search"]; [[UIImageView appearanceWhenContainedIn:[UISearchBar class], nil] setBounds:CGRectMake(0, 0, image.size.width, image.size.height)]; To customize UISearchBarIconSearch you need the following code: [yourSearchBar setImage:[UIImage imageNamed: @"yourImage.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; To properly change the icon the resolution image must be exactly: 14x14, 28x28 for @2x and 42x42 for @3x. I hope this helps :) After facing some problems with UISearchBar in iOS 7, I decided to switch to UITextField due to the placeholder text alignment. But I still managed to get it work by setting the image for UISearchBar and it's textfield. UITextField *textfieldField = [searchBar valueForKey:@"_searchField"]; [searchBar setImage:[UIImage imageNamed:@"icon_search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; UIImage *whatSearchImage = [UIImage<EMAIL_ADDRESS>UIImageView *whatSearchView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 29, 29)]; whatSearchView.image = whatSearchImage; textfield.leftViewMode = UITextFieldViewModeAlways; textfield.leftView = whatSearchView; Funny thing, if you don't set the image for the UISearchBarIcon it will use the default one from Apple but make it big. I would also like to see if someone has found a better solution for this. don't know if it's the best solution, but it works like a charm How would you switch the view on one side when the mode is different? Example: you want a certain image on the rightView when the mode is whileEditing, and you want a different image for the same rightView when the mode is unlessEditing ? I had the same problem, then I made size for search icon smaller and everything is ok now. Play with icon size. E.g. I changed size of retina image from 38x38 to 30x30, and now it works perfect. Probably iOS checks size and if it is not proper it uses instead of retina non-retina image Mine worked on a 40x40 retina image resolution on iOS 7.
common-pile/stackexchange_filtered
How do I get a date formatted as YYY-MM-DD from a cell for using in a script? I have a problem getting a date from a cell in my Google Spreadsheet. I would like to access A3 in the sheet Dates, which holds the date 01/12/2013, and re-use that as variable start-date in the below mentioned script. function fetchMAP28() { // our query object var query = { "optionalArgs": { "dimensions": "ga:date", "max-results": "50" }, "ids": "", "metrics": "ga:users,ga:goal1Completions", "start-date":"Here I like the date from the cell", "end-date": "yesterday" }; var results = Analytics.Data.Ga.get( query.ids, query['start-date'], query['end-date'], query.metrics, query.optionalArgs ); var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("dataMAP"); outputToSpreadsheet(results, sheet); } I'm not really sure what your problem is. Best is to share a doc and explain what you want to happen. Welcome to Web Applications !! This is a good start: http://www.google.com/script/start/ See link on how to change the date format in GAS: https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String) So you want to get a value from your spreadsheet, and use it in your script? I have added a couple of lines at the top of your script, and used startDate to populate the query object: function fetchMAP28() { var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dates").getRange("A3"); var startDate = range.getValue(); // Note the timezone is GMT+1 - you should adjust it to your locale var formattedStartDate = Utilities.formatDate(new Date(startDate), "GMT+1", "yyyy/MM/dd") // our query object var query = { "optionalArgs": { "dimensions": "ga:date", "max-results": "50" }, "ids": "", "metrics": "ga:users,ga:goal1Completions", "start-date": formattedStartDate, "end-date": "yesterday" }; var results = Analytics.Data.Ga.get(query.ids, query['start-date'], query['end-date'], query.metrics, query.optionalArgs); var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("dataMAP"); outputToSpreadsheet(results, sheet); } The variable formattedStartDate contains the string 2013-12-01. Thank you so much! Last thing: startDate print 2013-11-30T23:00:00.000Z how can I strip it to only have 2013-11-30 without time? I would use: Utilities.formatDate(new Date(startDate), "GMT+1", "yyyy/MM/dd"), since OP is using GAS. Ahh ... of course. So you would need to know the timezone, obviously. Thanks again! In my last version, I used Utilities.formatDate(startDate, ...) while the current edit says Utilities.formatDate(new Date(startDate), ...). Not sure why you would need to wrap startDate in new Date, provided you have a date in A3. Firstly, this is how the usage is described by Google (see comment at OP). Secondly, it will force the input to be seen as a date in all other instances. Since this isn't Stack Overflow, it's better to use it with the new Date()wrapped around it.
common-pile/stackexchange_filtered
Unique filter issue in angular Here is my drop down <select name="EType" id="opt-type" class="form-control" ng-options="type.id as type.name for type in types" ng-disabled="!eng.adding" ng-change="TypeChange()"> <option value=""></option> </select> I want unique record in combo i tried unique filer after applying that filter all record showing empty data Can any one help me on this. Try the 'unique' filter (angularUi) ng-options="type in types| unique:'name'" As you say you tried unique filter then it should work. Kindly cross check below points : required modules are added angular.module('myApp',['ui.directive', 'ui.filters']); angular-ui is referred? <script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
common-pile/stackexchange_filtered
Can I export the RGB values from an ArcGIS layer symbology? I've got a point layer in ArcGIS that has 100 specific color codes based on the name of the store. I'm trying to export the RGB values for these colors (along with the name value it's tied to) so I can create a qml style file for QGIS. So, basically I'm trying to apply ArcGIS symobology rules into a QGIS qgs project. Anyone know how I can do this? Maybe. Symbology is typically stored in a lyr file for ArcGIS. As this question notes, lyr file format is Esri proprietary and it's not 'readable' like a text or xml file. But the question of opening a lyr file in QGIS has been asked before and the answer there suggests an intermediate step of lyr -> sld and then applying the sld in QGIS to create a qml. But I'm not aware of anyway to export an RGB value list short of manual lookup and type. Were the colors applied via a ramp? If so, you might be able to convert the points to a raster and then export a color map (clr) file for said raster, which would have the RGB values in text format along with whatever attribute value goes with them. Roundabout way, but might be worth exploring. Chris, thanks for the reply. No, colors are random. Just seems like arcpy / python should be able to loop through a layer in the map and tell me the RGB codes for the symbology. I don't need a lyr or sld file, i just want the RGB codes for the colors it's using. I found this GEO thread Link which uses the java script API on server to extract from the JSON file. Might be worth further investigation.
common-pile/stackexchange_filtered
assigning two different arrays the same subscript in c I can't seem to find the answer I'm looking for. I am working on a project that involves creating two arrays. One stores a string, the other stores a number (name and age). I have to print the arrays, once in the order they are entered, and once alphabetized. I can alphabetize just fine, but I cannot get the ages to line up with the right name. Is there a way to assign an array the same subscript as another array in C ? How about using a struct? Have you learned about struct types yet? If so, use one. If not, say so. It means you have to work harder when doing the sorting. You must either use structs as shown or use one array as the 'key' values but do the same rearrangement steps to both arrays when sorting. Declare a struct like this: struct person { char name[30]; int age; }; Declare an array like this: struct person record[2]; Use it like this (example): strcpy(record[0].name, "Raju"); record[0].age = 24; Now record[0] has both a name and an age. When you sort they will stay together. I didn't show any array sorting or printing but it seems like you can handle it. If not, I can add more to the answer. Assuming the array of strings is a 2d matrix, where each row contains a name string, and if you want to keep the two arrays separate, then create a third array of indices, and sort the third array according to the array of names. Then display the names and ages using the third array of indices. If the array of strings is an array of pointers to strings, you could create a array of indicesto the array of pointers to strings, then sort that array of indices according to the strings, then use the sorted indices to display the two arrays in sorted order. If using a sort function where you supply a compare function, then create an array of pointers to the array of names (pointer[i] = &names[i]), sort the pointers according to the names, and convert the pointers to indices using pointer subtraction (index = pointer[i] - &name[0]).
common-pile/stackexchange_filtered
How to solve errors after yaourt -S code aborted accidentally, When I was installing code with yaourt -S code, something like ctrl d was typed accidentally. Then I try to install yaourt -S code again: gyp: Call to 'pkg-config --libs-only-l libsecret-1' returned exit status 0 while in binding.gyp. while trying to load binding.gyp gyp ERR! configure error gyp ERR! stack Error: `gyp` failed with exit code: 1 gyp ERR! stack at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:336:16) gyp ERR! stack at ChildProcess.emit (events.js:180:13) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:209:12) gyp ERR! System Linux 4.14.21-1-MANJARO gyp ERR! command \"/usr/bin/node\" \"/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\" gyp ERR! cwd /tmp/yaourt-tmp-czxyl/aur-code/src/vscode/node_modules/keytar gyp ERR! node -v v9.8.0 [proxychains] DLL init: proxychains-ng 4.12 [proxychains] DLL init: proxychains-ng 4.12 ==> ERROR: A failure occurred in build(). [proxychains] DLL init: proxychains-ng 4.12 Aborting... [proxychains] DLL init: proxychains-ng 4.12 [proxychains] DLL init: proxychains-ng 4.12 ==> ERROR: Makepkg was unable to build code. [proxychains] DLL init: proxychains-ng 4.12 [proxychains] DLL init: proxychains-ng 4.12 ==> Restart building code ? [y/N] ==> ----------------------------- ==> n How can I fix it? Did you remove the previous builddir? @jasonwryan how to remove the previous builddir? rm -r $wherever_you_build @jasonwryan I cannot find the dir where yaourt build : ( Really? It is printed in your error message: gyp ERR! cwd /tmp/yaourt-tmp-czxyl/aur-code/src/vscode/node_modules/keytar
common-pile/stackexchange_filtered
Graphics editor that represents everything as code/script/markup? When I'm creating graphics in Photoshop or Illustrator, I often wish my work was entirely represented by some plain-text format so that I could dive down and make rapid changes without doing too much work. (For example: changing the properties of a bunch of text labels at once, or instancing a similar object several times, or globally changing a color that applies to multiple objects.) I suppose it would sort of work like a WYSIWYG web development application, where you would do most of your work with the UI toolset but dive down into the raw HTML/CSS on occasion. Postscript seems like a good candidate, but I don't think I've seen anything that uses it in such a way. Are there any tools like this already available? (PaintCode looks similar to what I'm describing, but I don't think it's as robust as Illustrator for example.) Illustrator can import/export vector images in Scalable Vector Graphics (SVG) format, which is text-based (XML) and supports style sheets, similarly to HTML. Photoshop works mainly with raster images with binary file formats. I should have clarified: I'm specifically looking for real-time editing support. As far as I can tell, you'd have to export to SVG, edit, and then re-import in Illustrator. @Archagon, in that case, the best I can suggest is to try Inkscape's XML Editor mode (Shift + Ctrl + X). You can have the main drawing open simultaneously with the XML Editor and changes are reflected in both. That sounds perfect! I'll be sure to check it out. We all need this tool by Bret Victor to become available! @beroe, thanks for the link. Bret's new tool looks amazing. Hopefully it will be available soon. Once upon a time there was a system called NeWS (/nee-wuss/) which offered much of what you describe. I'm working on an open-source clone, called xpost which has a goal of implementing an Illustrator work-alike that will expose (and re-parse, after editing) the implementation of any construct. NeWS was itself inspired by earlier integrated graphics/language-environment systems like Interlisp-D, and Smalltalk. These earlier systems were hampered by being tied to (obsolete) monochrome bitmaps. There another program I've used called Mayura Draw which exported nice, clean, editable postscript.
common-pile/stackexchange_filtered
Console.log does not show up when I run 'ionic run android -lc' My console.logs stopped showing up when I run 'ionic run android -lc' It shows up when I hit it in the web browser. Based on this post I have tried to add this line to my package.json file: "scripts": { "ionic:build": "ionic-app-scripts build", "ionic:watch": "ionic-app-scripts watch" } but it gives me an error when I do a 'ionic build android' saying that 'ionic-app-scripts' is not recognized: Here is my json.package, I highlighted what I added. I tried to just remove the 'ionic-app-scripts' line in my package.json and it built correctly but it still did not log. Would appreciate any help. Thanks. UPDATE: I just did a restart with a completely blank copy with 'ionic start moment blank' and I copied my www folder into the clean app. Then I did a npm install and ran my app. I am still not getting console.logs. Could this somehow be happening because of my code in my www folder? I don't understand this. Any ideas? I am running on Ionic 1. Assuming this is an Ionic 2 app, you are missing the @ionic/app-scripts dependency from your package.json. The latest is: @ionic/app-scripts": "1.0.0" Example of a basic fully working ionic 2 package.json can be found in Ionic's conference app demo (https://github.com/driftyco/ionic-conference-app) : { "name": "ionic-conference-app", "description": "Ionic Conference App", "license": "Apache-2.0", "repository": { "type": "git", "url": "https://github.com/driftyco/ionic-conference-app.git" }, "scripts": { "build": "ionic-app-scripts build", "clean": "ionic-app-scripts clean", "ionic:build": "ionic-app-scripts build", "ionic:serve": "ionic-app-scripts serve" }, "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", "@angular/compiler-cli": "2.2.1", "@angular/core": "2.2.1", "@angular/forms": "2.2.1", "@angular/http": "2.2.1", "@angular/platform-browser": "2.2.1", "@angular/platform-browser-dynamic": "2.2.1", "@angular/platform-server": "2.2.1", "@ionic/storage": "1.1.7", "ionic-angular": "2.0.0-rc.5-201701112208", "ionic-native": "2.2.11", "ionicons": "3.0.0", "rxjs": "5.0.0-beta.12", "sw-toolbox": "3.4.0", "zone.js": "0.6.26" }, "devDependencies": { "@ionic/app-scripts": "1.0.0", "typescript": "2.0.9" } } Take notice of the @ionic/app-scripts here. To ensure a clean build, delete your current node_modules folder, and do a fresh npm install once you add the required dependencies. Its actually an Ionic 1 app. I added the script anyway and tried it but it is still not printing out the logs.
common-pile/stackexchange_filtered
Convert tabular data to XML in node.js I would like to find a way to convert a series of tabular data stored in a CSV file to XML using node.js or JavaScript in general and I do not know where to start. The original data files look like this: 2009-11-11 13:57:48|NOVAL|FPNxxx1B40000034|1|1|DATA001XE0OP|NOVAL 2009-11-11 13:57:48|NOVAL|FPNxxx1B40000034S|3|2|DATA001XE0OP|NOVAL 2009-11-11 13:57:48|NOVAL|PCNxxx1B40000812|24|2|DATA001XE0OP|NOVAL The desired output: <SYSTEM> <PARENT scanned="FPNxxx1B40000034"> <PARTNO>PNxxx1B4</PARTNO> <CLIENT>CLIENT_NAME</CLIENT> <SIDE no="1" parentcode="FPNxxx1B40000034"> <child code="PCNxxx1B40000793" pos="1" side="1" counterindex="1" state="1" /> <child code="PCNxxx1B40000794" pos="2" side="1" counterindex="2" state="1" /> <child code="PCNxxx1B40000795" pos="3" side="1" counterindex="3" state="1" /> </SIDE> </PARENT> I realise that the example XML shows some extra tags not included in the original data, but converting the main body of the data is what my question is about. Parsing CSV data: https://github.com/wdavidw/node-csv Producing XML: https://github.com/dylang/node-xml @Oleg thank you for your edit... one think to mention is that the only information I really need is the FPNxxxxx... and the PCNxxxxx... lists the other elements of the xml file are generated by the application, and the list needs to be ordered read your csv, parse it and use something like xmlbuilder to build xml var obj = { person: { name: "John", '@age': 35, address: { city: "Istanbul" }, '#list': [ { phone: { '#text': "555-1234", '@type': 'home' } }, { phone: { '#text': "555-1235", '@type': 'mobile' } } ], id: function() { return 42; } } }; var builder = require('xmlbuilder'); var root = builder.create(obj); How could I read the values in the 3rd column and add it to the XML? @reguia use a csv parser like the guy above mentioned.
common-pile/stackexchange_filtered
Binary search slower, what am I doing wrong? EDIT: so it looks like this is normal behavior, so can anyone just recommend a faster way to do these numerous intersections? so my problem is this. I have 8000 lists (strings in each list). For each list (ranging from size 50 to 400), I'm comparing it to every other list and performing a calculation based on the intersection number. So I'll do list1(intersect)list1= number list1(intersect)list2= number list1(intersect)list888= number And I do this for every list. Previously, I had HashList and my code was essentially this: (well, I was actually searching through properties of an object, so I had to modify the code a bit, but it's basically this: I have my two versions below, but if anyone knows anything faster, please let me know! Loop through AllLists, getting each list, starting with list1, and then do this: foreach (List list in AllLists) { if (list1_length < list_length) //just a check to so I'm looping through the //smaller list { foreach (string word in list1) { if (block.generator_list.Contains(word)) { //simple integer count } } } // a little more code, but the same, but looping through the other list if it's smaller/bigger Then I make the lists into regular lists, and applied Sort(), which changed my code to foreach (List list in AllLists) { if (list1_length < list_length) //just a check to so I'm looping through the //smaller list { for (int i = 0; i < list1_length; i++) { var test = list.BinarySearch(list1[i]); if (test > -1) { //simple integer count } } } The first version takes about 6 seconds, the other one takes more than 20 (I just stop there cuz otherwise it would take more than a minute!!!) (and this is for a smallish subset of the data) I'm sure there's a drastic mistake somewhere, but I can't find it. Where in that code are you sorting your lists? Or did you do it prior to this. HashList is O(1) amortized, BinarySearch() is O(logN). So this is completely normal. Hi, yes, I did it prior to this Really, so there's no other way to make it faster? HashList is the way to go. Given you're doing about 8000 x 4000 list comparisons (if I understand correctly), so it's expected to take a while! If you have a fixed list of strings it may be faster to iterate through all of these instead, but thinking about it, I think your method above would actually turn out to be faster. I can't think of other ways to speed it up unfortunately. Well I have tried three distinct methods for achieving this (assuming I understood the problem correctly). Please note I have used HashSet<int> in order to more easily generate random input. setting up: List<HashSet<int>> allSets = new List<HashSet<int>>(); Random rand = new Random(); for(int i = 0; i < 8000; ++i) { HashSet<int> ints = new HashSet<int>(); for(int j = 0; j < rand.Next(50, 400); ++j) { ints.Add(rand.Next(0, 1000)); } allSets.Add(ints); } the three methods I checked (code is what runs in the inner loop): the loop: note that you are getting duplicated results in your code (intersecting set A with set B and later intersecting set B with set A). It won't affect your performance thanks to the list length check you are doing. But iterating this way is clearer. for(int i = 0; i < allSets.Count; ++i) { for(int j = i + 1; j < allSets.Count; ++j) { } } first method: used IEnumerable.Intersect() to get the intersection with the other list and checked IEnumerable.Count() to get the size of the intersection. var intersect = allSets[i].Intersect(allSets[j]); count = intersect.Count(); this was the slowest one averaging 177s second method: cloned the smaller set of the two sets I was intersecting, then used ISet.IntersectWith() and checked the resulting sets Count. HashSet<int> intersect; HashSet<int> intersectWith; if(allSets[i].Count < allSets[j].Count) { intersect = new HashSet<int>(allSets[i]); intersectWith = allSets[j]; } else { intersect = new HashSet<int>(allSets[j]); intersectWith = allSets[i]; } intersect.IntersectWith(intersectWith); count = intersect.Count; } } this one was slightly faster, averaging 154s third method: did something very similar to what you did iterated over the shorter set and checked ISet.Contains on the longer set. for(int i = 0; i < allSets.Count; ++i) { for(int j = i + 1; j < allSets.Count; ++j) { count = 0; if(allSets[i].Count < allSets[j].Count) { loopingSet = allSets[i]; containsSet = allSets[j]; } else { loopingSet = allSets[j]; containsSet = allSets[i]; } foreach(int k in loopingSet) { if(containsSet.Contains(k)) { ++count; } } } } this method was by far the fastest (as expected), averaging 66s conclusion the method you're using is the fastest of these three. I certainly can't think of a faster single threaded way to do this. Perhaps there is a better concurrent solution. I'll try it, because my results were only for a small subset and it takes me like 8 minutes to do them all lol. Maybe because I'm not intersecting sets, but properties of objects that happen to be hashsets (and my sets are strings, but I don't think that matters much)? If I do parallel processing, where can I put the intersection numbers for each intersection? It seems if I do a matrix, I'll be accessing the same matrix, and that'll slow it down. What if I make an object with 3 properties, set1,set2, and intersection_number? Then ultimately I'll just have 64,000 instances of that object? Is intersecting object properties slower than just taking those properties and making a set out of them (like your allsets) and intersecting those? I've found that one of the most important considerations in iterating/searching any kind of collection is to choose the collection type very carefully. To iterate through a normal collection for your purposes will not be the most optimal. Try using something like: System.Collections.Generic.HashSet<T> Using the Contains() method while iterating over the shorter list of two (as you mentioned you're already doing) should give close to O(1) performance, the same as key lookups in the generic Dictionary type. Wait, wasn't I using Hashsets already, or do you mean something different? You were using the List type Yeah, I was using List<Hashset>...? Can you clarify or show an example? Ok, that you're already using HashSet was not shown in your code example or clear to me in your explanation. If you're already doing this, then you need to consider that comparing 8000 lists to each other is itself the bottleneck. You will not achieve optimum performance using a simple loop. Consider the System.Threading.Tasks.Parallel type to parallelize your calculations. Will post an example if I have time. Thanks, I actually looked into that, and I implemented it without really understanding what I was doing, so I only gained a 3x speed improvement, but I'm not sure how to deal with the fact that I'm accessing the same variables at the same time, and that I'd like to store the intersection number somewhere. Right now, I think my inefficiency is causing out of memory exceptions halfway through (maybe also because my hashets consist of strings, not integers). Should I post my updated code in another question? I don't think handling strings instead of ints will have any perceivable impact using HashSets. Using parallelism is a little tricky :-) There are many ways to slice and dice, including using the LINQ AsParallel() with various kinds of partitioners. There are also thread context considerations, which can hurt performance. No need to post your updated code... maybe you can explain, though, how you want to store the intersections.
common-pile/stackexchange_filtered
Elements and arrows in an abelian category. Suppose to work in an abelian category $\mathcal{A}$, so in particular for every objects $A$ and $B$, we have that $Hom(A,B)$ is an abelian group - in particular a set. My questions are: Does it suffice to conclude that $A$ and $B$ are sets? If "yes", does it suffice to conclude that the arrows from $A$ to $B$ are function, in a set-theoretic sense? I am almost sure that both of the statement are completely wrong, but I should be better if I received a proof/disproof (if possible, an example should be perfect!). Thanks in advance. Cheers It's not meaningful to ask whether the objects in a category "are" sets. The meaningful question is whether they can be interpreted as sets, or more precisely whether the category admits a faithful functor to $\text{Set}$ (http://en.wikipedia.org/wiki/Concrete_category). The key distinction is that interpretations (that is, faithful functors to $\text{Set}$) need not be unique if they exist; they are structures on rather than properties of categories. The formal answer is no, the objects of an abelian category need not be sets, nor do the morphisms need be functions. However, the Freyd-Mitechell embedding theorem says that an abelian category, and particularly a small one, is not far from being essentially a category of modules over some ring, with morphisms the module homomorphisms. In particular, when dealing with small enough diagrams in an abelian category one can safely pretend one is working with modules.
common-pile/stackexchange_filtered
Determine the convergence of the following series $\sum_{n=1}^{\infty} \sin\frac{\pi}{2\sqrt{n}}$ I want to determine the convergence of the following series $\sum_{n=1}^{\infty} \sin\frac{\pi}{2\sqrt{n}}$ At first, when i saw this series i thought that it is alternating, since function $\sin x$ is sometimes above, sometimes under the $x$ axis. But then, when a took a better look at the argument i noticed that in this case, sine remains in the first quadrant since when $n=1 \Rightarrow \sin\frac{\pi}{2} = 1$ and after that, it just decreases to the point when we are looking for the sine of zero (when $n \rightarrow \infty)$, so it looks to me like it's going to converge, i just don't know how to prove that. I tried few tests, but none of them works, for example, when i try d'Alembert's test, i get $1$ which is undefined. So i am not really sure what to do with this. Always use asymptotic bounds to understand the terms. Let "$[r]$" denote "$\{ x : |x| < |r| \}$" for any real $r$. As $n \to \infty$:   $\sin(\frac{π}{2\sqrt{n}}) \in \frac{π}{2\sqrt{n}} + [\frac{π}{2\sqrt{n}}^3] = \frac{π}{2\sqrt{n}} + [\frac{π^3}{8n\sqrt{n}}]$ by Taylor expansion. Therefore $\sum_{n=1}^m \sin(\frac{π}{2\sqrt{n}}) \in \sum_{n=1}^m \frac{π}{2\sqrt{n}} + \left[ \sum_{n=1}^m \frac{π^3}{8n\sqrt{n}} \right]$ by triangle inequality. Now it should be clear what happens, because there is a $c$ such that $\sum_{n=1}^m \frac{π^3}{8n\sqrt{n}}$ is bounded by $c$ for all $m$, and so it suffices to determine whether $\sum_{n=1}^m \frac{π}{2\sqrt{n}}$ converges as $m \to \infty$. Note that $\sin \frac{\pi}{2 \sqrt{n}} \geq \frac{1}{\sqrt{n}}$ for all $n$, so the series diverges by comparison. In general, if you have a series $\sum \sin(a_n)$ where $a_n \to 0$, you should always be able to determine convergence by comparing it to $\sum a_n$ or some constant multiple of $\sum a_n$. We have that (the easiest approach I know to the following inequalities uses the fact that $\sin$ is concave in the given interval) $$\frac{2}{\pi}x\leq\sin(x)\leq x\quad\text{ for }x \in \left[0,\frac{\pi}{2}\right],$$ so \begin{array}{ccccccc} \displaystyle\sum_{n=1}^{\infty} \frac{2}{\pi}\frac{\pi}{2n} &\leq&\displaystyle\sum_{n=1}^{\infty} \frac{2}{\pi}\frac{\pi}{2\sqrt{n}} &\leq&\displaystyle\sum_{n=1}^{\infty} \sin\frac{\pi}{2\sqrt{n}} &\leq&\displaystyle\sum_{n=1}^{\infty} \frac{\pi}{2\sqrt{n}}\\ \downarrow&&\downarrow&&&&\downarrow\\ \infty&&\infty&&&&\infty\\ \text{(harmonic series)} \end{array} and the sum diverges (actually, as the lower bound is $\infty$, the upper bound is not necessary). I hope this helps $\ddot\smile$ Thanks, but could you explain me why is it divergent, i mean if you read my question, you will see why i thought this is convergent, i mean, when we start with $n=1$ we have that the first term is $1$ every next term is positive, so it increases the value of sum, but every next term has lower value than the previous one, until the point when $n\rightarrow \infty$, shouldn't then this sum converge? @cdummie I've added one more sum on the left side: observe that $\frac{1}{n} < \frac{1}{\sqrt{n}}$, yet the harmonic sum still diverges. As you observed this is a positive series so you can use any of the powerful tests for positive series, say limit comparison limit: $$\lim_{n\to\infty}\frac{\sin\frac\pi{2\sqrt n}}{\frac\pi{2\sqrt n}}=1\;,\;\;\text{since}\;\;\lim_{n\to\infty}\frac\pi{2\sqrt n}=0\implies\;\text{since}\;\;\sum_{n=1}\frac\pi{2\sqrt n}$$ diverges, then also our series diverges.
common-pile/stackexchange_filtered
Newton's method of finding square root in python using only while loop The loop is not running at all. I'm just new to python and I have no idea what I did wrong. x = float(input("Enter a number: ")) y = x * 0.5 while True: y = 0.5 * (y + (x/y)) y_square = y * y if -0.001 < y_square < 0.001: break print("Square root:",y_square) The loop is running and it is running infinitely. Try printing inside the loop and you'll see it is running infinitely your if condition that breaks you out of loop isn't working in this case. Such small programs can be easily debugged using PythonTutor. Your loop does run, but it never stops. Two issues: if -0.001 < y_square < 0.001: surely you don't expect the square to be that small? It needs to be close to x, not close to zero. So change that to: if -0.001 < y_square - x < 0.001: The output should not be about y_square. You are not interested in the square, since that is what the user provided. You want to output the root, which is y: print("Square root:", y)
common-pile/stackexchange_filtered
What changes in MS Windows system libraries after restart? I'm running a 64-bit MS Windows 7 with all updates installed. About 1 or 2 weeks ago I've noticed that whenever I restart the OS, the virtual memory pages (of whatever process), corresponding to system libraries like ntdll.dll and kernel32.dll are slightly different. I'm not talking about the base address of the loaded modules, because I know that changes due to ASLR. I'm talking about the actual contents of the loaded modules, which as far as I know was not affected by ASLR implementations on Windows. To illustrate what I mean, let me show you the following screenshot that compares 2 binary instances of ntdll.dll captured before (top-half) and after (bottom-halt) one OS restart: The picture shows just a small part of ntdll.dll and therefore just a few differences. However, there are more. The size of these DLLs don't change, only some bytes at particular locations. I obtained the 2 binary instances which are compared in the previous picture using Process Hacker like so: Right-click a process and select Properties Go to the Memory tab and scroll-down until you find several entries having the name: ntdll.dll: Image (Commit) Double-click one of these entries (I chose the one that had 856kB) Press the Save... button to store the contents to a binary file on the HDD. Question 1: What is causing these bytes to change? Sub-question 1.1: Is is some sort of protection mechanism? Sub-question 1.2: Was it recently introduced? Sub-question 1.3: Can it be disabled? Question 2: What do these changing bytes represent in the code of the DLLs? Run dumpbin /relocations ntdll.dll and compare the listed addresses against the changes. @IgorSkochinsky I did run dumpbin as you indicated and compared the listed addresses against the changes. As a matter of fact it seems that no relocations were applied on ntdll.dll. And the changes that are visible in my picture are due to the system DLLs being linked with /DYNAMICBASE Question 1: What is causing these bytes to change? These appear to be standard relocation fixups applied based on the DLL's Relocation Table. Sub-question 1.1: Is is some sort of protection mechanism? No. Sub-question 1.2: Was it recently introduced? No. Sub-question 1.3: Can it be disabled? Not easily, no. Question 2: What do these changing bytes represent in the code of the DLLs? Addresses. Thanks for your answer. Would you be so kind as to also mention the addresses of what change? Is it the addresses of all functions or just some? It's not just for function addresses; it also applies to global variable addresses, etc. Simply put, any time the code or data references a virtual address instead of a relative virtual address, that reference needs to have a Relocation Table entry. See Sections 4.2 and 5.6 of http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v83.docx Thanks for clarifying that. One last question regarding this issue: is there a win32 API which can map/convert all the VAs to RVAs of a mapped image file? Or is this a question for stackoverflow? No API needed... VA - Image Base Address = RVA (since the "Relative" part of "RVA" is relative to the Image Base Address). Sure, I got the point, however, I need to known where all VAs are located inside the image file in order to subtract the base address. And I was wondering if there is something more efficient than checking whether the value obtained by subtracting the image base address from every DWORD in the image file is greater than 0 and smaller than the module size. Thanks again Just parse the Relocation Table. It seems that parsing the relocation table is not very common. Do you happen to know of any code which does this? What I have right now is: PIMAGE_NT_HEADERS imageNtHeaders = ImageNtHeader((PVOID) moduleBase); IMAGE_SECTION_HEADER *imageSectionHeader = ImageRvaToSection(imageNtHeaders, (PVOID) moduleBase, imageNtHeaders->OptionalHeader.BaseOfCode); However, the imageSectionHeader->NumberOfRelocations field is always 0. I expected it to be equal to the number of byte changes in my binary diff. Do you have any advice other than to read the document which you provided above? The code you posted in your comment above is not using the Relocation Table. Please refer to the PE COFF document to which I linked above, and ask further software development questions on http://stackoverflow.com/ @Benny, check out the 'PerformBaseRelocation' function in this code, https://github.com/fancycode/MemoryModule/blob/master/MemoryModule.c You can see how it parses the relocation table in that function. What you see is offsets modified to reflect a changed base address. Anything that's not relative to the base (be it global variables or calls or whatever) needs to be adjusted if the image base changes. PE files can have a relocation table for that. Can, as in standard .exe files usually don't have it, as it was not necessary until ASLR (random base addresses for modules) came along. For DLLs the base address is likely to change as it depends on what other files are already loaded so they almost always have a base relocation table that says "If the base address differs from XYZ, add the delta to the following locations". If you are curios how that base relocation table looks like, I'll recommend checking out the following: See the following code implementing a custom PE file loader. Search for IMAGE_DIRECTORY_ENTRY_BASERELOC to see code handling the relocation directory.
common-pile/stackexchange_filtered
elasticsearch phrase suggester java api The PhraseSuggestionBuilder in 1.6.0 of the elasticsearch java API has a collateQuery method that takes a String. builder .collateQuery("\"match\": {\"title\" : \"{{suggestion}}\"}") .collatePrune(true); Unfortunately the escaped quotes are escaped by the builder to produce JSON like this: "collate" : { "query" : "\"match\": {\"title\" : \"{{suggestion}}\"}", "prune" : true } Anyone any ideas how I can stop this String being escaped as the JSON is generated? Thanks. I ended up using the RestTemplate pattern and not using the Java API at all. Digging though the 1.6.0 elasticsearch code, I can't see how to avoid the double escaping of the collate query. String text = String.format(config.getQueryTemplate(), query.getText().toLowerCase()); String url = addTypes(getIndexUrl(), types) + "/_search"; try { return rest.postForObject(url, text, String.class); } catch (HttpClientErrorException e) { LOG.error("Unable to search: {}", e.getResponseBodyAsString(), e); throw e; }
common-pile/stackexchange_filtered
What kind of paint should be used to protect gas meter? During our home inspection, the inspector mentioned that the gas meter wasn't painted and could be subject to rusting later but he didn't elaborate on what paint to use. Anyone have suggestions here? Are there paint types specifically made for this? -M Check with your gas company. They may own the meter (per local laws) and so they'd be responsible for replacing it if it gets rusted. And they not be happy if you go painting their property without permission. If they let you do it, they would probably have recommendations. SoCal Gas meters are prepainted, but they do use a meter gray paint to paint the pipes to match. Did not copy down brand name of paint. The one at my house is new and it appears to be powder-coated. I'd let the gas company fix it though. Gas meters will be painted at the gas-meter factory. When factories (with an institutional customer) paint things in production, they use the very best paints, which would be a 2-part LPU over 2-part epoxy primer. Or lately, powdercoating with chemicals of similar quality. (they jack the cure temperature to 400F, so they can sell it to you pre-mixed in one can, but you must oven cure it.) You can't touch that kind of durability with any consumer-available paints. Such paints have a very tough outer sheen that won't take paint. If you want to repaint it because you don't like the color, you would need to scuff up the paint, e.g. with a Scotchbrite pad.
common-pile/stackexchange_filtered
IIS hangs waiting for result of async call We have an IIS website running C# code which is compiled by IIS (this is not running from a *.cs file, it's within code with <% %> tags on a aspx page. There are no async directives used in the page code. We have a .NET library with a class that exposes async methods. When we try to call the async method synchronously, like this: var articles = _cmsClient.GetAllArticlesAsync().Result; the page hangs indefinitley. The solution we found by trial and error is to wrap the async call in a task: List<Article> articles = null; var wpLoadTask = Task.Run(async () => { articles = await _cmsClient.GetAllArticlesAsync(); }); wpLoadTask.Wait(); This is working but I'm curious to understand why. https://www.bing.com/search?q=c%23+async+result+deadlock if one explanation is not enough. Note that your code will still lead to deadlock, just in a bit more specific conditions than standard deadlock with .Result. @AlexeiLevenkov this look like the root cause, but this code is not experiencing a deadlock (not we're talking about deadlock, not thread starvation). Doesn't Task.Run create a new thread context that allows a new thread to be spawned for completion? If not, how is this working? You should not call an asynchronous method from within a code render block (<% %>), because there's no way to make that call in an asynchronous manner. In other words, there's no such syntax such as <async% %> or anything of the sort. Instead, set Async="true" in the @Page directive, move your async code to a codebehind method, and register it using RegisterAsyncTask in the Page_Load. This is all described in detail with samples in the documentation here. The method you put in your codebehind should be something like this: public async Task<List<Article>> GetAllArticlesAsync() { var articles = await _cmsClient.GetAllArticlesAsync(); return articles; } Don't use .Result or .Wait(). Those are blocking, non-asynchronous methods. Don't wrap in Task.Run - that's just exchanging one task for another - which is valid for desktop apps with the UI thread, but has very little reason to be in a web app. To be clear, I'm not recommending this as a pattern for ASP.NET code - this is a legacy site and there is a major amount of tech debt standing in the way of making this site conform to textbook ASP.NET. It's obvious that using Task.Run isn't simply exchanging one task for another because it is allowing the call to succeed. There is some difference in the thread context of the spawned thread that allows the async call to execute. @PaulKeister with Task.Run you may be trading hanging site on your dev box vs. dead productions server when it gets decent load when it chews up all worker threads. @AlexeiLevenkov there's no doubt that is true, which is why I am trying to understand this behavior. The Task.Run workaround increases the likelihood of thread starvation, and if someone has an alternative other than rewriting all code associated with this call to conform to a standard async pattern, I'm listening. Beyond the practice necessity of avoiding Task.Run, I would also like to understand the underlying mechanism better, specifically: why does Thread.Run() work and task.Wait() hang? @PaulKeister read articles by Stephen Cleary from linked duplicate. Summary: both cases require free worker thread (from thread pool) to run/finish, .Result (without .ConfigureAwiat) deadlocks because it must use same thread it started on; Task.Run deadlocks when there is no available worker thread left to either start operation or return due to inner await. Note that Task.Run is not "create new thread" (search for "C# Task vs. Thread"). @AlexeiLevenkov thanks for the guidance, the linked articles do provide an explanation, which is that the SynchronizationContext for Task.Run does not capture the current context (this requires some inference, since this scenario is not explained directly). Your insistence that thread starvation and deadlock are the same is confusing to me in addition to being false. But I wish you well in any case.
common-pile/stackexchange_filtered
wget: unrecognized option `--no-check-certificate' on windows Despite being advised to use --no-check-certificate option with wget, I get this error that the option is not recognized. What do I do? wget: unrecognized option '--no-check-certificate' Turns out I've got a wrong version of wget compiled for windows. To support encrypted HTTP (HTTPS) downloads, Wget must be compiled with an external SSL library. ... If Wget is compiled without SSL support, none of these options are available. This version is compiled with SSL https://eternallybored.org/misc/wget/ more reading wget manual - HTTPS (SSL/TLS) Options
common-pile/stackexchange_filtered
Derived category of $k$-vector spaces Let $k$ be a field. How can describe the morphisms in the derived categories of $k$-vector spaces? I know that every short exact sequence is splitting. Take the definition of the morphisms in an arbitrary derived category associated to an abelian category (e.g. https://en.wikipedia.org/wiki/Derived_category) and specialize to the case of the category of vector spaces over a field $k$. Note: One can choose in each isomorphism class of an object a special representative... But this is an other question. Dan Petersen's answer is excellent, I am just providing more details. You can easily check that any complex of vector spaces is the direct sum of the two following complexes (with arbitrary degrees of course) : $$ \dots \to 0 \to k \to 0 \to \dots $$ $$ \dots 0 \to k \overset{id}{\to} k \to 0 \to \dots$$ The second complex is obviously quasi isomorphic to the zero complex. This shows that any $V \in D$ is isomorphic to $\oplus_{i \in \Bbb Z} V^i[i]$ for some vector spaces $V^i$. Now $Hom_D(k,k[j]) = Ext^j_k(k,k) = 0$ if $j \neq 0$, and $k$ else. So it follows that $Hom_D(V,W) = \oplus_{i \in \Bbb Z}(Hom_k(V^i, W^i))$ which is by definition $Hom(V,W)$ in the category of graded vector spaces. Again, as Dan Petersen said, you can apply exactly the same argument to any semisimple abelian category. $V^i[i]$ is the same $i$? @rafa : yes. $V^i$ is by definition a vector space, and also by abuse of notation is a complex concentrated in degree $0$. For a complex $K$, we define $K[i]^n := K^{i+n}$ (with differential multiplied by $(-1)^i$). I hope this is clear now. The derived category in question is equivalent to the category of graded $k$-vector spaces. In fact this is true generally for the derived category of a semisimple abelian category. Your answer is excellent (+1), I just did another answer with more precisions, I hope you don't mind.
common-pile/stackexchange_filtered
Change url with ajax call I'm doing cross-domain GET to get cnn html like this: $(function(){ var site = 'http://cnn.com'; $.get('proxy.php', { site:site }, function(data){ $(data).appendTo('#div'); }, 'html'); }); Im getting everything that I need except the url's sometimes are not complete urls but point to a certain path on there server like this: /2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3 So the problem is that if someone is clicking the link on my site the url will look like this: http://MY-WEBSITE/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3 How can I get rid of my own url being inserted and replace it with 'cnn.com'? I tried jquery split and replace but it doesn't work: href = $(this).prop('href'); url = href.split('/'); href.replace(url[2], 'cnn.com'); I usually get an error in console 'split is not defined', when I fixed it the error moves on to 'url is not defined' and so on. Sometimes (with other code variations) I get no errors but it still doesn't work. I cant figure it out. Have you tried using an IFrame ponting to the CNN site? You can simply check if the url is relative or not. Easiest way to do this is to check if it starts with http://. var url = $(this).prop('href'); if (!(/^http/).test(url)) { url = site + url; // prepend "http://cnn.com" to the address } alert(url); // url is now a full url if you want a more generalised solution, you can use the regexp object on the site to determine if the prefix is there. var site = "http://cnn.com"; var siteRegex = new RegExp("^" + site); // Regex - Starts with site var url = $(this).prop('href'); if (!siteRegex.test(url)) { url = site + url; } alert(url); I like it, its simple. I will test it later on my server Looking at your code I am assuming you are using jQuery. The problem is occurring because the source code on cnn.com seems to be using relative links. You can insert cnn.com at the beginning with the following jQuery $(function() { $('a').each(function() { if ($(this).attr('href').indexOf('http') === 0) { $(this).attr('href', 'http://www.cnn.com' + this.href); } }); }); the if statement is simply there to make sure it only changes relative links This little function can be used in a general purpose: function RelativeToAbsoluteURL(root, url) { var httpMatch = /https?:\/\//ig; if (!httpMatch.test(url)) { return root + (url.substr(0, 1) != "/" ? "/" + url : url); } else { return url; } } Use: RelativeToAbsoluteURL("http://www.cnn.com", "http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3"); RelativeToAbsoluteURL("http://www.cnn.com", "/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3"); Both will output the same URL (http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3) DEMO Either seems to work: var href = $(this).attr('href'); var url = (href.indexOf("/")===0) ? "http://...."+href:href; Possible alternative - this one will return the fully qualified URL from the href var href = this.href; // actual href and not the property var url =(href.indexOf(location.hostname)===7) ? href.replace(location.hostname,"www.cnn.com"):href; Using prop var href = $(this).prop('href'); var url = (href.indexOf("/")===0) ? "http://...."+href:href; Im getting this in console: TypeError: Object # has no method 'prop' I did not ask for prop, I asked for a way to do the job. The prop was just something I tried, nothing more. Any way I dont think I can do this with chrome console, I will try later on on my server
common-pile/stackexchange_filtered
What permissions are granted to an app with device administration privileges? Does a Device Administrator application have any/all permissions such as contacts, storage, etc.. ? It's not clear from developer.android.com device-admin whether or not these admin rights also imply application permissions. Or does device administrator simply mean that it can only do the things in the policy it's allowed to such as lock the screen, wipe the phone, prevent (easily) uninstalling the app, etc.. and that permissions to access private information is managed via the permissions settings only ? Yes, a device administrator only has permissions to do what it says. If you change the permissions of the app that the administrator is associated with, the administrators permissions will not change (Answer made from the following sources): Do you have evidence for this? I'm just curious how you found that out. From my personal experience, and from research online It would be nice of you, if you added your online sources. The answer is good but could be better. As you explicitly pinged me for an answer: AFAIK, apps can only use permissions declared in their Manifest – so there should be no way an app could add itself permissions it never requested there. DeviceAdmin gives high extra powers (apps are e.g. protected against uninstall, and can access some extra stuff they couldn't do without). What exactly this includes, I'm not sure. I only can refer to a specific part of the page you've linked, where the powers are explained. I cannot vouch for the pages completeness (or correctness at that: wouldn't be the first time some error made it in there). Enabling Device Administrator (source: Android Developers; click image to enlarge) You might remember there's something else carrying a similar name: ADM, the Android Device Manager. Checking above screenshot with that in mind, gives you an idea on the basics: ADM allows you to permit those functions (though AFAIK it doesn't feature "Monitor screen-unlock attempts" and "Disable cameras"). But this is a typical example of using most of those features. TL;DR: AFAIK DeviceAdmin cannot grant permissions to any app (including the DA-app itself), especially not if the app-in-question did not declare them in its Manifest. It just gives the app carrying this permission access to specific system features not available otherwise. I take it that this passage on that device administration page: Once users enable the device admin application, they are subject to its policies. Complying with those policies typically confers benefits, such as access to sensitive systems and data. means that an example company app could allow access to company sensitive data, not the other way around. That's correct, @ChristophAlrich – but at the same time, the company gets the permission to remotely wipe your device whenever it wishes, or have your password changed. I'd be very careful with whom I grant this. If some company wanted to force it upon me, I'd tell them to rather give me a device of theirs, but wouldn't let them manipulate my own.
common-pile/stackexchange_filtered
What does "one every 4 and 97/100 seconds" mean? I'm attempting to recreate a game AI system within JavaScript. Luckily, someone has made a post where they decompiled and listed the events - so i'm basing some of it from that. They explained that the AI's activity level increases 1 every 4 and 97/100 seconds - what do they mean by this? Is a number randomly picked between 97 and 100, then the resulting number would be randomly picked between 4? Lets say I had a variable called activityLevel set to 0, and I wanted to increase the variable 1 every 4 and 97/100 seconds. I have a random integer function here: function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } How could I replicate "1 every 4 and 97/100 seconds" in JavaScript? Otherwise, what does it mean? I think it just means every 4.97 seconds. Just a guess but I'd read that as 4970 ms (i.e. just a bit less than 5 seconds) setInterval(..., 4970) https://javascript.info/number Thanks. I'm used to decimal numbers, so the term "4 and 97/100" confused me. I would interpret it as meaning every 4970 ms, which is 4.97 seconds. That said, if you did want to vary between 97 and 100 (inclusive) hundredths of a second, you could do something like: myVar = 4970 + getRandomInt(0, 31); Thanks, not sure why someone would go into the effort of saying "4 and 97/100" when they could just say "4.97"
common-pile/stackexchange_filtered
Cosmos DB emulator raw authorization value format I have to access cosmos DB stored procedure from 3party application that allows only to configure and send requests in a raw HTTP format. To emulate that I use fiddler but I have no idea how to generate proper authorization token when I have emulator key. Cosmos DB default emulator key is C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw== My raw request: POST https://localhost:8081/dbs/Orders/colls/volcano1/sprocs/GetDocumentsAndTransform HTTP/1.1 x-ms-date: Wed, 09 Dec 2015 18:05:07 GMT Cache-Control: no-cache authorization: type%3dmaster%26ver%3d1.0%26sig%3dkOU%2bC2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==%3d User-Agent: contoso/1.0 x-ms-version: 2015-08-06 Accept: application/json Content-Type: application/json Host: localhost:8081 Content-Length: 9 Expect: 100-continue ["World"] It's fails with a authorization issue. Any ideas how to convert key to a proper authorization value for a HTTPs request? You can take a look at the Java SDK, it's open source. E.g. https://github.com/Azure/azure-cosmosdb-java/blob/master/sdk/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseAuthorizationTokenProvider.java /** * This class is used internally by both client (for generating the auth header with master/system key) and by the Gateway when * verifying the auth header in the Azure Cosmos DB database service. */ public class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider { private final String masterKey; private final Mac macInstance; public BaseAuthorizationTokenProvider(String masterKey) { this.masterKey = masterKey; byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(this.masterKey.getBytes()); SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256"); try { this.macInstance = Mac.getInstance("HMACSHA256"); this.macInstance.init(signingKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } } /** * This API is a helper method to create auth header based on client request using masterkey. * * @param verb the verb * @param resourceIdOrFullName the resource id or full name * @param resourceSegment the resource segment * @param headers the request headers * @return the key authorization signature */ public String generateKeyAuthorizationSignature(String verb, String resourceIdOrFullName, String resourceSegment, Map<String, String> headers) { if (verb == null || verb.isEmpty()) { throw new IllegalArgumentException("verb"); } if (resourceIdOrFullName == null) { resourceIdOrFullName = ""; } if (resourceSegment == null) { throw new IllegalArgumentException("resourceSegment"); } if (headers == null) { throw new IllegalArgumentException("headers"); } if (this.masterKey == null || this.masterKey.isEmpty()) { throw new IllegalArgumentException("masterKey"); } if(!PathsHelper.isNameBased(resourceIdOrFullName)) { resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT); } // Skipping lower casing of resourceId since it may now contain "ID" of the resource as part of the FullName String body = String.format("%s\n%s\n%s\n", verb.toLowerCase(), resourceSegment, resourceIdOrFullName); if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) { body += headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(); } body += '\n'; if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) { body += headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(); } body += '\n'; Mac mac = null; try { mac = (Mac) this.macInstance.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } byte[] digest = mac.doFinal(body.getBytes()); String auth = Utils.encodeBase64String(digest); String authtoken = "type=master&ver=1.0&sig=" + auth; return authtoken; } Well, it's a problem than. System accepts only raw requests.
common-pile/stackexchange_filtered
Why this works in C++? I have a code like this in C++: #include <iostream> #include <deque> #include <type_traits> using namespace std; int main() { deque<int*> myDeque; int a = 10, b = 20; myDeque.push_front(&b); myDeque.push_back(&a); int *const &r = myDeque.back(); myDeque.pop_back(); cout<<is_reference<decltype(r)>::value<<endl; cout << r << endl; cout << *r << endl; return 0; } Basically what I did is using a reference to the previously last element in the deque that has been deleted. However, the compiler reports no error and the behavior is not undefined. Could someone explain to me why this works? Thanks in advance! How can you determine whether a behavior is undefined if the observed behavior is "it works"? Working as expected is one possible outcome of undefined behavior, so just from observation you can never rule out undefined behavior, only confirm it. - "I can't see any undefined behavior" is therefore never a valid statement to make. In this case you do have undefined behavior which just happened to manifest itself in working normally in the few instances that you saw. The behavior is undefined. "Looks like it works" is one of many possible outcomes for undefined behavior. However, the compiler reports no error and the behavior is not undefined. C++ is not a nanny language. It relies on the programmer not to make these kinds of mistakes. It gives you enough rope to shoot yourself in the foot. In this particular case, the bullet didn't even hurt. Implied in freeing a variable is a promise not to use that variable anymore. If you break that promise, that's on you. Closely related topic: Can a local variable's memory be accessed outside its scope? Another side note: Code is not a list of instructions to be executed by a computer. It is a description of behaviours you want a program to have. The compiler's job is to read the code, interpret the behaviour, and generate the list of instructions to be executed by a computer. If you specify behaviour that is undefined, the program behaviour is undefined and the compiler can and will do whatever it wants. Usually it takes the path of least resistance and assumes you didn't screw up and very often this makes a broken program look like it worked.
common-pile/stackexchange_filtered
Does etoolbox's \ifboolexpr use lazy evaluation? In other words, is bool{testB} evaluated at all in this example code? \newbool{testA} \newbool{testB} \booltrue{testA} \booltrue{testB} \ifboolexpr{ bool{testA} or bool{testB} }{OK}{Something's wrong...} (I am too lazy (pun intended;)) to check in the source, the documentation seems to say nothing about it – maybe someone just knows that and doesn't have to analyze the source (which I did look into, but didn't understand it at a first glance)? If it isn't something obvious, I'll be happy to do my homework, dig into the source and try to establish this.) The evaluation is not lazy, revealed by scanning the .log when tracing the macro expansions: %\begingroup \tracingmacros1 \ifboolexpr{ bool{testA} or bool{testB} }{OK}{Something's wrong...} %\endgroup That is, a complete evaluation of bool{testA} is followed by an equivalent evaluation of bool{testB}, followed by an evaluation of or, to output \@firstoftwo{OK}{Something's wrong...}. Depending on your inspection of the macro expansion, you may require the use of a group to limit the output to the .log. I'd have gone for a faster route: \ifboolexpr{ bool{testA} or bool{\ERROR} } would work with testA true and lazy evaluation, but fails so evaluation can't be lazy :-) @JosephWright: I see, the lazy approach to detecting whether the evaluation is lazy. :)
common-pile/stackexchange_filtered
Powershell : how to pass a hashtable as args for parameter -PivotData with Export-Excel command (ImportExcel Module v7.8.6)? I could manage to build a simple script that collects some system metrics from different computer as a scheduled task, and export them into CSV files (one per computer). I am now trying to complete that first script with a second-stage script that works on all CSV files, turning each one into an XLSX file with two sheets : "DATA" and "CHARTS", using the Export-Excel command. Then come troubles... Within the "CHARTS" sheet in every XLSX file, the three first clomuns have to be "TIMESTAMP", "CPU" and "RAM", and the others must be "DISK-?1", "DISK-?2"... ("?" being put here for drive letter). As you may imagine, not all systems have the same number of drives/partitions, so not all CSV files have the same number of columns, nor all drives/partitions the same names. With the following code snippet, I found a rough way to dynamically determine the columns names to be considered for each file, columns names that will be passed as args to the -PivotData parameter of Export-Excel command: # Get list of CSV files to be processed $CSVList = Get-ChildItem -Path "\Collection\Folder" -Filter "*.csv" $CSVList | ForEach-Object { # Import CSV file as in-memory object for processing $CurrentFile = (Get-Content -Path $_.FullName) | ConvertFrom-Csv # Get list of disks/partitions to be reported in XLSX file $DiskList = New-Object -TypeName System.Collections.ArrayList $DiskList = $CurrentFile[0].PSObject.Properties.Name | Select-String -Pattern "DISK-" # Define static args for -PivotData parameter $PivotDataArgs = [Ordered]@{ "CPU" = "None" "RAM" = "None" } # Add dynamic args (DISK-?) according to $DiskList for ($i=0; $DiskList[$i] -ne $null; $i++) { $PivotDataArgs.Add("$($DiskList[$i])","None") } # # "Breakoint", to be explained later on... # # Export $CurrentFile to XLSX with selected columns # Code to be continued normally if "Breakpoint" solved } Basically, the Export-Excel documentation states this: -PivotData <Object> In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash-table in the form ColumnName = Average\|Count\|Max\|Min\|Product\|None... If I had to write an individual second-stage script for each CSV file (not having to build a dynamic list of args for -PivotData parameter), then the following code snippet would work perfectly, with a single chart on sheet "CHARTS", combining the metrics levels of CPU, RAM and the differents DISK-? all-in-one: # Import CSV file as in-memory object for processing $CurrentFile = (Get-Content -Path $_.FullName) | ConvertFrom-Csv # Export $CurrentFile to XLSX with selected columns $CurrentFile | Export-Excel -Path "\Results\Folder\$($_.BaseName).xlsx" ` -WorksheetName "DATA" -AutoSize -AutoFilter ` -IncludePivotTable -PivotTableName "CHARTS" ` -PivotRows "TIMESTAMP" -PivotDataToColumn ` -PivotData @{"CPU"="None";"RAM"="None";"DISK-C:"="None";"DISK-D:"="None"} ` -IncludePivotChart -ChartType Line -Activate Now time to explain the "Breakpoint", and this is where the troubles deepen... At this time in code (Breakpoint), $PivotDataArgs has *.GetType().Name = [OrderedDictionary] and *.GetType().BaseType = [System.Object]. Because the documentation states that only a hashtable can be passed as argument to the -PivotData parameter, then I need to cast my ordered list in order to get an hashtable. So, by doing $PivotDataArgs = [hashtable]$PivotDataArgs, I can now have *.GetType().Name = [Hashtable] with *.GetType().BaseType = [System.Object]. But exporting my CSV with a parameter line like -PivotData @PivotDataArgs throws an error stating Missing an argument for parameter 'PivotData'. Specify a parameter of type 'System.Object' and try again.. Having this error, then an idea comes to me : making $PivotDataArgs a string that looks exactly like when written manually. So, back from my ordered dictionary, I transform it into an identical string with $PivotDataArgs = ($PivotDataArgs | ConvertTo-Json -Compress).Replace('":"','"="').Replace('","','";"'). Now $PivotDaraArgs is a sting almost identical to the one manually written, with only the '@' missing. as our parameter only accepts hashtable as args, I then tried to make my almost-identical-json string become a hashtable with $PivotDataArgs = $PivotDataArgs | ConvertFrom-Json -AsHashtable... but no, it didn't work neither. Trying with ConvertFrom-StringData? No way to make it work... As a newbie in Powershell coding and automation, I tried everything that came to my mind, and I'm absolutely lost... your help and guidance would be more appreciated, please (Im dead if I don't get a solution asap)! I see a mistake in your script, you typed '-PivotData @PivotDataArgs' instead of '-PivotData $PivotDataArgs' is this your problem? Dear @Someone... from what I understood while google'ing, it's called "splatting" (unfortunately I can't get a link to that information now at time of writing) : we use $MyHashTable at definition, but @MyHashTable when passing it as args ; but as previously mentioned in my original post, I'm not an expert so this could be a mistake and you might probable be right. I'll check and test again. I just tested, and you were right... obviously I misunderstood what I read. Thank you for blowing away that mist in my eyes!
common-pile/stackexchange_filtered
How can stop trails when mouse don't move or mouse get inside other container React js I have built a mouse trails its starts when the mouse moves but I did not know how can hide the trails when the mouse stop I will leave a link similar to what I built. Link: codepen.io/paulholmes/pen/wPLqPw Take a look at this question: https://stackoverflow.com/questions/15066849/how-to-detect-when-mousemove-has-stopped I will share the code after I finish it. // dots is an array of Dot objects, // mouse is an object used to track the X and Y position // of the mouse, set with a mousemove event listener below var dots = [], mouse = { x: 0, y: 0 }; // The Dot object used to scaffold the dots var Dot = function() { this.x = 0; this.y = 0; this.node = (function(){ var n = document.createElement("div"); n.className = "trail"; document.body.appendChild(n); return n; }()); }; // The Dot.prototype.draw() method sets the position of // the object's <div> node Dot.prototype.draw = function() { this.node.style.left = this.x + "px"; this.node.style.top = this.y + "px"; }; // Creates the Dot objects, populates the dots array for (var i = 0; i < 50; i++) { var d = new Dot(); dots.push(d); } // This is the screen redraw function function draw() { // Make sure the mouse position is set everytime // draw() is called. var x = mouse.x, y = mouse.y; x = x + 125; // to make dots little bit far from cursor // This loop is where all the 90s magic happens dots.forEach(function(dot, index, dots) { var nextDot = dots[index + 1] || dots[0]; dot.x = x; dot.y = y; dot.draw(); x += (nextDot.x - dot.x) * .6; y += (nextDot.y - dot.y) * .6; }); } (function (mouseStopDelay) { var timeout; document.addEventListener('mousemove', function (e) { clearTimeout(timeout); timeout = setTimeout(function () { var event = new CustomEvent("mousestop", { detail: { clientX: e.clientX, clientY: e.clientY }, bubbles: true, cancelable: true }); e.target.dispatchEvent(event); }, mouseStopDelay); }); }(1700)); addEventListener("mousemove", function(event) { //event.preventDefault(); mouse.x = event.pageX; mouse.y = event.pageY; }); addEventListener("mousestop", function(event) { // You can hide or get the dots far from the cursor when mouse is stop mouving mouse.x = 0; mouse.y = 0; }); // animate() calls draw() then recursively calls itself // everytime the screen repaints via requestAnimationFrame(). function animate() { draw(); requestAnimationFrame(animate); } // And get it started by calling animate(). animate(); * { background: black; } .trail { /* className for the trail elements */ position: absolute; height: 10px; width: 10px; border-radius: 50%; background: red; box-shadow: 1px 1px 4px 1px lightblue; }
common-pile/stackexchange_filtered
variadic arguments which are all a specialization of a template type We can validate at compile time that an input to a function is a specialization of a template. I.E the following code validates that the input for f is some specialization of struct Holder. template<typename T> struct Holder<T> {...}; template<typename T> void f(Holder<T> h) {...}; I want to validate that a set of variadic arguments are a specialization of a template. More precisely I want to differentiate between two consecutive sets of variadic arguments - a set which is a specialization of a template, and a set which isn't. Following is an example of how it might have looked like if the syntax allowed it to - template<...Args1, ...Args2> void f(Holder<Args1>.... args_which_are_specializations_of_Holder, Args2... args_which_are_not) { use_holders(args_which_are_specializations_of_Holder...); use_rest(args_which_are_not...); return; } Is this possible ? Thanks, This is not possible, but a completely unrelated reason: two variadic parameter packs are not going to deduce the way you think they will deduce. what do you mean? and can i change the signature somehow to that they will ? You can store the args in a tuple and calculate the index of the last Holder argument, then extract the Holder and normal arguments by index and forward them to the corresponding function. #include <tuple> template<class T> constexpr bool is_holder = false; template<class T> constexpr bool is_holder<Holder<T>> = true; template<class... Args> void f(Args... args) { constexpr auto holder_index = (is_holder<Args> + ... + 0); auto args_tuple = std::tuple(args...); [&args_tuple]<auto... Is>(std::index_sequence<Is...>) { use_holders(std::get<Is>(args_tuple)...); }(std::make_index_sequence<holder_index>{}); [&args_tuple]<auto... Is>(std::index_sequence<Is...>) { use_rest(std::get<Is + holder_index>(args_tuple)...); }(std::make_index_sequence<sizeof...(Args) - holder_index>{}); } Demo somehow use_rest gets all the inputs, including the holder. Not sure what the issue is, but I made it work for what I needed. It's harder to mix variadic arguments like that. You can use std::tuple: #include <tuple> #include <cstdio> template<class T> struct Holder { T value; }; template <class ...T1, class ...T2> void f(const std::tuple<Holder<T1>...>& holders, const std::tuple<T2...>& non_holders) { std::printf("Holder count: %zu\n" "Non-holder count: %zu\n", sizeof...(T1), sizeof...(T1)); } int main() { Holder<int> a{}; Holder<double> b{}; int c{}; double d{}; f(std::tuple{a, b}, std::tuple{c, d}); } Looks pretty good. But I wonder if it's possible to remove the tuple creation when calling f? I think the second tuple isn't needed at all. And maybe the first one can be removed by some kind implicit cast to a tuple? trying to play with it, but unable so far to remove the first tuple. @NimrodFiat if you remove the second tuple, it becomes more fragile.
common-pile/stackexchange_filtered
how to view data based on clicked id im trying to view data based on clicked id, this is my button to catch the clicked id <a href="viewfull.php?id=<?php echo $result->id?>"class="btn btn-warning"><i class="glyphicon glyphicon-zoom-in"></i> Edit </a> and this is my viewfull.php code <?php include 'koneksi/koneksi.php'; $ID = $_GET['id']; $query = mysqli_query($con,"SELECT * FROM t_koperasi WHERE id_koperasi = '$ID'"); $result = mysqli_fetch_object($query); include 'views/v_data.php'; and this is the code to echo the data <?php while ($result = mysqli_fetch_object($query)) {?> <h1>Nama Koperasi : <?php echo $result->nama_koperasi ?></h1> the issue is when i click the view button the data isnt there it was just white blank good. You forgot to mention the issue... oh than you for reminding @LuthfiMusafa for this u need to use JQuery or ajax call thank you
common-pile/stackexchange_filtered
No matching distribution found for pybullet==2.7.3 I am trying to install pybullet with Python3.7.9 as python3.7 -m pip install pybullet==2.7.3. I keep getting an error that says it can't find the version and as you can see from the full error below that the version is skipped in the error output. However, PyPI seems to have the release of the package I am looking for. Why is pip unable to find this version? Full Error: ERROR: Could not find a version that satisfies the requirement pybullet==2.7.3 (from versions: 0.1.2, 0.1.3, 0.1.5, 0.1.6, 0.1.7, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.0.6, 1.0.7, 1.0.8, 1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.1.6, 1.1.7, 1.1.8, 1.1.9, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.2.8, 1.2.9, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.3.9, 1.4.0, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.8, 1.5.9, 1.6.0, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.7.0, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.8.0, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.8, 2.0.9, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.6, 2.1.7, 2.1.8, 2.1.9, 2.2.0, 2.2.1, 2.2.2, 2.2.3, 2.2.4, 2.2.5, 2.2.6, 2.2.7, 2.2.8, 2.2.9, 2.3.0, 2.3.1, 2.3.2, 2.3.3, 2.3.4, 2.3.5, 2.3.6, 2.3.7, 2.3.8, 2.3.9, 2.4.0, 2.4.1, 2.4.2, 2.4.3, 2.4.4, 2.4.5, 2.4.6, 2.4.7, 2.4.8, 2.4.9, 2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.5.4, 2.5.5, 2.5.6, 2.5.7, 2.5.8, 2.5.9, 2.6.0, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.6.6, 2.6.7, 2.6.8, 2.6.9, 2.7.0, 2.7.1, 2.7.2, 2.7.4, 2.7.5, 2.7.7, 2.7.8, 2.7.9, 2.8.1, 2.8.2, 2.8.3, 2.8.4, 2.8.5, 2.8.6, 2.8.7, 2.9.0, 2.9.1, 2.9.3, 2.9.4, 2.9.5, 2.9.6, 2.9.8, 3.0.0, 3.0.1, 3.0.2, 3.0.4, 3.0.6, 3.0.7, 3.0.8, 3.0.9, 3.1.0, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, 3.1.7, 3.1.8, 3.1.9, 3.2.0, 3.2.2) ERROR: No matching distribution found for pybullet==2.7.3 What is your operating system? My OS is: MacOS 12.3 While the version exists, if you look at the files tab you will see that for that version only whl files for manylinux are available. Interestingly, for most over versions (all the ones listed in your error output), an additional source distribution (.tar.gz) is available, just not for that version, so it cannot be installed on MacOS from pypi. The releases on github only go back to 2.86, so at this point it looks like you will have to pick one of the versions listed in your error message instead of 2.7.3 I did use 2.7.4 and it worked. Thank you for the response!
common-pile/stackexchange_filtered
Azure S2 Database Automatically creating and deleting a database every day I currently have an Azure S2 database running via the new Azure Portal. I notice my billing was higher than it should be and after investigating further, I noticed there were new databases appearing every day then disappearing. Basically, something is running a CreateDatabase and DeleteDatabase event every evening, and I'm being charged an extra hour each day. Microsofts response is: "Our Operations Team investigated the issue and found that these databases did indeed exist in a 1 hour windows at midnight PST every day. It looks like you may have some workload which is doing this unknowingly or an application with permissions which is unknowingly creating these databases and then dropping them. " I haven't set up any scripts to do this, and I have no apps running that could be doing this. How can I find out what's happening? Regards Ben Do you have an azure automation runbook doing this? Can it be a scheduled export? You might consider setting up SQL Auditing on your database (https://azure.microsoft.com/en-us/documentation/articles/sql-database-auditing-get-started) to gain more insights. Or you might consider rolling your DB password or revoking the create database permission? Thanks for the comments. I'm not sure what Azure Automation Runbook is? I don't have any scheduled exports. The strange thing is, the database is getting copied with DBName_ then getting deleted 20 minutes later... I have also this issues... When I look at the list of 'Deleted Databases' in old portal, I see databases name_GUID that are deleted daily. Can this be somehow related to Entity Framework? Do you use EF in your project?
common-pile/stackexchange_filtered
Is there a Google API for the Google Vault product? I'm looking for a way to extract emails from the Google Vault email archive database. I see there is a way to put data in, through their email migration API, but not out. I am aware of the Vault licensing API but that is not what I need. Any ideas? There is no way to access Vault via API. You would need to manually export the user data via the Vault UI. Google now has documentation about the API here.
common-pile/stackexchange_filtered
execute other class before executing the main windows form application class I've been given a windows form application written in VB. For some reasons I will need to execute the second class before the form application in the first class. The form class has to be the first class in the file. I can't simply inherit the second class and call the functions, because it has already used up the only allowable inheritance. I did some research and found there is something called main procedure that determines which codes executes first? It is automatically generated for any windows form application, but I simply can't find that file. Any thoughts on that? or any other ways that I do this? Follow Start VB.NET GUI app using Sub Main or form startup object? for better alternatives. But if you really need to start with Main(), follow these steps. Open application settings. Uncheck "Enable application framework" Set startup object to "Sub Main" Then add a new source file (.vb) and include Main() in it Module MainModule Sub Main() 'Your code here End Sub End Module
common-pile/stackexchange_filtered
How can I select something before and after a certain element I'm trying to select the first element with some condition (For example, .some_class) which is after a certain element. I don't know the relation between the elements, they could be siblings, cousins, whatever, all I know is they're all in this #container. HTML code: <div id="container"> <div class="subcontainer"> <div id="before" class="some_class"> </div> </div> <div id="this" class="some_class"> <div> <div class="subcontainer"> <div class="subcontainer"> <div id="after" class="some_class"> </div> </div> </div> ... </div> Given an element with the class "some_class" (in this case #this) i want to find the "some_class" elements that are immediately before (the #before div) or after (the #after div) said element. try with $('.some_class').after() OR $('.some_class').before() You cannot select an element before with pure css, but you can select the element after with .class + .element {} Sure thing i'll edit the question to make it more clear I think I understand. I don't think this should have been downvoted. var element = $("#container").find(".some_class"); like http://jsfiddle.net/arunpjohny/RST4C/1/ You can do this : var all = $('#container .some_class'); var before = all.slice(0, all.index(yourElement)); var after = all.slice(all.index(yourElement)+1); Demonstration (open the console) Yep, this works. So involved in finding a pure jquery solution that I didn't think of using array functions. Thanks you know what I mean... What would you call them, anyway? Also I just used all[index-1] and all[index+1] since I wanted the very next and previous element specifically. @Bogdan I didn't know if you were aware that index and slice were jQuery (array like) functions. For all the nodes around that "some_class" element try, $( "#this" ).siblings().css( "background-color", "red" ); For the next element, $( "#this" ).next().css( "background-color", "red" ); And for previous element $( "#this" ).prev().css( "background", "yellow" ); "I don't know the relation between the elements, they could be siblings, cousins, whatever, all I know is they're all in this #container."
common-pile/stackexchange_filtered
Why are there so many different types of payos that Jews grow? I would like to know how the different minhagim regarding growing payos (sidelocks) developed. I see so many different styles including curled, straight, tucked behind the ear, twisted above the ear, sideburns, wild growth etc. Can each of these styles be traced back to certain countries of origin? Are there any styles that trace back to the early days of Jewish history? "Why are there so many types of shoes that Jews wear?" seems like an equally interesting question. We all know people have different styles and various aesthetics go in and out of style. @DoubleAA. Great. So you're saying that it's just a matter of styles like shoes and eyeglasses. That's what I was asking. Why don't you post that as the answer? @MarkA. Because if he is right, then it would be nearly impossible to prove, as Jewish literature gives very little screen time to irrelevant historical fashion decisions. 2 shitot if peot can be bellow the hairs area, arizal & Rashash Related questions on the meaning and origins of arup peyos, geknipt payos, short Lubavitch peyos and Teimani simanim @mevaqesh. So it's just a question of style? Exactly like shoes and glasses? No other significance in the different minhagim? I imagine somebody out there has some better info than that. This is too massive of a question. There are so many payos styles to count and trace back to a specific place! Not to mention there are different ways people interpret the part in the Torah referring to not shaving the edges of the beard... @Ezra. Nothing is too massive for the Miyodeya family. Anyways, it's not that many basic options. Long curled, long straight, behind the ears, twisted above the ears, pulled up under the yarmulkah. @MarkA. Your comment does not seem to be a response to what I said. Since you raise issue, however, I would respond: https://en.wikipedia.org/wiki/Apophenia. Nothing is too massive for the Miyodeya family While a romantic notion, that is simply false. too broad: There are either too many possible answers, or good answers would be too long for this format. @Mark A. - ...Some people curl the payos 13 times, others do not, some don't even have defined payos at all, some grow them long but tuck them behind the ears still...The options are endless Note that Rambam writes that there is no reason to grow out one's peyot as is commonly assumed.
common-pile/stackexchange_filtered
Scrum - When do you Estimate the Effort for Product Backlog Items? At which part of the Scrum process does your team make educated estimates as to the effort required to complete a given product backlog item? For example, say you have a product backlog item that says "The user will be able to supply their email address and receive an email with a link for resetting their password" scheduled for Sprint 1. Do you start the sprint with a very rough estimate and refine it? When does this "user story" turn into granular action items that a programmer can estimate in time? (ex: "Build web form with one text box and submit button" = 2 hours) Do you do the finer, more accurate, estimates before the sprint begins? At the beginning of the sprint? Or during the sprint whenever the designer/programmer finally bumps into the task? According to the on-topic article, an article is considered on-topic if it "covers... a practical, answerable problem that is unique to software development". Scrum product backlog item estimating is a problem that is unique to software development. Voted to reopen. Usually, estimation should be done in 2 levels at the start of each sprint: story level and task level. For best results, product owner and team should do both together, every time, although sometimes it is acceptable for the team estimate at task level without the product owner present. Project Estimation / Roadmap Construction (Story Level) On your first sprint, you have to estimate at least 80% of the backlog items (I'm assuming the Product Owner already had it prioritized) to build a reasonable project roadmap, which will consist of stories grouped in sprints and a initial estimated projection of the project length. At this moment, the estimation of each story is done using, not hours, days or week, but a relative unit for size (which encompass effort, complexity and risk all at the same time), such as story points. We use the Fibonnaci scale and Planning Poker for this phase. It is important that the whole team actively participate in this process. After that, the team has to guess how many stories they are able to complete in the 1st sprint, which will be their initial estimated velocity (points/iteration). Usually, it is best not to use 1-month sprints but rather a 2-week or 1-week sprint length to improve estimation accuracy. The 1st planning will usually take the whole day or even 2 days, depending on backlog size, team size and the length of the sprints. After this 1st round of story estimation, the product owner together with the team might want re-prioritize the backlog to optimize the cost/benefit ratio, so the might be some back and forth until there is an agreement. You should end up with something like this: PROJECT ACME ROADMAP SPRINT 1 (38 points) <= estimated velocity -------- Story 1 (21 points) Story 2 (13 points) Story 3 (4 points) SPRINT 2 (40 points) -------- Story 4 (13 points) Story 5 (13 points) Story 6 (8 points) Story 7 (5 points) SPRINT 3 (39 points) -------- ... On the following sprints, this roadmap will be revised over and over, at the start of each sprint, adjusting the velocity to the actual velocity that the team is obtaining and re-calculating the project length as needed. Sometimes, re-estimating the stories is necessary as well, as the team evolves and requirements change. However, the time to revise the roadmap should be no more than half a day. The progress at this level should be visible to stakeholders using a burndown chart, where the X axis are the sprints and the Y axis are the story points. Sprint Estimation (Task Level) The 2nd part of the planning phase for each sprint is spent breaking down each story into tasks. Here, tasks should be highly technical in nature and estimated using hours. We have a policy that if the task is estimated longer than 8 hours, then it needs to be broken down into more detailed tasks no matter what. The result will be the sprint backlog, with tasks grouped by story, and the sprint burndown chart, where X/Y axis should be days of the sprint and hours respectively. It should look like this: Sprint 8 -------- Story 17 Task 1: 8 hours Task 2: 6 hours Task 3: 2 hours Story 18 Task 1: 8 hours Task 2: 6 hours Story 19 Task 1: 6 hours Task 2: 3 hours ... So basically, these are the 2 types of estimation you should be doing at the start of each sprint, where usually the 1st sprint requires a little more effort to build the initial project roadmap. don't agree about using time to estimate. I've been doing it for a long time a the results are not always positive. If you still use effort for the second estimation the velocity of each sprint will give you the time it takes. If you estimate with time you will almost always fail the estimation The rough estimate should be done before the sprint planning where this particular item is supposedly picked by a team. Usually we check the product backlog out during context switches or downtime during a sprint to do rough estimates on new items in "story points", so the product owner can prioritize them properly before the next sprint planning. Our sprint planning is usually time-boxed to 2 hours in the beginning of a new sprint. This is when we meet with the product owner(s) and pick items from the backlog, most of them roughly estimated and correctly prioritized. Missing estimates are done on the spot and then we do the "fine-grained" tasking of the stories within this time-window (which is usually quite intense work) leveraging the fact that the rest of the company is aware of this and POs and stakeholders are available to sort out unaccounted for details. Of course, sometimes the implementation task sequence will differ from the planned tasking, then it has to be adjusted, and the burndown chart might need to be retuned. Burndown in tasks We simply use number of tasks for our burndown measure. Usually you do something like actual hours or ideal hours, but this was good enough for us and apparently interesting enough to need some clarification. We do not estimate time on these tasks, all that matters is the story point estimate (the rough estimate) on the story, which we put in ideal man days. How that story is split into tasks is more of a team distribution and general progress indicator thing and not so much making accurate hour-estimates for us. In the end we have handled x amount of story points and get our focus factor from that in relation to the actual available man days in the team that sprint. In the end the rough estimate in story points is what we base our story selection on (ie, how many sp we can do in a sprint). We tend to get better at the rough estimate - and I think this is important because the product owner prioritizes items in the backlog mostly based on this, and never based on task estimates anyway - because that's team internal. As the tasks have no explicit time estimate on themselves, the focus is on the rough estimate in story points. If the tasks together takes more time than estimated story points * focus factor, we simply did the rough estimate wrong or should have corrected it during sprint planning when most information should have been available or sorted out. Hi Oskar, so you don't burn down development hours you burn down the number of tasks completed? And what is a 'task', are these the 'fine grained' tasks you produce in the sprint planning? Yes, the tasks we burn down are the fine grained tasks produced during sprint planning. It was an attempt to simplify things over burning down hours or whatnot, and it turned out good enough (for us). At the moment we produce detailed task breakdown and estimates before the sprint starts. This is for 2 reasons: 1) Our business want the estimates to help them decide the priority. 2) The development teams are under a pressure to deliver to the estimates and to not deviate from the natural burn down. In my opinion this is the wrong approach as it removes the ability to be agile. I think the process should be more like this... 1) The business should use the fibonacci numbers produced during the planning meeting to help them determine priority. Or at least only expect a 'finger in the air' estimate from the dev team. 2) The burn down chart should be seen as a guide to how the project is progressing to indicate whether more PBI's need to be added or lower priority ones dropped and not as a firm 'target' of what will be completed. Working this way would allow us to spend much less time in planning and design. We would still produce a high level estimate at the start of the sprint which could be refined as the sprint goes on. I will be interested to get comments on this before I have the battle with my business. Mostly agree. I think it's important as you say to give the PO rough estimates before the sprint, not detailed tasks breakdown, but this means several days or weeks before the sprint planning to help them prioritize. Your wanted use of the burndown chart also seems as how it should be used. Over the last few months we have been working more to this way and it is generally working for everyone. Our planning usually only takes a day or two at the most and we get less grief for falling behind the natural burndown. I have a question related to the of 1st (1) and (2). Is it a mistake to treat Estimates == Promise ? If so then what value does estimates have? I think dev teams comes under pressure and becomes less agile when we treat estimates == promise. This also reduces quality of code.I really like to hear some comments on this.
common-pile/stackexchange_filtered
statement to check if the datetime is within the two datetime from the column I have 2 column, start_date and end_date which contains a date and time with "yyyy-MM-dd H:mm:tt" format. At my program, I wanna query with this logic: If current_date is between start_date and end_date, return True. But the start_date and end_date is not static. Variety of value for each column. How to make a query statement to check if the current date is between start_date and end_date for every row? Answer for Alex: select if(start_date<=now() and now()<=end_date,true,false) from table You will get 1 (true) or 0 (false). that is the result from the query. It should be normal to view all data? And yes. If the now() is valid in between those two column, it will fill with value: 1..
common-pile/stackexchange_filtered
Divergence of power series in commutative Banach algebras Let $(A,||\cdot||)$ be a commutative Banach algebra over $\mathbb{C}$. Consider a formal power series $f(z):=\sum_{n=0}a_n z^n\in A[[z]]$ and let $$ r:=\frac{1}{\limsup\limits_{n\to\infty}||a_n||^{1/n}} $$ For $b\in A$ denote by $\rho(b)$ its spectral radius. Is it generally true that $f(b)$ is divergent (in the $||\cdot||$-topology) for any $b\in A$ with $\rho(b)>r$? I believe one can easily show in certain cases that $f(b)$ is divergent if $$ \rho(b)> \frac{1}{\limsup\limits_{n\to\infty}\rho(a_n)^{1/n}}=:R, $$ but $R$ can be much bigger than $r$. No, and more generally you can make no statement along these lines that depends only on $\rho(b)$. For instance, let $a,b\in A$ be elements with nonzero spectral radius such that $ab=0$. Let $a_n=c_na$ for some scalars $c_n$. Then $r$ can be made arbitrary by choosing $c_n$ appropriately, but $f(b)$ will always converge since all terms after the first term will be $0$. I see. The examples I had in mind, where the $\rho(b)$-thing works, are indeed too special. A follow-up question if you don't mind (let me know if it is better to create a new topic for it): based on $r$ is it at all possible to conclude where $f$ diverges, or that works only in special cases? (I mean aside from simply restating the root criterion.) I'm not sure exactly what you mean by that. The problem with getting any sort of divergence statement is that there is no lower bound for $|a_nb^n|$ in terms of just numerical data about $a_n$ and $b$ individually (you also need to know something about their product, which could be smaller than expected). Yes, this was what I meant. In $\mathbb{C}$ everything works out fine because the absolute value is multiplicative, but in general $A$ the norm is only submultiplicative, and for example, if I apply the root test, I can only conclude convergence, but the norm inequality is in the "wrong" direction in order to conclude divergence. Do you happen to have any references where such topics and examples about convergence/divergence issues of power series with Banach algebra coefficients are handled? I would really like to learn more about this topic, but I don't really know the literature. I'm afraid I don't know the literature either.
common-pile/stackexchange_filtered
MockBukkit#mock() throwing NPE I'm trying to test my Minecraft plugin with MockBukkit, but when I'm trying to mock a server (via MockBukkit#mock()) a NPE is thrown: java.lang.NullPointerException: Cannot invoke "org.eclipse.aether.RepositorySystem.newLocalRepositoryManager(org.eclipse.aether.RepositorySystemSession, org.eclipse.aether.repository.LocalRepository)" because "this.repository" is null at org.bukkit.plugin.java.LibraryLoader.<init>(LibraryLoader.java:59) at org.bukkit.plugin.java.JavaPluginLoader.<init>(JavaPluginLoader.java:73) at be.seeseemelk.mockbukkit.plugin.PluginManagerMock.<init>(PluginManagerMock.java:90) at be.seeseemelk.mockbukkit.ServerMock.<init>(ServerMock.java:166) at be.seeseemelk.mockbukkit.MockBukkit.mock(MockBukkit.java:56) Here you can find my pom.xml: https://pastebin.com/TPjDRr9f My test contains just a method with the annotation @BeforeAll in which I mock via MockBukkit#mock(). This issue is also mentioned here https://github.com/MockBukkit/MockBukkit/issues/614, but this issue is currently in backlog, so I'm trying to find a solution / workaround for this. I tried mocking the server in a test method with the annotation @BeforeAll: @BeforeAll public void setUp() { MockBukkit.mock(); } I expected the test to work. I actually got a NPE, which origin's located in the MockBukkit code. So I finally managed to fix this error: it occured because of this dependency: <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>2.0.4</version> </dependency> Watch this for updates: https://github.com/MockBukkit/MockBukkit/issues/614
common-pile/stackexchange_filtered
How do I get the touchpad working on an ASUS N551V? I have ASUS N551V with fresh install of Ubuntu 14.04.3 and my touchpad is not working. I tried a few solutions from Internet, but no success. For example, several solutions I have tried: editing this line GRUB_CMDLINE_LINUX_DEFAULT="quiet splash psmouse.proto=bare" in /etc/default/grub using dconf Editor, where the touchpad is enabled Can someone help with this? Thanks My biggest problem on N551 is: I couldn't install ubuntu16.04 onto it.
common-pile/stackexchange_filtered
Deaemon thread in Java created or not? I am confused regarding daemon threads in Java. Somewhere it says that a daemon thread is not created but only control, and someone else says that daemon threads can also be created. But how? Please don't state "please reply satisfactory answer" in your question. Daemon threads are not as special as you might imagine. They are regular threads with a flag set which has a particular meaning. I think the confusion comes from imagining it is something more. Daemon thread is just a regular thread. The only difference that it does not prevent application from terminating. Application is terminated if all its non daemon threads have finished.
common-pile/stackexchange_filtered
comparing eclipse project settings systemattically My question is: how I can systematically compare the settings of two eclipse projects? Background: I have two projects in eclipse, both using JavaCC. When I add maven nature to one of them, JavaCC doesn't work any more. When I remove maven nature, the once-has-been maven project seems spoiled, JavaCC still does not work. So I need a systematical method to find what the difference is between these projects. You can run diff on the configuration files, located in the .settings directory in the project folder. So you run diff -r NewProject/.settings OldProject/.settings That will show all differences between the config of NewProject and OldProject (There is also a .classpath so also do a: diff -r NewProject/.classpath OldProject/classpath Because this is just doing a text diff, it might be difficult to read, but it should at least give you a hint. Where NewProjecet and OldProjcet is the name of the old/new project folder. That's what I was looking for, but I didn't expect the difference being in only one or two files. And I did not ask for an easy way, just for a systematical one. .settings is a folder, now a file. There are many files inside it which is why you should run diff -r to compare 2 folders. (Or you can compare each file on it's own). Folder or file, it's just one place. And in my special case, there is an option "org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate", and in the same folder there is also a file "org.eclipse.m2e.core.prefs" that looks like eclipse hasn't removed it together with the maven-nature. @GyroGearloose Have you verified whether it is caused by the different org.eclipse.jdt.core.prefs settings files. Be aware that you can diff and edit those files inside of Eclipse. If you make changes to this file outside of Eclipse, you have to do a Refresh (F5) in Eclipse. @howlger Yes, I have checked all files I have found based on the accepted answer. There were a lot of differences that were not reverted when "removing" the maven nature, albeit the two projects were created in exactly the same way, with the only difference that one had a "holiday" as maven project. It finally worked again after I checked .classpath (which I had suspected the least), found and removed maven references. I frequently work with emacsclient outside of eclipse, so F5 is the first thing I do after changes by habit.
common-pile/stackexchange_filtered
Exception: Failed to retrieve form data. Please wait and try again I intended to write a script for Changing uploaded file name Changing file upload folder. As I am new to Apps Script, I decided to do up 2 separate scripts to test and merge when both are working. I have since gotten both scripts to work as intended but suddenly the auto trigger for on form submit is not working. Throwing the following error. Exception: Failed to retrieve form data. Please wait and try again. When I manually run the scripts, it is still working so I assume my coding is correct. I came across an article stating that adding var form=FormApp.getActiveForm(); will help but it doesn't for my case. Can anyone help please? Sometimes Google takes a bit longer to have formdata available. You could try Utilities.sleep(1000); or even longer if it's not time-critical and then try to get the response again.
common-pile/stackexchange_filtered
Async fields generation and TextureRegion rendering problem I have a piece of code to render a grid from which I will render a maze. My build function: fun buildAsync(): Deferred<RegularMaze> { return KtxAsync.async(newSingleThreadAsyncContext()) { addEmptyFields() enableLeftBordersRender() enableBottomBordersRender() regularMazeService.convertFieldsToMaze(fields, colsNo, rowsNo) } } And it looks like this: But when I move addEmptyFields() before async section it is rendering correctly And my Wall class class Wall (width: Float, height: Float, x: Float = 0F, y: Float = 0F, rotation: Float = 0F) : BasePart() { private val textureRegion: TextureRegion private val size: Size = Size(width, height) private val position: Position = Position(x, y, rotation) var relatedFieldIndex: Int? = null var shouldBeDraw = true init { inject() val wallTexture = assetsHelper.getTextureFromAsset(TextureAsset.WALL) wallTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat) textureRegion = TextureRegion(wallTexture, 0, 0, size.widthInt, size.heightInt) setBounds( position.x, position.y, width, height ) rotateBy(position.rotation) } override fun draw(batch: Batch, parentAlpha: Float) { super.draw(batch, parentAlpha) if (shouldBeDraw) { batch.draw(textureRegion, position.x, position.y, 0F, 0F, size.width, size.height, 1F, 1F, position.rotation) } } class Size (val width: Float, val height: Float) { val widthInt: Int get() = ceil(width).toInt() val heightInt: Int get() = ceil(height).toInt() } data class Position(val x: Float, val y: Float, val rotation: Float) } [EDIT/UPDATE] I discover something strange, when I create a single Wall without dimensions before async it starts working. "Working" code: fun buildAsync(): Deferred<RegularMaze> { Wall(0f,0f) // <---- new line return KtxAsync.async(newSingleThreadAsyncContext()) { addEmptyFields() enableLeftBordersRender() enableBottomBordersRender() regularMazeService.convertFieldsToMaze(fields, colsNo, rowsNo) } } Why? Is this line assetsHelper.getTextureFromAsset(TextureAsset.WALL) lazily instantiating a Texture? You cannot load textures from background threads. This would explain why instantiating a Wall first (on the game thread) fixes it. Feel free to use KTX GitHub issues if you want to discuss any parts of the framework. You are running into concurrency issues. The "fixed" code probably works by accident due to a slight delay in executing the coroutine or performing some crucial operation on the main thread, not because it addresses the actual problem. As a rule of thumb, you should never modify anything that is accessed by the rendering thread on different thread pools. My guess is that something modifies or accesses the regularMazeService while the coroutine is being executed, or the assetsHelper.getTextureFromAsset(TextureAsset.WALL) fails to load the texture in a background thread as it lacks the OpenGL context. If there is some expensive part of the operation that you want to do on a separate thread - that's OK, but anything that modifies the state of the rendering thread should be done on the rendering thread. For example: fun buildAsync(): Deferred<RegularMaze> { return KtxAsync.async(asyncContext) { onRenderingThread { addEmptyFields() } enableLeftBordersRender() enableBottomBordersRender() regularMazeService.convertFieldsToMaze(fields, colsNo, rowsNo) } } If any part of your code executed via coroutine launched with a custom thread: Needs access to OpenGL context (e.g. texture loading). Accesses or modifies data from the rendering thread. Performs any kind of rendering or updates relying on the rendering delta time. You should move it into the onRenderingThread block. Also, you should reuse coroutine contexts. Do not start a new thread for each coroutine with newSingleThreadAsyncContext() - assign the AsyncContext and reuse its instance. If you are loading textures manually, I encourage you to use the AssetStorage available in ktx-assets-async module. It leverages coroutines for true parallel asset loading.
common-pile/stackexchange_filtered
Bluetooth printer project - Failed to resolve: io.paperdb:paperdb:2.7.1 Hi i m getting this error: Failed to resolve: io.paperdb:paperdb:2.7.1 Caused by: org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find io.paperdb:paperdb:2.6. After following this tutorial to do Bluetooth printing: https://www.youtube.com/watch?v=M6azeYSRgoQ Without any link to get this error library. implementation 'io.paperdb:paperdb:2.7.1' I have not used this library, I have already cleaned, rebuilt and eliminated invalidate caches. They tell me to add Paper.init(this); in onCreate method, how do you do it? It makes sense? This is all i get on my Logcat. This is a build problem, so it won’t be solved by modifying onCreate. Please include relevant gradle files to help identify the problem. I can leave the : Grandle App 'implementation 'com.squareup.picasso:picasso:2.71828' implementation 'com.github.mazenrashed:Printooth:1.2.1'' Grandle Project 'repositories { maven { url "https://github.com/jitsi/jitsi-maven-repository/raw/master/releases" } google() mavenCentral() jcenter() maven { url 'https://www.jitpack.io' } maven { url "https://maven.google.com" } maven { url "https://artifactory.img.ly/artifactory/imgly" } }' In order to fix the issue, I updated the project's dependencies in build.gradle by changing: implementation 'io.paperdb:paperdb:2.7.1' to: implementation 'io.github.pilgr:paperdb:2.7.2' Fortunately, the import statements remain the same: import io.paperdb.Book; import io.paperdb.Paper;
common-pile/stackexchange_filtered
how to disable Bootstrap links hover background color? I integrated Bootstrap menu in my web site that I am developing now. In fact, I would like to know how can I disable Bootstrap links hover background color ?. The explanation is as below: This is the menu that I integrated: When I put the mouse cursor over an item of the menu, its background color changes to blue: What I want is that when I put the mouse cursor over any item nothing happens, it means that its background color doesn't change at all. This is the part of css code I am using: .notif_link:hover{ background-color: inherit !important; } And this is the code line belonged to an item of the menu I am using: <li class="notif"><a class="notif_link" href="#"><span class="notif_content">hello</span></a></li> So, my question is what is the error here?..And how can I do that? Thanks in advance. Either find the :hover pseudo selector in the Bootstrap css itself and change the value or overwrite it with the same selector (that you can find in dev tools/inspector) using your desired color. Ah, also remove the !important declaration. It is totally unnecessary. a[href]:after { display:none;} (or)<a class="disabled" href="javascript:void(0)">LINK</a>
common-pile/stackexchange_filtered
Why do we see the stairs in the cloaked ship in Star Trek 4? When they first leave the ship.... in San Francisco, they walk off/down the stairs/lift of the ship... we see the stair rails But the ship is cloaked! The cloaking field seems to extend around the normal extent of the ship. When objects protrude from this silhouette, they become visible. This is explicitly confirmed in the movie's novelisation: For a minute Javy considered jumping out of the truck, but Ben had it going nearly fifty. Javy tried to see behind them in the side mirror, but the light and the ramp had vanished, and he could make out only shadows. Jim led the way out of the Bounty and signaled for the ramp to withdraw. It disappeared into the cloaking field. The hatch closed, cutting off the interior light. Star Trek IV : Novelisation We see another example of this when Scotty sticks the upper half of his body outside the field when he's manhandling the plexiglass walls into place: Gillian gasped. The man hung unsupported in the air. But from the waist down, he did not even exist. It was as if he were standing within a structure that could not be seen and that could conceal him as well. An invisible structure ... " You mean transparent aluminum. @Thepopmachine - No. They pay for the perspex by giving the engineer the formula for transparent aluminium. Hmmm, Really? That's not how I remember it at all. This seems like some kind of script change because someone felt them gearing up and producing the transparent aluminum would be too unbelievable. @ThePopMachine - From the novelisation "Ah, what else indeed? Let me put it another way. How thick would ye need to make a sheet of your acrylic"-Scott hesitated a moment, converting meters to feet, wishing the twentieth century had finished getting around to the change--"sixty feet by ten feet, if ye wished it to withstand the pressure o’ 18,000 cubic feet 0' water?". "That's easy," Nichols said. "Six inches. We carry stuff that big in stock." @ThePopMachine - And from the script; SCOTT: Ah, what else indeed? I'll put it another way. How thick would a piece of your plexiglass need to be, at sixty feet by ten feet to withstand the pressure of eighteen thousand cubic feet of water? NICHOLS: That's easy, six inches. We carry stuff that big in stock. I'm not doubting you're right, but I don't think those excerpts show it. @ThePopMachine - From the novelisation; "In the far end of the cargo bay, the water nearly reached the top of the acrylic tank" @ThePopMachine - And from the script; "Cut to : The Plexicorp helicopter, carrying an enormous pane of plexiglass across the city. It is not exactly steady." OK, cool. But I might add keeping that quantity of six-inch plexiglass in stock isn't believable either. I would have preferred if they made the aluminum. From the dialog in the scene that scotty gave the formula for T-alum "It will take years to figure out the" ...something. Key here is the years and the fact he said he had plexi in stock to do what scotty wanted. Someone should ask this as a question... it was my understanding that they made the transparent aluminium, but it may take decades to work out "how it works" or some thing like that...
common-pile/stackexchange_filtered
Can output range of algorithms in <numeric> in C++ overlap with the input range? There are six algorithms that will output a range(which is denoted by an output iterator) in <numeric>: adjacent_difference, partial_sum, inclusive_scan, exclusive_scan, transform_inclusive_scan and transform_exclusive_scan. Can their input ranges overlap with output ranges? What about their parallel version? I've tried to find some hints in the C++ standard with no luck. In cppreference, for inclusive_scan "d_first - the beginning of the destination range; may be equal to first". I would expect that the parallel versions would not be able to share an input and output range, but I haven't checked. See the remarks at https://eel.is/c++draft/numeric.ops. Search for 'Remarks: result may be equal to first' All of the algorithms that you asked about except adjacent_difference have that remark. So the output range can be the same as the input range. That's more restrictive than what you asked about (can they overlap).
common-pile/stackexchange_filtered
How to create soft objects (wheel tires) in gazebo? Hello, I am currently trying to model a wheeled robot (pioneer3at) in Gazebo. The problem I face is that it strangely bounces of its wheels whenever it gets an impulse. So I thought the problem might be that the wheels are too hard and do not absorb any energy. http://gazebosim.org/wiki/Tutorials/1.9/Using_A_URDF_In_Gazebo#The_.3Cgazebo.3E_Element Following the link above I added a kp-tag to the according gazebo-tag in my URDF, but whatever value I use, it just causes the wheel to be ignored completely for collisions. (It will just fall through the floor) What is the correct way to describe collision properties in Gazebo? Update: I now had a closer look at the Husky-Bot, which seems quite similar to the Pioneer. In Gazebo, it shows none of the mentioned problems. The definition of the Husky-Wheels seems pretty similar to what I did: <gazebo reference="${fb}_${lr}_wheel"> <mu1 value="1.0"/> <mu2 value="1.0"/> <kp value="10000000.0" /> <kd value="1.0" /> <fdir1 value="1 0 0"/> <material>Gazebo/Grey</material> <turnGravityOff>false</turnGravityOff> </gazebo> So how comes it is not bouncing around like my Pioneer? Originally posted by Sebastian Kasperski on ROS Answers with karma: 1658 on 2014-04-09 Post score: 0 We had good success on our robots with not really modeling softness, but using the default parameters. You should be able to find a few skidsteering robots for inspiration regarding parameters (the husky_simulator package should provide a working example). I found that some parameters do not appear to work correctly though (see Gazebo Q/A). There also is a user group for Pioneer robots. I´d be surprised if there is not AT3 available for simulation, as this robot is in pretty widespread use still. /edit: Regarding parameters of the husky: Performance is a function of the complete model, so also the masses, inertias and ratios between them for the full model. It might be the case that the husky has better properties there. Note that issues could be reduced by altering some simulation parameters (timestep etc.) or model parameters (changing masses, getting rid of details etc.). Originally posted by Stefan Kohlbrecher with karma: 24361 on 2014-04-09 Post score: 2 Comment by Sebastian Kasperski on 2014-04-09: Thank you, I will have a look at these packages! I am currently using the p3at-model from p2os_urdf, which works in Gazebo besides the mentioned problems. I had the same problem. My Pioneer-3AT couldn't run much far without a bit of bouncing... making some useless reads with the laser scan, and move_base creating false collisions predictions. But the Pioneer-3AT model is very widespread and quite complete now, so I suspected this could be generated by other issues. I had ROS-Indigo on Ubuntu 14.04 LTS, and for me the solution was to run ROS-Hydro on a VM with a previous version of Ubuntu . I'm still not sure if the problem was the version of Gazebo which is shipped with ROS itself that had problems... or it was something on ROS-Indigo. I don't know. I'm on a rush to get results and this is what worked for me. Originally posted by gmcouto with karma: 11 on 2014-06-23 This answer was NOT ACCEPTED on the original site Post score: 1 I had the same problem with a pioneer3at package I found on the web. The problem was that the inertia information for the wheels was set to be the identity matrix: <inertial> <origin xyz="0 0 0" rpy="0 0 0"/> <mass value="1"/> <inertia ixx="1" ixy = "0" ixz = "0" iyy="1" iyz = "0" izz="1" /> </inertial> When ever I would move the robot through teleopt, I would get some bouncing behavior. I replaced it with the proper formula for a the interia matrix of a cylinder, and the runs smoothly: <macro name="cylinder_inertia" params="m r h"> <inertia ixx="${m*(3*r*r+h*h)/12}" ixy = "0" ixz = "0" iyy="${m*(3*r*r+h*h)/12}" iyz = "0" izz="${m*r*r/2}" /> </macro> <inertial> <origin xyz="0 0 0" rpy="0 0 0"/> <mass value="1"/> <cylinder_inertia m="1" r="0.1" h="0.11" /> </inertial> When you run Gazebo, go to the visualusation tabe and check the inertia view and you will see pink boxes. These should be more or less within the meshes of your vehicle. I now have fully working version of the pioneer3at for indigo under ubuntu 14.04 Originally posted by gpldecha with karma: 285 on 2014-11-08 This answer was NOT ACCEPTED on the original site Post score: 2
common-pile/stackexchange_filtered
Java GridBagLayout JPanels automatically resizing issue? I need a help with a resizing of Red coloured JPanel. Basically the problem is that I set the grid bag constraints for RED and BLUE JPanel same size and it works perfect, until i add the JLabel, then it just stupidly starts making the RED JPanel Larger size, but it should of been the same size as the BLUE JPanel, 0.05 size it should of stay at. I would be really appreciated if you can help me out, thank you so much in advance :) package weatherapp; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; public class WeatherApp { JFrame mainFrame = new JFrame("Weather App"); Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize(); GridBagConstraints gbc = new GridBagConstraints(); JPanel topMenuBar = new JPanel(); JPanel weatherInfoMaster = new JPanel(); JPanel weatherGraphMaster = new JPanel(); JPanel bottomMenuBar = new JPanel(); JLabel currentDateLabel = new JLabel(new SimpleDateFormat("dd MMMM yyyy").format(new Date())); WeatherApp() { constructAppFrame(); constructTopMenuBar(); } public void constructAppFrame() { mainFrame.setSize(540, 960); mainFrame.setPreferredSize(new Dimension(540, 960)); //Terminate the program when the user closes the app. mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setResizable(false); mainFrame.setLocation(screenDimension.width / 2 - mainFrame.getSize().width / 2, screenDimension.height / 2 - mainFrame.getSize().height / 2); mainFrame.setLocationRelativeTo(null); mainFrame.setLayout(new GridBagLayout()); gbc.fill = GridBagConstraints.BOTH; gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1; gbc.weighty = 0.05; mainFrame.add(topMenuBar, gbc); gbc.gridy = 1; gbc.weighty = 0.6; mainFrame.add(weatherInfoMaster, gbc); gbc.gridy = 2; gbc.weighty = 0.5; mainFrame.add(weatherGraphMaster, gbc); gbc.gridy = 3; gbc.weighty = 0.05; mainFrame.add(bottomMenuBar, gbc); mainFrame.pack(); mainFrame.setVisible(true); } public void constructTopMenuBar() { topMenuBar.setBackground(Color.RED); //topMenuBar.setBorder(new EmptyBorder(-20, 20, -20, 20)); topMenuBar.setLayout(new BoxLayout(topMenuBar, BoxLayout.X_AXIS)); currentDateLabel.setForeground(Color.WHITE); currentDateLabel.setFont(new Font("Comic Sans MS", Font.PLAIN, 20)); currentDateLabel.setBackground(Color.BLUE); currentDateLabel.setOpaque(true); topMenuBar.add(currentDateLabel); weatherInfoMaster.setBackground(Color.CYAN); weatherGraphMaster.setBackground(Color.GREEN); bottomMenuBar.setBackground(Color.BLUE); } public static void main(String[] args) { //Create the frame on the event dispacthing thread. SwingUtilities.invokeLater(() -> { new WeatherApp(); }); } } The requirements for the red panel have changed, requiring it to take more space, this is kind of the point of layout managers But if you look at the label there is so much free space, i set background to the label just to see how much space it takes and the original size would of been enough to accommodate the label, if not it should of slightly became larger, but in my case it's just ridiculously massive. //mainFrame.setLocation(screenDimension.width / 2 - mainFrame.getSize().width / 2, screenDimension.height / 2 - mainFrame.getSize().height / 2); mainFrame.setLocationRelativeTo(null); The first statement is not needed, since the setLocationRelativeTo(...) will reset the location. constructAppFrame(); constructTopMenuBar(); Don't add components to the frame AFTER the frame is visible. The order of the two statements should be reversed. it just stupidly starts making the RED JPanel Larger size, but it should of been the same size as the BLUE JPanel, 0.05 size it should of stay at. It is not stupid. It is well defined behaviour of the layout manager. Every layout manager has it own rules to follow. The GridBagLayout works on the "preferred size" of components. When no components are added to the panel the preferred size is (10, 10) because a JPanel uses a FlowLayout by default and the default gap before/after components is 5 pixels. So when extra space is available the GridBagLayout allocates the space based on the preferred size which results in the red getting more space. As a quick hack (after following my other suggestions from above) you can do: bottomMenuBar.setPreferredSize( topMenuBar.getPreferredSize() ); mainFrame.add(bottomMenuBar, gbc); Now the sizes will be the same because the preferred size is also the same. This proof of concept is not really a good solution because the preferred size of the blue panel becomes fixed even if you change the red panel. Maybe a better solution is to use the Relative Layout. This layout will size the components based on the space available in frame, not the preferred size, so if the red/blue panels have the same relative size they should be the same size even as components are added. I ended up not using grid bag layout :) I actually require them to be exact the size i give them to have enough space for the other components i will place, than you for great, clear explanation.
common-pile/stackexchange_filtered
How to turn off Overflow Check in VBA for MS Access? I am writting a CRC8 function in VBA which results in error: Overflow ! Since I cannot fix it and there are no sample code solutions on how to fix the overflow error with left shifting, I`d like to try and turn it off to see the result I get. I cannot find it in options. Change As Integer to As Long. I cannot find it in options. This is because it is a runtime error, not an "option." Most likely a cause of an Overflow error is trying to slick a number that's too huge for the data type. Byte type is for 0-255. Integer type can hold numbers up to 32,767. Long data type can hold numbers up to 2,147,483,647 so it's probably better suitable for your specific case. Adjust your variables types accordingly. Generally, VBA converts all Integers to Long these days so it's a better practice to dim your variables as Long by default. Here is an excellent writup as to why you should use them as Long. Here is how you left shift a Byte without overflowing: Dim abyte as Byte abyte = &H81 '10000001 'To shift left, you multiply by 2, BUT because the msb is 1, multiplying by 2 gives you an Overflow. 'To fix that, you first mask off the leftmost bit, THEN multiply by 2... 'abyte is 10000001 'And it with the mask &H7F And 01111111 'which results in = 00000001 'multiplied by 2 is *2 = 00000010 abyte = (&H7F And abyte) * 2 It's a bit more complicated for Integer/Long because they are signed, but it's still possible. Use: On Error Resume Next ' Disable Error Handler .. do the calculation .. If Err Then ' Handle Error End If On Error Goto 0 ' Activate Error Handler This won't allow OP to evaluate an expression which raises an error. This simply ignores the error and proceeds to the next line of syntax. gosh... that's a terrible suggestion
common-pile/stackexchange_filtered
Car struggles to start when warm (fine when cold) Car is a Mk1 Golf Cabriolet with JH1 injected engine. The car struggles to catch when the engine is warm. It turns over easily but will start to fire on only 1 or 2 cylinders for a while before catching on all 4. When cold, there is no problem - it starts normally. When running, either hot or cold, the car drives normally. I have replaced the plugs, leads and battery, but no change. I have also replaced the fuel filter, thinking there was a blockage, but again no change. The distributor cap and rotor seem a little worn and there is carbon deposits that I scrape off sometimes. Could that be a cause? Does the engine run rough when warm, or do you have any performance problems? No, once running engine seems smooth. However, it does feel a little down on power when warm. I think it may need timing adjusted. Found that for whatever reason ensuring the lifter pump seal was properly fitted fixed this. I ended up using aviation gasket sealant along with the O ring.
common-pile/stackexchange_filtered
Google Sheets: how to SUM multiple criteria (AND of OR) where the OR comparisons are strings? For example in https://docs.google.com/spreadsheets/d/179oMZ1h8cHC9T2yKotsmV9hdpDMIzLM9EOPW-vpobkg/edit#gid=2085573974 I want the sum of Hours where Status = TODO or INPROGRESS and Location = NYC or LA Hope I phrased the question clearly enough and thanks for any ideas! Which do you want, Google-sheets or Excel? The approach to each are different. Google Sheets, per my example. Thanks! Use Query: =sum(QUERY(A2:D8,"Select C where (B = 'TODO' OR B = 'INPROGRESS') AND (D = 'NYC' or D = 'LA')"))
common-pile/stackexchange_filtered
Issue while converting pandas to datetime I'm converting string to datetime datatype using pandas, here is my snippet, df[col] = pd.to_datetime(df[col], format='%H%M%S%d%m%Y', errors='coerce') input : col 00000001011970 00000001011970 ... 00000001011970 output: col 1970-01-01 1970-01-01 ... 1970-01-01 00:00:00 the ouput consists of date and date with time.. I need the output as date with time. PLease help me out where I am going wrong Just like the other answer suggested time is there, but since it's midnight 00:00:00, it's not showing explicitly. To print out the date with time you can try this : df[col] = pd.to_datetime(df[col], format='%H%M%S%d%m%Y', errors='coerce').dt.strftime('%Y-%m-%d %H:%M:%S') your code converts datetime datatype to object , and i need date time datatype
common-pile/stackexchange_filtered
How to quit Electron app on Mac? Below is stock code from the Electron website (https://electron.atom.io/docs/tutorial/quick-start/): app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) On Mac OS 10.12.4, when the above is called, it will not close the app. Only the window. Adding app.quit() above the conditional does close the app. Did they leave something out specific to Mac OS X that prevents the app from closing?
common-pile/stackexchange_filtered
Create and manage a group using the Facebook API I am new to Facebook application development and I am looking for a way to create and manage a group using the the Facebook API. There is a get and get list call but I have not found a way to manage groups. At the time of writing there is no method of the Facebook API for creating groups. Methods are however available to get the details of specific groups. For more information see the API docs, http://wiki.developers.facebook.com/index.php/API I wish this were wrong but I am becoming to believe it is true also. The link appears to be broken. Can you find the new home of the API? (I'd do it, but I don't use Facebook, and Google keeps taking me to pages where they're asking me to log in.) Looks like the API has been released: https://developers.facebook.com/docs/reference/api/app-game-groups/ Is this available in any way for regular groups? this is available for anyone to post/read to facebook groups, if you have permission from the user. You can create/delete groups by using the app token. Facebook says developers will also be able to create Groups and manage Group membership via the API “in the near future.” (11 Oct 2010) http://www.insidefacebook.com/2010/10/11/groups-api-details-apotential/ I'd sure like to know what Facebook considers the "near future"... I don't think they define that the same way as the rest of us. 11/16 and still no way to manage groups with the API.. even basic functions.. or even list posts by date.
common-pile/stackexchange_filtered
Download and save image from a website using wget How do I download and save the particular image from the following web page using wget. http://www-nass.nhtsa.dot.gov/nass/cds/GetBinary.aspx?SceneView&ImageID=509617654 I tried this "C:\Program Files (x86)\GnuWin32\bin\wget" -r -P "C:\temp\" -A jpeg,jpg,bmp,gif,png "http://www-nass.nhtsa.dot.gov/nass/cds/GetBinary.aspx?SceneView&ImageID=509617654" But the image did not download and save. I am using Windows 7. I guess I am not getting the image since the web page is not a proper html page (no html or asp etc extension). Am I correct? Not exactly. A file extension is not required for URLs containing HTML (e.g. http://google.com/). By inspecting the HTML source (ignoring that the page has invalid HTML (<script> tag in between <head> and <body>)), we can see it's using JavaScript to alter the image's src attribute on page load (why, who knows...) to /GetBinary.aspx?Scene&ImageID=509617654&CaseID=&Version= (relative to the HTML page). As wget can't execute JS, this will never work (like this). However the actual image URL does return a JPEG image, but you'll have to rename it, as, also, the web server (IIS) is misconfigured, as for that URL it returns a header: Content-Type: E:\Sites\NASS\CDS\/img/jpg which is invalid, and causes file association problems when downloading in most browsers / clients. To prove it's there, you can try downloading it directly with wget: wget "http://www-nass.nhtsa.dot.gov/nass/cds/GetBinary.aspx/GetBinary.aspx?Scene&ImageID=509617654&CaseID=&Version=" -O image.jpg
common-pile/stackexchange_filtered
Ubuntu Server 12.04 forked-daapd 5 minute time out issue I have a server running ubuntu 12.04.1 LTS and I have installed forked-daapd but i am having the issue where forked-daapd stops working after five minutes of use. Has anyone been able to get around this issue? I believe there is a fix for this but I haven't found a way to install that in ubuntu 12.04. Any help is appreciated. Thanks, Prince You have to tell us what you done. Like how you installed forked-daapd and which patch you tried. We can't read your mind and hasn't looked over your shoulder while you tried to fix this, you know. So please update your question with that information. We may close this since it doesn't have enough information to answer, but if you answer @Anders's questions (edit your question to add the request info), please feel free to flag (and maybe also comment) to request this be reopened.
common-pile/stackexchange_filtered
concatenate both two contents or image and content on one button, c# code needed I tried to paste an image on multiple buttons using find resource in MainWindow source code and window resources in XAML. But the problem is that, image removes the button content. How to fix it?? May I paste image at border corner or any other solution of this problem? .cs private void button_Click(object sender, Routed Event Args e) { Button button = (Button)sender; if (isGroupOpen == true) { List<Button> buttonlistA = new List<Button>(); buttonlistA.Add(button); button.Content = FindResource("Play1"); } } .xaml <Window.Resources> <Image x:Key="Play1" x:Shared="false" Name="button" Source="image.png" Height="20" Width="20" Margin="30px,-20px,-20px,30px" HorizontalAlignment="Left" VerticalAlignment="Top"> </Image> </Window.Resources> Might I trouble you for a glass of code? SO won't just write code for you. Please show us what you have tried and we can help you from there. @RandomStranger private void button_Click(object sender, Routed Event Args e) { Button button = (Button)sender; if (is Group Open == true) { List<Button> button listA = new List<Button>(); button list A.Add(button); button.Content = Find Resource("Play1"); @RandomStranger in x.m.l <Window.Resources> <Image x:Key="Play1" x:Shared="false" Name="button" Source="image.png" Height="20" Width="20" Margin="30px,-20px,-20px,30px" HorizontalAlignment="Left" VerticalAlignment="Top" > </Image> </Window.Resources> Short answer: don't do it. You have your image in xaml, you can have your buttons in xaml, you can bring them together in xaml. Also, your button content can be pretty much anything, you just design some visual, then place it in a button and the button will contain the visual. @grek40 i have multiple buttons and multiple lists , and images are pasted at runtime. if button goes to list 1 then it get image A on it if it goes to list 2 it gets image B and so on... Sounds like you can provide a list-specific Button.Style where all buttons in one list have the same icon but buttons in another list have a different icon Also I don't understand "Images are pasted at runtime". In the question, the image is a resource, created from a static image filename lists are created acording to conditions. when button goes to a list it gets a specific image. means image will be according to list I give you a little example to experiment with. As commented, you shouldn't rely on code behind to much, when trying to define the visual representation of something in WPF. Since you didn't show much of your code, it's impossible to give a precise answer for your specific problem instance, still this answer can give you an idea how visible design and functionality can be separated. In the following example, there is one initial button and a checkbox. When you click the button, a new button is spawned in List A or List B (depending on the CheckBox.IsChecked), with an icon and with a Command that handles clicks. The following assumes that your project contains images /Images/Yes.png /Images/No.png. You may adjust the actual image properties as you need. The code public class ButtonDescription { public object ButtonContent { get; set; } public ICommand ButtonCommand { get; set; } } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded += MainWindow_Loaded; } public ObservableCollection<ButtonDescription> ButtonListA { get; set; } public ObservableCollection<ButtonDescription> ButtonListB { get; set; } void MainWindow_Loaded(object sender, RoutedEventArgs e) { ButtonListA = new ObservableCollection<ButtonDescription>(); ButtonListB = new ObservableCollection<ButtonDescription>(); grid1.DataContext = this; } private void Button_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; if (TargetDescriptor.IsChecked == true) { ButtonListA.Add(new ButtonDescription { ButtonContent = button.Content, ButtonCommand = ApplicationCommands.Open }); } else { ButtonListB.Add(new ButtonDescription { ButtonContent = button.Content, ButtonCommand = ApplicationCommands.Close }); } } private void Open_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("Open"); } private void Close_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("Close"); } } The xaml <Window x:Class="WpfTests.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Open" Executed="Open_Executed"/> <CommandBinding Command="ApplicationCommands.Close" Executed="Close_Executed"/> </Window.CommandBindings> <Window.Resources> <!-- Button content templates with image before text content --> <DataTemplate x:Key="buttonContentA"> <StackPanel Orientation="Horizontal"> <Image Source="/Images/Yes.png" Margin="3" Width="16" Height="16"/> <ContentPresenter Content="{Binding}" VerticalAlignment="Center"/> </StackPanel> </DataTemplate> <DataTemplate x:Key="buttonContentB"> <StackPanel Orientation="Horizontal"> <Image Source="/Images/No.png" Margin="3" Width="16" Height="16"/> <ContentPresenter Content="{Binding}" VerticalAlignment="Center"/> </StackPanel> </DataTemplate> <!-- Common style --> <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Setter Property="Margin" Value="5 3"/> </Style> <!-- Specific style for A --> <Style x:Key="buttonStyleA" TargetType="{x:Type Button}" BasedOn="{StaticResource buttonStyle}"> <Setter Property="ContentTemplate" Value="{StaticResource buttonContentA}"/> <Setter Property="Command" Value="ApplicationCommands.Open"/> </Style> <!-- Specific style for B --> <Style x:Key="buttonStyleB" TargetType="{x:Type Button}" BasedOn="{StaticResource buttonStyle}"> <Setter Property="ContentTemplate" Value="{StaticResource buttonContentB}"/> <Setter Property="Command" Value="ApplicationCommands.Close"/> </Style> <!-- Let the list items of type ButtonDescription be shown as Button --> <DataTemplate x:Key="ButtonsListItemTemplate"> <Button Content="{Binding ButtonContent}"/> </DataTemplate> </Window.Resources> <Grid x:Name="grid1"> <StackPanel> <CheckBox x:Name="TargetDescriptor" Content="Copy to List A" IsChecked="True" Margin="3 5"/> <Button Content="Click me please" Click="Button_Click" Margin="3 5" MinHeight="28"/> <TextBlock FontWeight="Bold" Text="List A" Margin="3 5"/> <ItemsControl ItemsSource="{Binding ButtonListA}" ItemTemplate="{StaticResource ButtonsListItemTemplate}"> <ItemsControl.Resources> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource buttonStyleA}"/> </ItemsControl.Resources> </ItemsControl> <TextBlock FontWeight="Bold" Text="List B" Margin="3 5"/> <ItemsControl ItemsSource="{Binding ButtonListB}" ItemTemplate="{StaticResource ButtonsListItemTemplate}"> <ItemsControl.Resources> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource buttonStyleB}"/> </ItemsControl.Resources> </ItemsControl> </StackPanel> </Grid> </Window>
common-pile/stackexchange_filtered
Slide-able UIView menu that responds to UIGestureRecognizer So what I am trying to do with this view is make it so that i can slide the UIView (menuView) up and down in and out of the screen. So in storyboard/IB i placed a UIView and connected it to files owner and all that jazz. then i entered the program the below code. The problem is that when the nib loads it doesnt put the UIView where it should be in the first place and then the swipe doesn't work on it. I tried this method of programming with a button and it worked fine. Thanks in advance for any help you may have on the subject. .h file UIView *menuView; } @property (strong, nonatomic) IBOutlet UIView *menuView; .m file @synthesize menuView; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)]; [swipeGesture setDirection:UISwipeGestureRecognizerDirectionDown]; [self.view addGestureRecognizer:swipeGesture]; menuView = [[UIView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)]; [menuView setFrame:CGRectMake(0, -80, 320, 80)]; [self.view addSubview:menuView]; } -(void)swipe:(UISwipeGestureRecognizer*)sender { [UIView animateWithDuration:0.5 animations:^{ [menuView setFrame:CGRectMake(0, 0, 320, 80)]; }]; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } You've set up your menuView as a storyBoard/IB outlet. That means the xib/nib/storyboard is doing the alloc-init and initial framing. So you should remove this line: menuView = [[UIView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)]; You can also remove the next line from viewdidLoad: [menuView setFrame:CGRectMake(0, -80, 320, 80)]; There it's superfluous. It was already done by "initWithFrame" -- which is already done by the nib. On the other hand, it might be hard to position something offscreen in a nib. So you might actually reinstate the setFrame: line -- but in viewWillAppear rather than viewDidLoad. viewWillAppear is called after the nib has done its thing, so the nib is out of the way and won't interfere with your reframing. Make those changes and, if "all that jazz" includes connecting menuView to a reference outlet, you should be good to go. none of it worked. The "menuView" still wont slide around like it's programmed to do.
common-pile/stackexchange_filtered
Uncaught ReferenceError: $ is not defined while Adding webticker I've been getting this error: Uncaught ReferenceError: $ is not defined I've done the basics right but still it show this. What am I doing wrong? Here is my script. I'm using DOM elements to create this. var parenthead = document.head; sjq = document.createElement("script"); sjq.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"; parenthead.appendChild(sjq); swt = document.createElement("script"); swt.src = "http://otexconnect.com/jquery.webticker.min.js"; parenthead.appendChild(swt); $("#webticker").webTicker(); Here is my HTML <ul id="webticker"> <li id="item1">Some text</li> </ul> Any sort of help will be appriciated. Thanks Any reason why you load your scripts via JavaScript instead of using plain script tags? Also it's possible you're executing $("#webticker").webTicker(); before jQuery has finished loading. Im writing a service in script form to be included from another website so i can not really write html tags directly. You call a function that is not yet ready for use, you need a callback, did a load function, when all scripts are ready it will call the callback statement. <ul id="webticker"> <li id="item1">Some text</li> </ul> <script> var libsToLoad = ['http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', 'http://otexconnect.com/jquery.webticker.min.js']; function load(array,cb){ var ready = false; var lib = null; var parenthead = document.head; var totalItens = array.length; var loaded = 0; while(lib = array.shift()){ console.log('lib',lib); var script = document.createElement("script"); script.src = lib; parenthead.appendChild(script); script.onload = function(){ loaded++; if(loaded == totalItens){ ready = true; cb(); } }; } } load(libsToLoad,function(){ console.log('ready'); console.log($); console.log($("#webticker li").html()) //Make your logic here }); </script> +1 for loading function. Now I know my html is loading first but still jQuery error is being occurred in my jquery.webticker.min.js file at the end line })( jQuery ); . Any idea why. Even though the jQuery file is included first and the version jquery.webticker.min.js requires is 1.4.0 or above and i have included 1.11.1 I tested here and the only way that happened this error, was without including the jQuery. I hope that you find answer.
common-pile/stackexchange_filtered
Rails Form: post to external form and redirect to external response page Is there a way for the customer to fill in the credential in my Rails App and the app posts to an external form? If the credentials are correct, the customer will be redirected to the external response page. As if my Rails App is behaving as the external website. Thanks! You can redirect to external page with GET method but I can't do this via POST. if user_signed_in? redirect_to http://external.page/ # this will use GET METHOD end redirect_to using POST in rails This answer your question?
common-pile/stackexchange_filtered
pass data result from python to Java variable by processbuilder I used process builder to run a python script from java. and i can sent the data from Java to python variable ( import sys to get data from Java) . and print out the python result in java. for example: public static void main(String a[]){ try{ int number1 = 100; int number2 = 200; String searchTerm="water"; ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","D://my_utils.py",""+number1,""+number2,""+searchTerm); Process p = pb.start(); BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream())); System.out.println(".........start process........."); String line = ""; while ((line = bfr.readLine()) != null){ System.out.println("Python Output: " + line); } System.out.println("........end process......."); }catch(Exception e){System.out.println(e);} } } However, I do not know how to get back the result from python and pass the result to JAVA Variable for further use. How to do that? I have issue with passing a list as a method argument in JAVA. [![enter image description here][1]][1] [![enter image description here][2]][2] How to pass the variable (return variable in def MatchSearch() in python) to the JAVA VARIABLE? u can save the python result in JSON format. and use java to read parser the json file to get the content so as to create the variable. As far as I am aware, you can't do that with ProcessBuilder. You can print your variable to the output and let Java interpret it. Or you can use some API that is connecting Java and Python stronger (for example Jython). i can only use the process builder. Jython the lib is too limited @HiPownedBi I have the same problem :/ Then parsing is the only option I fear
common-pile/stackexchange_filtered
How to randomize the position of a variable in a grid (in python) I have been making a game in python where a 2x2 grid containing four letters is displayed. One of the letters is replaced with a new letter. Each time the grid is displayed, the new letter must be a different letter and it must have a different position on the grid. I have created a variabe called 'newletter', but i am having trouble randomizing the position of this variable on the grid each time it is displayed. My code so far works, but it does not change the position of the variable. 'letters' is a textfile which contains 5 different letters random.shuffle (letters) print (letters[0]+ " " +letters[1]) print (letters[2]+ " " +letters[3]) random.shuffle (letters) replacedletter = letters[3] newletter = letters[4] print (letters[0]+ " " +letters[1]) print (letters[2]+ " " +newletter) Any help would be appreciated Here's a simpler approach. # 4 letters, for sanity grid = ['a','b','c','d'] # determine replacement letter new_letter = 'e' # get random position (4-value list has positions 0,1,2,3) position = random.randint(0,3) # set the position to a new value grid[position] = new_letter # one letter should have been set to 'e' print grid This is really helpful but the letters need to be presented in a 2x2 grid. I'm having trouble randomizing the position of the new word because its in a grid format.
common-pile/stackexchange_filtered
How do I change SQL Server 2012 Availability Group DNS subdomain? Questions: how can I get my availability group to be registered as ag-ewgtest.sql.company.com given that my server thinks of itself as server.company.com. Setup: my SQL Server 2012 availability group is on multiple subnets, similar to what's described at in this MSDN blog article. When I go into Failover Cluster Manager, it shows that name resolution is not yet available: I then right-click "Name: ag-ewgtest" and choose properties. I check off "Publish PTR records" and it shows me that the full name is ag-ewgtest.company.com. The problem I have is that I'm only being allowed to update the DNS zone sql.company.com. If I change the DNS name to be ag-ewgtest.sql.company.com then the full name becomes ag-ewgtest.sql.company.com.company.com. I've tried updating my NIC as: But hasn't made a difference. How can I change the subdomain that my availability group tries to register itself in? The Availability Group Listener name is a Computer Name Object (CNO) in Active Directory, not just a DNS entry: http://technet.microsoft.com/en-us/library/ff367878(v=exchg.150).aspx Its location in AD determines where it gets registered. If you want to create a different one somewhere else, you can create a DNS CNAME (alias) pointing to the real Availability Group Listener name: http://technet.microsoft.com/en-us/library/ff625726(v=ws.10).aspx this implies there is no way to change the subdomain that my availability group tries to register itself in and that I need a manual workaround. Is this correct? To add, I'm assuming this is correct so I'll be happy to accept this answer unless anyone can provide a solution to the question I originally asked in the next few day. I've started looking for manual workarounds and posted this at http://serverfault.com/questions/502898/ddns-client-for-windows What's the logic behind this requirement from the sysadmin side? The cluster is going to register the DNS in the same domain that the cluster exists in, not a subdomain of the domain that the cluster is in. You can put a CNAME in place in sql.company.com that points to your DNS name in company.com, but you'll need to be able to update the DNS record in company.com for the cluster to work correctly. Editing DNS records in the company.com zone has the potential to affect 10's of thousands of records. The Network Team is trying to scope DNS write permissions to a limited zone that would only affect SQL Servers. By default in Windows DNS the machine that creates the DNS record is the only one that can change the DNS record. All computers that exist within the domain have the ability to change their own DNS records within the company.com DNS zone. It sounds like the network team needs a better understanding of how AD DNS works and how Windows DNS is secured. They are making it a lot harder than it needs to be. I don't know enough about the DNS, but we use BIND for our nameservers. My understanding is that they can give my IP address permission to update records in the company.com zone, but they can't make it more granular than that. I could definitely be wrong on that and can follow up next week after talking to them. They also suggested securing DNS write permissions using TSIGs, but based on the lack of responses I got at http://serverfault.com/questions/500342/ddns-from-windows-bind-with-dhcp-keys I don't think that's an option. Ah, you are using a non-standard DNS config which is why so few people are able to help you. Basically no one sets up their DNS this way which is why you aren't finding any useful answers. In a nut shell, they aren't going to get to secure things the way that they want. If they had gone with Microsoft's DNS servers everything would be much easier to configure, but using BIND you are going to be limited in what can be done. For the automatic failover between subnets to work the cluster has to update DNS. The other option is to update DNS manually and tell the cluster not to register DNS. Considering that BIND has many times the market share that Microsoft has for DNS servers I'm not sure it could would be correct to call this a non-standard DNS config. I think it's a limitation of AlwaysOn Availability Groups that they do not give you the ability to configure the DNS domain you use for them. While I agree that BIND has a much higher adoption than Microsoft DNS, I'd also say that Microsoft DNS has a much higher adoption when being used for Active Directory's DNS which is what matters for this. It isn't a limitation of AlwaysOn's Availability Groups, it's a limitation of Failover Clustering which the Availability Group is using. Either way there's no work around.
common-pile/stackexchange_filtered