Posts

Showing posts from September, 2010

ruby on rails - gocardless webhook signature mismatch -

i going through gocardless getting started guide, when try setup webhook (sandbox mode), don't correct value. the code copy-pasted https://developer.gocardless.com/getting-started/api/staying-up-to-date-with-webhooks/#building-a-webhook-handler and looks this computed_signature = openssl::hmac.hexdigest(openssl::digest.new('sha256'), secret, request.raw_post) provided_signature = request.headers['webhook-signature'] rack::utils.secure_compare(provided_signature, computed_signature) # => false what missing? help

python - How to add language code to URL in Pyramid? -

i've created basic pyramid "hello world" template project , added i18n support. i'm using python 3.5 , chameleon templates ( .pt ) gettext. i can change language through .ini file. now make dynamic , read language code url. urls changed /<language code>/page/{possible params} example /fi/home . don't want add {language} existing routes/views language code parameter hidden , views don't know except when creating links other pages in templates/views. edit: here's attempt using tweens mentioned mikko ohtamaa: added __init__.py : config.add_tween('myapp.tweens.localizertween') tweens.py : import logging pyramid.registry import registry pyramid.request import request log = logging.getlogger(__name__) class localizertween(object): """ set translator based on url """ def __init__(self, handler, registry: registry): self.handler = handler self.registry = registry def __call__(...

python - Update dataframe values by broadcasting series -

Image
trying update portion of dataframe values series. np.random.seed(1) df = pd.dataframe(np.random.randint(1,100,(5,5)),columns =list('abcde')) print df b c d e 0 38 13 73 10 76 1 6 80 65 17 2 2 77 72 7 26 51 3 21 19 85 12 29 4 30 15 51 69 88 with series: ser = pd.series(index =list('cbade'),data = range(-5,0)) c -5 b -4 -3 d -2 e -1 dtype: int64 lets take slice updating criteria = df['a'] < 25 criteria: 0 false 1 true 2 false 3 true 4 false trying: df[criteria] = ser df.loc[criteria,:] = ser etc. desired output: b c d e 0 38 13 73 10 76 1 -3 -4 -5 -2 -1 2 77 72 7 26 51 3 -3 -4 -5 -2 -1 4 30 15 51 69 88 i want honor column index , ignore row index, using boolean criteria , broadcasting. you can fillna series can make df np.nan mask works df.mask(criteria).fillna(ser)

Symfony 3.1 swiftmailer email doesn't send -

i wanted send test email using symfony 3.1 , swiftmailer, doesn't work. reading other solutions, still doesn't work. config.yml: swiftmailer: transport: %mailer_transport% encryption: %mailer_encryption% auth_mode: %mailer_auth_mode% host: %mailer_host% username: %mailer_user% password: %mailer_password% spool: { type: memory } parameters.yml mailer_transport: smtp mailer_encryption: ssl mailer_auth_mode: login mailer_host: smtp.gmail.com mailer_user: user@gmail.com mailer_password: mypass parameters.yml v.2 trying: mailer_transport: gmail mailer_encryption: ssl mailer_auth_mode: login mailer_host: smtp.gmail.com mailer_user: user@gmail.com mailer_password: mypass controller: public function contactaction(request $request) { $name = $request->request->get('name'); $surname = $request->request->get('surname'); ...

curl - C++ Codeblocks + libcurl ends up with link errors -

hi c++ beginner , wanted learn http requests... picked curl because have experience using before php. downloaded version curl website c:\libs win64 x86_64 7zip 7.51.0 binary ssl ssh viktor szakáts 1.81 mb this i've done far on codeblocks: under global compiler settings/search directories/compiler, added path: c:\libs\curl-7.51.0-win64-mingw\include\curl under global compiler settings/search directories/linker, added path: c:\libs\curl-7.51.0-win64-mingw\lib under global compiler settings/linker settings, added paths: c:\libs\curl-7.51.0-win64-mingw\lib\libcurl.a c:\libs\curl-7.51.0-win64-mingw\lib\libcurldll.a -under global compiler settings/compiler settings, box checked before: have g++ follow c++11 standard... (no idea if matters or not...) also, because desperate copied contents of c:\libs\curl-7.51.0-win64-mingw c:\program files (x86)\codeblocks\mingw, step makes no sense me, found online tried... now running code: #include <cstring...

linux - How to write a bash script to test table of logins? -

i've participated in hacking competition in school. came solution didn't knew how code here asking help. the problem involved security breach on server. files gmail usernames:passw had been leaked , we, infosec team, had test logins compromised (if users hadn't changed pw yet) email them. idea was: first, cat files using cat * > merged-file . then, somehow create mechanism test each combination usr + pw on gmail putting flag or creating file successful ones. sorry bad english, i'm not native speaker. you can check username , password using curl curl -u $username:$password --silent "https://mail.google.com/mail/feed/atom" | grep "<title>" it return <title>unauthorized</title> if combination not correct.

linux - Implementation of multiple pipelines and command executions in C -

i have homework asks me create shell executes multiple commands separated pipelines. here code snippet forking childs , executing commands: (int = 0; < commands; i++) { place = commandstarts[i]; if((pid = fork()) < 0) exit(1); else if (pid == 0) { if(i < pipe_counter && dup2(fds[j + 1], 1) < 0) exit(1);// if not last remaining command if(j != 0 && dup2(fds[j-2], 0) < 0) exit(1); // if not first command for(int c = 0; c < 2*pipe_counter; c++) close(fds[c]); if(execvp(argv[place], argv+place)) exit(0); // execute , if returns anything, exit! } j+=2; } for(int = 0; < 2 * pipe_counter; i++) close(fds[i]); while ((wait(&status)) != pid); // program gets point // parent process, should wait completion even though, seems working fine in simple examples, in m...

javascript - Creating parent and child elements wit Js/jQuery -

Image
i'm beginner @ js/jquery. want code structure js/jquery: <div class="box"> <p>1</p> <div class="content"><span>lorem</span></div> </div> <div class="box"> <p>2</p> <div class="content"><span>ipsum</span></div> </div> <div class="box"> <p>3</p> <div class="content"><span>dolor</span></div> </div> <div class="box"> <p>4</p> <div class="content"><span>sit</span></div> </div> <div class="box"> <p>5</p> <div class="content"><span>amet</span></div> </div> i have code: function adddivs(n) { for(var i=1; i<=n; i++) { var parentp = $("<p>"+i+"</p>"); ...

c - How can an (int) be converted to (unsigned int) while preserving the original bit pattern? -

suppose define: short x = -1; unsigned short y = (unsigned short) x; according c99 standard: otherwise, if new type unsigned, value converted repeatedly adding or subtracting 1 more maximum value can represented in new type until value in range of new type. (iso/iec 9899:1999 6.3.1.3/2) so, assuming 2 bytes short , two's complement representation, bit patterns of these 2 integers are: x = 1111 1111 1111 1111 (value of -1), y = 1111 1111 1111 1111 (value of 65535). since -1 not in value range unsigned short , , maximum value can represented in unsigned short 65535, 65536 added -1 65535, in range of unsigned short . bits remain unchanged in casting int unsigned , though represented value changed. but, standard says representations may two's complement, one's complement, or sign , magnitude. "which of these applies implementation-defined,...." (iso/iec 9899:1999 6.2.6.2/2) on system using one's complement, x represented 1111 1111...

Error calling range in Excel table causing crash -

complete vba newbie here. i'm trying adapt code found on ron de bruin's site (bmail9.html specific tutorial/example). code straightforward enough , works in de bruin's file. i able adapt work column name [days until liquidation due] within excel table [tbl_countdown] on secondary worksheet [interface2] of workbook. (this link file in question. 1 ) however, when tried shift focus column name [days until liquidation due] in excel table [tbl_interface] in primary worksheet [interface] , code has failed spectacularly: crashes excel (2013). ( this link screenshot of error message on opening file. ) , re-open it, error message generated. , more not (although not 100% of time), crashed excel regardless of whether choose 'end' or 'debug'. option explicit private sub worksheet_calculate() dim formularange range dim countdownrange range dim notsentmsg string dim mymsg string dim sentmsg string dim mylimit double dim countdownf...

multithreading - C++: Is the passing of a mutex from a notifier to a waiter seamless? -

in multithreaded environment, have following 2 functions: std::mutex mtx; std::condition_variable cv; void waiter() { std::unique_lock<std::mutex> lck(mtx); //... cv.wait(lck); //... } void notifier() { std::unique_lock<std::mutex> lck(mtx); //... cv.notify_one(); } assume waiter executes first , waits on condition_variable. notifier executes , notifies waiter. waiter tries reacquire mutex after notifier has released it. question: possible other thread locks mutex right after notifier has released still before waiter gets it? if yes, has done cannot happen? , if yes, don't understand purpose of condition_variable. purpose should block thread until condition fulfilled. if, after condition fulfilled , thread has been woken up, there chance again condition not fulfilled, what's point? is possible other thread locks mutex right after notifier has released still before waiter gets it? yes. if yes, has done cannot ...

c++ - Process snapshot can't be compared against wide strings -

i have following problem: i want keep track of running processes using createtoolhelp32snapshot , process32first/next. want use unicode charset default. bool active( const std::wstring& process_name ) { handle snapshot = createtoolhelp32snapshot( th32cs_snapprocess, 0 ); if ( snapshot == invalid_handle_value ) return false; processentry32 entry; if ( process32first( snapshot, &entry ) ) { if ( process_name.compare( entry.szexefile ) == 0 ) { closehandle( snapshot ); return true; } } while ( process32next( snapshot, &entry ) ) { if ( process_name.compare( entry.szexefile ) == 0 ) { closehandle( snapshot ); return true; } } closehandle( snapshot ); return false; } int main( ) { setconsoletitle( l"lel" ); if ( active( l"notepad++.exe" ) ) std::cout << "hello" <...

Got a loop in Excel sheet vba -

i doing sheet has cell let user put in downpayment amount displays percent is. have row has unlocked cell user enter percent , fill in downpayment amount. know awkward , want have 1 cell downpayment , 15% having trouble writing formula it. because skill bad, used event handler on "sheet1 change" looks change in fields , hides 1 hasn’t been used bigger problem have button on sheet clear of unlocked cells @ once when calculations done. "clear cells" button clears cells have referenced in "worksheet change" code , causes loop. if there better way enter formula on bar have 1 row has both cell percent , cell downpayment amount , have user enter 1 of them , other autopopulates. ie: downpayment/total amount fills % cell. or if entered percent percent * total amount fills dollar value in downpayment amount. sorry if confusing trying keep clear. private sub worksheet_change(byval target range) if target.address = "$b$5" msgbox "...

Regex first and last characters must be a number -

could please me come correct regex match string starts , ends digit. string between these 2 digits may have , , . , digits only. i have tried: ([0-9.,]+) strings match: ,5,190 ,5,190, output should 5,190 . alright let's take definition bit bit: string starting number. [0-9] or \d same thing. string may have , , . , consist numbers. `[\d,.]* string ends number. \d which gives \d[\d,.]*\d . try it, , please try understand before moving on.

wordpress - echo mysql select statement with wpdb displays NO RESULTS -

i function in plugin return data when it's called for . i'm trying result @ point. used more specific query. function ml_results() { global $wpdb; $results = $wpdb->get_results( 'select * wp_ml_char', object ); echo "<p>your character's info {$results}</p>"; } add_shortcode('ml_return', 'ml_results'); i've had no luck returning , displaying output_type. i've tried print instead of echo. i've tested query in phpmyadmin works fine. returned "array". so, $results returns "your character's info array". var_dump works fine, that's not how data displayed. belive problem lies in wordpress code, i'm not sure part of code exactly. your results returned in array, why, can't printed out string. actually, have set flag object, , results being returned object, containing field values records in wp_ml_char table. should try this: function ml_results() { global $wpdb; $re...

Twitter OAuth error 32 (401) using Unirest Java -

i using unirest build http request: httprequestwithbody request = unirest .post("https://api.twitter.com/1.1/statuses/update.json") .header("authorization", oauth) .header("content-type", "application/x-www-form-urlencodedheader") .querystring("status", "123testtest"); so far can't see issues this. maybe problem in creating oauth signature? private string percentencode(long toencode) { try { string returnstring = urlencoder.encode(toencode.tostring(), "utf-8"); return returnstring.replace("+", "%20"); } catch (unsupportedencodingexception e) { return ""; } } private string percentencode(string toencode) { try { string returnstring = urlencoder.encode(toencode, "utf-8"); return returnstring.replace("+", "%20"); } catch (un...

ubuntu - Tomcat fail to start after 1st successful run -

root@ubuntu-512mb-sfo1-01:~# sudo systemctl start tomcat root@ubuntu-512mb-sfo1-01:~# sudo systemctl status tomcat ● tomcat.service - apache tomcat web application container loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: enabled) active: activating (auto-restart) (result: exit-code) since sat 2016-11-05 17:40:01 utc; 3s ago process: 19639 execstop=/opt/tomcat/bin/shutdown.sh (code=exited, status=1/failure) process: 19624 execstart=/opt/tomcat/bin/startup.sh (code=exited, status=0/success) main pid: 19636 (code=exited, status=1/failure) nov 05 17:40:01 ubuntu-512mb-sfo1-01 systemd[1]: tomcat.service: control process exited, code=exited status=1 nov 05 17:40:01 ubuntu-512mb-sfo1-01 systemd[1]: tomcat.service: unit entered failed state. nov 05 17:40:01 ubuntu-512mb-sfo1-01 systemd[1]: tomcat.service: failed result 'exit-code'.

java - Hsqldb doesn't get populated with data -

i want insert sql data when run datasource configuration can't data in test class. works if create data first inside test class , getting though. @configuration @enablejparepositories("se.system.repository") public class dbconfig{ @bean(name = "hsqldb") public datasource inmemorydatasource() { embeddeddatabasebuilder builder = new embeddeddatabasebuilder(); embeddeddatabase database = builder .settype(embeddeddatabasetype.hsql) .addscript("classpath:se/system/sql/create-db.sql") .setname("database") .build(); return database; } @bean public jpatransactionmanager transactionmanager(entitymanagerfactory factory) { return new jpatransactionmanager(factory); } @bean public jpavendoradapter jpavendoradapter() { hibernatejpavendoradapter adapter = new hibernatejpavendoradapter(); adapter.setdatabase(database.hsql); adapter.setshowsql(false); adapter.setgene...

ios - Trying to save UiimageView but code is saving all of the page. In swift -

these 5 lines of code saving photo saving whole screen. save button acting screen on laptop. have uiimageview outlet imagepicker displays photo. want uimmmageview saved , not whole page. my outlets name camerascreen. have tried insert in code not work. app takes photo , puts graphic on well. here code import uikit class camera: uiviewcontroller, uiimagepickercontrollerdelegate, uinavigationcontrollerdelegate, uitextfielddelegate { @iboutlet weak var camerascreen: uiimageview! var screenview: uiimageview! @ibaction func camera(_ sender: anyobject) { if uiimagepickercontroller.issourcetypeavailable(uiimagepickercontrollersourcetype.camera){ let imagepicker = uiimagepickercontroller() imagepicker.delegate = self imagepicker.sourcetype = uiimagepickercontrollersourcetype.camera; imagepicker.allowsediting = false self.present(imagepicker, animated: true, completion: nil)}} func imagepickercontroller(_ picker: uiima...

while loop - where have i went wrong with my code? -

attempt = 0 answer = "canberra": while answer != "canberra" input("what capital of australia: ?") print(attempt) i don't know whats wrong it. basically, task write code repeatedly ask user question until answer correct. however, when run code, repeatedly asks question when answer question correctly. able "if" statements task requires use "while" loops please, if can, help!!(don't on complicate though.) :) loops it's unclear programming language use. think it's python :) you should increment attempts counter in while loop this: attempt += 1 in beginnig of while loop comparing variable answer string 'canberra'. comparsion returns false because variable answer have 'canberra' inside. "canberra" != "canberra" => false . you have colon @ end of line answer = "canberra": , should @ end of next line while answert ... . the code: attempt = 0 ...

logging - How to send weblogic server logs to graylog? -

Image
we sending applicatios logs graylog logback config. want send weblogic server logs graylog. how can that? thanks i work oracle commerce on weblogic, , wanted investigate using graylog. able setup test environment using graylog amis on aws ec2. used collector-sidecar on redhat machine running weblogic 12.1.3.0.0. if follow directions here: http://docs.graylog.org/en/2.2/pages/collector_sidecar.html pretty simple do. took me 2 hours total (about 1 hour of spent trying figure out why servers couldn't talk on port 5400 - ec2 security profile wasn't setup port open - duh). the things found bit confusing in terminology, input , output... these in terms of collector-sidecar, not graylog server, nor beats backend (i used filebeat on nxlog). input data coming collector-sidecar log file (and pointed instance.out file weblogic), , output going collector-sidecar graylog server.

c++ - Why can templates only be implemented in the header file? -

quote the c++ standard library: tutorial , handbook : the portable way of using templates @ moment implement them in header files using inline functions. why this? (clarification: header files not only portable solution. convenient portable solution.) it not necessary put implementation in header file, see alternative solution @ end of answer. anyway, reason code failing that, when instantiating template, compiler creates new class given template argument. example: template<typename t> struct foo { t bar; void dosomething(t param) {/* stuff using t */} }; // somewhere in .cpp foo<int> f; when reading line, compiler create new class (let's call fooint ), equivalent following: struct fooint { int bar; void dosomething(int param) {/* stuff using int */} } consequently, compiler needs have access implementation of methods, instantiate them template argument (in case int ). if these implementations not in header, wouldn...

python - Using IMDB data for the sci-kit regression models package which has text values in feature variables -

i have csv file containing imdb movie ratings data. file has 27 features , 1 target variable. have attached sampledata . , data set can downloaded kaggledata . have learnt sklearn package of python requires data in numbers. how use data regression analysis? right have used below code, says "some director name" can't converted float. import pandas pd sklearn.linear_model import linearregression df = pd.read_csv('d:\machine learning\final\movie_metadata.csv') feature_cols = [ "director_facebook_likes", "cast_total_facebook_likes", "movie_facebook_likes", "facenumber_in_poster", "gross", "num_critic_for_reviews", "num_voted_users", "num_user_for_reviews", "duration", "title_year", ...

"require at least one field" for magento advanced search -

my magento 1.9 advanced search allows search without enter search term. leads 10 secounds of loading time , ends @ page says "no results". is there way change advanced search button "search" can pressed when entered? thanks!!

Still not get my SoundCloud API key -

i completed formular api key app, it's been more 2 weeks , did not receive answer. how can contact soundcloud please ? thank in advance help. they take 2-3 weeks before respond. email api@soundcloud.com you can try calling on +4930467247600 have not worked me. lastly read online 1 person heard nothing them weeks , checked soundcloud developer page under 'your apps' , app there set , client id , secret etc. never informed got it. story in case.

php - Laravel 5.3 relationship -

here code: class company extends model { public function employees() { return $this->hasmany('employee'); } } class employee extends model{ protected $table = "user_role_company"; public function user(){ return $this->belongsto('user'); } public function company(){ return $this->belongsto('company'); } } class user extends authenticatable { public function employee(){ return $this->hasmany('employee'); } } if run: $recordstotal = user::with(['employee' => function ($query) use ($company_id) { $query->where('company_id', $company_id); }])->count(); it returns users count not empolyee count. what doing wrong? thanks first of all, have 'company_id' , 'user_id' column in employee model/db? anyways, can try query instead. $recordstotal = user::wherehas('employee', function ($q) use (...

c++ - In a linked list, in what order are nodes removed by the destructor? -

this question has answer here: stl containers element destruction order 2 answers in linked list, in order nodes removed destructor? does go first last or last first? either order possible -- way inspect specific implementation you're using. in general, singly-linked list, expect first-to-last ordering because it's easier implement , bit more efficient: linkedlist::~linkedlist() { node *node = mhead; while (node) { node *next = node->mnext; delete node; node = next; } } versus last-to-first ordering, singly-linked list require sort of recursion: void deletelist(node *node) { if (node == 0) { return; } deletelist(node->mnext); delete node; return; } linkedlist::~linkedlist() { deletelist(mhead); } so again -- way sure @ linked list implementation.

ios - cellForRowAtIndexPath never called in UITableViewController -

cellforrowatindexpath never called (numberofrowsinsection is) using uitableviewcontroller following way: import uikit import eventkit class eventthisweekcontroller: uitableviewcontroller { var eventstore: ekeventstore = ekeventstore() var eventsthisweek: [ekevent] = [] override func viewdidload() { super.viewdidload() self.eventstore.requestaccesstoentitytype(.event) { (granted, error) -> void in guard granted else { fatalerror("permission denied") } let enddate = nsdate(timeintervalsincenow: 604800) let predicate = self.eventstore.predicateforeventswithstartdate(nsdate(), enddate: enddate, calendars: nil) self.eventsthisweek = self.eventstore.eventsmatchingpredicate(predicate) print(self.eventsthisweek.count) ...

c# - How do I move a sprite in a map of tiles larger then the screen? -

i'm bussy creating game sprite can move around map. problem map larger screen , i'm wondering how let sprite move, while staying @ center of screen. the solution : moving tiles instead of sprite, don't know if that's valid, , then, can guys give me advice how achieve this? i hope guys can me out one, because have been browsing ages... edit : game want create survival. need walk , resources stay alive. need make map sprite can walk on map has bigger screen size, , how possible sprite move examaple tile xpositiontile 5000 / ypositiontile 4000? hard me find information problem.. this game programmed in c# in windows forms using visual studio. not use engine.

c++ - Using $(OutDir) in Visual Studio .rc file -

in visual studio c++ project’s .rc file, there 2 included assemblies sources specified using relative paths. instead i’d specify these relative output directory. here’s i’m starting with: #ifndef apstudio_invoked ///////////////////////////////////////////////////////////////////////////// // // generated textinclude 3 resource. // language lang_neutral, sublang_neutral #ifdef _debug exceldna.loader assembly "..\\exceldna.loader\\bin\\debug\\exceldna.loader.dll" exceldna.integration assembly "..\\exceldna.integration\\bin\\debug\\exceldna.integration.dll" #else exceldna.loader assembly "..\\exceldna.loader\\bin\\release\\exceldna.loader.dll" exceldna.integration assembly "..\\exceldna.integration\\bin\\release\\exceldna.integration.dll" #endif ///////////////////////////////////////////////////////////////////////////// #endif // not apstudio_invoked ...

Java: Reading an array of a directory to display the images contained in the directory to be able to go forwards and backwards through the array -

hello , assistance in advance. my goal load directory called resource create array. after doing program should use "next" , "previous" button cycle both forwards , backwards through array using counter. cycling through array should display appropriate picture (without knowing picture is, order in array). my code far: import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jlabel; import javax.swing.jbutton; import javax.swing.boxlayout; import javax.swing.jtextfield; import java.io.ioexception; import javax.swing.imageicon; import java.io.*; import java.util.*; import java.nio.file.files; import java.nio.file.paths; import java.awt.*; import java.awt.event.*; public class viewer extends jframe implements actionlistener { int counter = 0; //initial counter value int maxitems = 0; // set equal length of array int minitems = 0; //minimum items previous button jpanel botpanel = null; jpanel midpanel = null; ...

c++ - How does boost::copy_graph's vertex_copy work? -

i using boost::copy_graph copy adjacency_list adjacency_list different vertexproperties template. this, trying use vertex_copy parameter ( doc here ). running compiler error tells have wrong type vertex properties of second (to-be-copied) graph. minimal example #include <boost/graph/adjacency_list.hpp> #include <boost/graph/copy.hpp> typedef boost::adjacency_list<boost::vecs, boost::vecs, boost::undirecteds, uint32_t, float> adjacencylist; typedef adjacencylist::vertex_descriptor vertexid; struct custom_property { uint32_t label; float f; }; typedef boost::adjacency_list<boost::vecs, boost::vecs, boost::undirecteds, custom_property, float> adjacencylistcustom; struct vertex_copier { void operator(...

c++ - Creating a Struct then passing a vector with those struct by reference -

i start off saying there many questions asked me quit hard understand explanations unless deals situation. here: full questions program working on. 11.7: customer accounts write program uses structure store following data customer account: customer name customer address city state zip code telephone account balance date of last payment the program should use array of @ least 20 structures. should let user enter data array , change contents of element , , display data stored in array . program should have menu-driven user interface. here example code because pasting full code b/c had go through , add 4 spaces @ beginning of each line. #include <iostream> #include <vector> #include <string> using namespace std; struct customeraccount{ string customername; string customeraddress; string customercity; string customerstate; int customerzipcode; string customertelephone; double customera...

for loop - Concurrent access to maps with 'range' in Go -

the " go maps in action " entry in go blog states: maps not safe concurrent use: it's not defined happens when read , write them simultaneously. if need read , write map concurrently executing goroutines, accesses must mediated kind of synchronization mechanism. 1 common way protect maps sync.rwmutex. however, 1 common way access maps iterate on them range keyword. not clear if purposes of concurrent access, execution inside range loop "read", or "turnover" phase of loop. example, following code may or may not run afoul of "no concurrent r/w on maps" rule, depending on specific semantics / implementation of range operation: var testmap map[int]int testmaplock := make(chan bool, 1) testmaplock <- true testmapsequence := 0 ... func writetestmap(k, v int) { <-testmaplock testmap[k] = v testmapsequence++ testmaplock<-true } func iteratemapkeys(iteratorchannel chan int) error { <-testma...

javascript - Jquery - animate after redirection -

i animate page after page redirected using jquery, problem code redirects ignores animation code, how can resolve issue ? $("#menu a:first-child").click(function() { window.location.href = "https://www.mysite/blog"; $('html,body').animate({ scrolltop: $("#mainwrapper").offset().top - 70}, 'slow'); }); (the animation scrolls down anchor fluid transition.) when redirect, current script stop. if 1 it, think there way, not recommend it, job. before redirect other page; assume new page still in same app, not totally different website), can set localstorage variable. @ beginning of js file of page redirect to, check if localstorage variable have set in earlier view there, if is, animation, remove localstorage variable. // js file of current view $("#menu a:first-child").click(function() { localstorage.setitem("animation", true) window.location.href = "http...

javascript - How can I allow two-finger scrolling over an HTML canvas element while allowing one-finger drawing? -

i attempting make canvas drawing app fixed size canvas - ability scroll around canvas draw on different points may not visible based on user's screen size. it scrolls on desktop, trying implement 2 finger scrolling on mobile. http://jsbin.com/qugabuh/edit in touch-drawing functions, tried following: const starttouch = function(e) { if (e.targettouches.length < 2) { ctx.beginpath(); x = e.changedtouches[0].pagex + content.scrollleft; y = e.changedtouches[0].pagey - 34 + content.scrolltop; ctx.moveto(x, y); } }; const movetouch = function(e) { if (e.targettouches.length < 2) { e.preventdefault(); x = e.changedtouches[0].pagex + content.scrollleft; y = e.changedtouches[0].pagey - 34 + content.scrolltop; ctx.lineto(x, y); ctx.stroke(); } }; this seems work okay on android tablet (although lines draw if don't lift both fingers off @ exact same time), not @ on iphone.

oauth - Web Api with Entity Framework code-first or database-first? -

this might big question. me out come out of this. i developing web api oauth (facebook, google). have database might undergo further modifications. i need implement generic repository pattern separate entities class library i need odata query support in it should follow standards (soc , unit of work) following questions confuse me database-first approach or code-first approach? how achieve minimum code? how can keep track of changes (migration in entity framework?) how enable odata in it? how have generic repository? is there way implement entire api in database-first approach , convert code-first approach? scaffolding api controller odata not simplify work in case of odata support, if how have generic dbcontext , generic repositories.

c# - Can't resize a borderless winform from top because of a docked panel -

i made borderless windows form, added drop shadow, ability drag, , ability resize angle, here's did, it's little messy: using system.runtime.interopservices; public class main { [dllimport("gdi32.dll", entrypoint = "createroundrectrgn")] private static extern intptr createroundrectrgn ( int nleftrect, // x-coordinate of upper-left corner int ntoprect, // y-coordinate of upper-left corner int nrightrect, // x-coordinate of lower-right corner int nbottomrect, // y-coordinate of lower-right corner int nwidthellipse, // height of ellipse int nheightellipse // width of ellipse ); [dllimport("dwmapi.dll")] public static extern int dwmextendframeintoclientarea(intptr hwnd, ref margins pmarinset); [dllimport("dwmapi.dll")] public static extern int dwmsetwindowattribute(intptr hwnd, int attr, ref int attrvalue, int attrsize); [dllimport("dwmapi.dll...