Posts

Showing posts from June, 2012

c - Why does rand() + rand() produce negative numbers? -

i observed rand() library function when called once within loop, produces positive numbers. for (i = 0; < 100; i++) { printf("%d\n", rand()); } but when add 2 rand() calls, numbers generated have more negative numbers. for (i = 0; < 100; i++) { printf("%d = %d\n", rand(), (rand() + rand())); } can explain why seeing negative numbers in second case? ps: initialize seed before loop srand(time(null)) . rand() defined return integer between 0 , rand_max . rand() + rand() could overflow. observe result of undefined behaviour caused integer overflow.

Android app - getting webpage content error -

currently code getting contents of html code (note starts @ line 45): public string refresh() { try { string link = "http://amethystmc.com/staff/android/serverstatus_essential.php?auth=android420"; url url = new url(link); urlconnection c = url.openconnection(); inputstream r = c.getinputstream(); bufferedreader reader = new bufferedreader(new inputstreamreader(r)); stringbuilder sb = new stringbuilder(); string line = null; // read server response while ((line = reader.readline()) != null) { sb.append(line); break; } return sb.tostring(); } catch (exception ex) { string stacktrace = ""; (stacktraceelement string : ex.getstacktrace()) { stacktrace += string + "\n"; } log.e("internet died", stacktrace); return new string("exception: " + stacktrace); } } ...

android - Different app name in play store -

when listing app in play store, possible have dynamically change on listing based on language listing being viewed? if so, how? at shore-listing in google play developer console, can add different language title, description , screenshots.

C++: Why doesn't what() throw an exception? -

in std::exception class , derived classes there virtual function called what() doesn't throw exception. why doesn't what() throw exception? what() method allows string (error message) associated exception: see reference documentation std::exception::what() it should not throw exceptions design. if want throw exception in c++ go with: throw std::exception("we going die");

plot - Plotting Probability Density Heatmap Over Time in R -

Image
let's have output of monte-carlo simulation of 1 variable on several different iterations (think millions). each iteration, have values of variable @ each point in time (ranging t=1 t=365). i produce following plot: each point in time, t, on x axis , each possible value "y" in given range, set color of x,y "k" "k" count of how many observations within vicinity of distance "d" x,y. i know can make density heatmaps 1d data, there package doing on 2 dimensions? have use kriging? edit: data structure matrix. data matrix day number [,1] [,2] [,3] [,4] [,5] ... [,365] iteration [1,] 0.000213 0.001218 0.000151 0.000108 ... 0.000101 [2,] 0.000314 0.000281 0.000117 0.000103 ... 0.000305 [3,] 0.000314 0.000281 0.000117 0.000103 ... 0.000305 [4,] 0.00...

jquery - Inserting two strings with the cursor in the middle of the two strings with JavaScript -

i trying create text editor. users can insert html code there. there toolbar. when user clicks 'add code' button, want <code></code> text inserted cursor @ middle of start , end tag. i have got following code insert text @ cursor position : function insertatcaret(areaid,text) { var txtarea = document.getelementbyid(areaid); var scrollpos = txtarea.scrolltop; var strpos = 0; var br = ((txtarea.selectionstart || txtarea.selectionstart == '0') ? "ff" : (document.selection ? "ie" : false ) ); if (br == "ie") { txtarea.focus(); var range = document.selection.createrange(); range.movestart ('character', -txtarea.value.length); strpos = range.text.length; } else if (br == "ff") strpos = txtarea.selectionstart; var front = (txtarea.value).substring(0,strpos); var = (txtarea.value).substring(strpos,txtarea.value.length); txtarea.value=front+text+back; strpos = strpos + text.length; if ...

java - I am attempting to store user input in one activity to a listview in another activity. It wont work -

i have been attempting store data listview separate items isn't working. if understands android studio , issue me helpful. think organization in mainactivity.java might why doesn't work. mainactivity.java has listview while newtask.java user inputs data such name of task , due date. have used startactivityforresult() still having issue. please help. mainactivity.java package com.example.shaan.todoer; import android.app.activity; import android.content.context; import android.content.intent; import android.support.v7.app.actionbaractivity; import android.os.bundle; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.arrayadapter; import android.widget.button; import android.widget.edittext; import android.widget.listview; import android.widget.textview; import java.util.arraylist; import java.util.list; public class mainactivity extends activity { arraylist<string> list = new arraylist<string>(); a...

c# - What is a NullReferenceException, and how do I fix it? -

i have code , when executes, throws nullreferenceexception , saying: object reference not set instance of object. what mean, , can fix error? what cause? bottom line you trying use null (or nothing in vb.net). means either set null , or never set @ all. like else, null gets passed around. if null in method "a", method "b" passed null to method "a". the rest of article goes more detail , shows mistakes many programmers make can lead nullreferenceexception . more specifically the runtime throwing nullreferenceexception always means same thing: trying use reference, , reference not initialized (or once initialized, no longer initialized). this means reference null , , cannot access members (such methods) through null reference. simplest case: string foo = null; foo.toupper(); this throw nullreferenceexception @ second line because can't call instance method toupper() on string reference pointing null ....

clojure - Why does y = 0 when I run println? -

how come when run (def y 0) (doseq [x (range 1000)] (if (or (= (mod x 3) 0) (= (mod x 5) 0)) (+ y x))) (println y) it prints 0 if no addition has taken place but (doseq [x (range 1000)] (if (or (= (mod x 3) 0) (= (mod x 5) 0)) (println x))) will print out of corresponding numbers match conditions? in clojure, values immutable. y is, , 0 of eternity. (+ y 1) 1, , 1. (+ y 1) not change value of y , evalutates result of adding 1 immutable value y . try this: (println (reduce (fn [y x] (if (or (= (mod x 3) 0) (= (mod x 5) 0)) (+ y x) y)) 0 (range 1000))) here, build y on time reducing on range in question. if match condition, add next value ( x ). if don't match condition, return y. look reduce function. note: there typos, wrote on phone

c - What's the difference using only one pthread_t variables and multiple pthread_t variables? -

i want know differences of using different number of pthread_t variables. here simple code made : #include <stdio.h> #include <pthread.h> void *thread(void *vargp); int main(int argc, char **argv) { pthread_t tid; (int = 0; < 5; i++){ int* = malloc(sizeof(int)); *a = i; pthread_create(&tid, null, thread, a); } if(pthread_join(tid, null) == -1){ printf("error"); exit(1); } } void *thread(void *vargp) { int count = 1; for(int = 0; <3; i++){ printf("count : %d, value : %d\n", count, (*(int *)vargp)); count++; } } it works mean to. however, thought strange create 5 threads using 1 pthread_t variable !.. saw examples using same number of pthread variables number of thread create. example, if gonna create 5 threads below, have create 5 length pthread_t array, pthread_t tid[5] . tell me what's differences? thanks ...

Remove specific XML element in Delphi -

i have xml document looks this: <?xml version="1.0"?> <person xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema"> <extensiondata /> <name>ali</name> <age>37</age> <father> <extensiondata /> <name>i</name> <age>72</age> </father> <mother> <extensiondata /> <name>m</name> <age>62</age> </mother> </person> i using delphi 7. how can remove extensiondata elements in xml document this? you can use ixmlnodelist.delete() or ixmlnodelist.remove() method remove nodes: var root: ixmlnode; begin root := xmldocument1.documentelement; root.childnodes.delete('elementdata'); := 0 root.childnodes.count-1 root.childnodes[i].childnodes.delete('elementdata'); end; var root, child, node: ixmlnode; begin ...

WAMP or XAMPP alternative that has Imagick already included -

recently lost hard drive had wamp installed , imagick working. else did part me way back. reinstalling win7 , getting working again = nightmare. installed latest version of wamp - no imagick. 3 days of trying solutions on site (and others - sorry) , got nowhere. know of "one shot" installation work out box? maybe fork of 1 of them - looked found nothing or maybe should install ubuntu onto old pc , use web server on home lan? - depreciating gd library time , imagick apparently successor no-one supports imagick natively. jumping through sorts of hoops no guarantee work either have painfully found out. in advance people. wamp , xampp not speed transition removed gd library imagemagic library , seem neither planning bring products date time soon. leaves many users major problem web site developers need able manipulate images @ time or during work. users not @ reasonably high level of expertize far messing around in guts of (in case, windows) operating systems, nightm...

c#.net winforms -

this question has answer here: what nullreferenceexception, , how fix it? 29 answers i new c#.net found following code in web , modified not working using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.data.sqlclient; namespace insertupdatedeletedatagridview { public partial class form1 : form { sqlconnection con = new sqlconnection(@"data source=(localdb)\v11.0;attachdbfilename=c:\users\bj\documents\visual studio 2013\projects\insertupdatedeletedatagridview\insertupdatedeletedatagridview\information.mdf;integrated security=true"); sqlcommand cmd; sqldataadapter adapt; //id variable used in updating , deleting record int id = 0; public form1() { ...

Android SwipeRefreshLayout with empty TextView not working properly -

what want , allow user swipe , refresh list, not matter if data there or not. when data there in listview listview should visible, , when data not there , empty textview should visible. in both cases user must able refresh list swipe. i tried solution given here in discussion none of them sounds working, idea of taking 2 swipetorefresh works fine given here , shows empty container while fetching data server. i tried own logic wrapping listview , textview inside relative/framelayout swipetorefresh accepts 1 view per behavior here xml snippet have tried <android.support.v4.widget.swiperefreshlayout android:id="@+id/activity_main_swipe_refresh_layout" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.945" > <relativelayout android:layout_width="match_parent" android:layout_height="match_parent" > ...

mysql - Decision to use KEY or UNIQUE KEY -

i understand unique key unique index , key non-unique index. have read in case of unique index'es inserting data might result in io. if don't have rely on db unique-ness , still want fast lookup's using column 'b' suggest use non unique index (key) instead of unique index (unique key)? both unique , non-unique indexes result in i/o operations insert , delete , , update statements. amount of index overhead should pretty same. difference unique indexes might result in failure of insert or update under normal use (of course, operations might fail other reasons, such disk being full, unusual circumstance). i don't understand statement: "if don't have rely on db unique-ness". unique attribute in table description of column/columns comprise key. 1 of functions of database maintain integrity of data, let database designed for. as performance, don't think there significant difference between unique , non-unique indexes. uniq...

javascript - how to reveal coupon code using php -

i want reveal coupon code on button click <script type='text/javascript' > jquery('#id1').click(function(){ jquery(this).replacewith("<?php echo $_coupon?>"); }) </script> <?php if ($_coupon != '' ):?> <button id="id1" type="button" class="but" value="button name"> </button> <?php endif; ?> this code works first button click means show 1 value not works loop please me solve problem i way: <script type='text/javascript' > jquery('#id1').click(function(){ jquery(this).replacewith(jquery(this).val()); }) </script> <?php if ($_coupon != '' ):?> <button id="id1" type="button" class="but" value="<?php echo $_coupon ?>"></button> <?php endif; ?>

Get video feeds using Youtube API v3 -

we have website displays our youtube video channels , favourite videos in our channel, etc. using youtube data api v2.0 fetch data. for example: https://gdata.youtube.com/feeds/api/users/ " + userid + "/playlists?v=2&alt=json-in-script&orderby=" + orderfeedsby + "&callback=? but these links return "networkerror: 410 gone". checked new youtube javascript api, didn't understand how migrate new api. please fix this. this url return json video ids playlist: https://www.googleapis.com/youtube/v3/playlistitems?part=id&playlistid= {playlist_id}&key={your_api_key} you need api key console.developers.google.com , playlist id. you can list of playlist ids channel url this: https://www.googleapis.com/youtube/v3/playlists?part=id&channelid= {channel_id}&key={your_api_key} documentation @ developers.google.com/youtube/v3/docs/

session array variable fatfree -

i playing own way of storing user selected items on simple shop system uses hidden int values( primary id item) form. on each selection test see if session variable has been set if not: if ($f3->get('session.item') == null) { $f3->set('session.item',array($itemfrompost )); ... } if has been set push next selection : $f3->push('session.item',$itemfrompost); it promising , can count of items like: $total = (count ( $f3->get('session.item') also can this: echo $f3->get('session.item[0]'); what doesn't work when want run through items: for ($i= 0; $i <= totalcountvalueminus1; $i++ ) { echo $f3->get('session.item[$i]'); } how do this?

c++ - makefile to link each other -

i have multiple unit test files in dir test, "test_a.cc" "test_b.cc" "test_c.cc"(each 1 has main function), , want build every 1 executable file, "test_a", "test_b", "test_c", each 1 executable file.so how write general makefile achieve goal? currently, using makefile this, want discard '.out' suffix: sources = $(shell find . -name '*.cc') objects = $(sources:.cc=.o) executable = $(sources:.cc=.out) : $(executable) %.out:%.cc $(cc) $(cflags) $< -o $@ "i want discard '.out' suffix" the simplest way achieve renaming executable file after build: %.out:%.cc $(cc) $(cflags) $< -o $@ mv $@ $(patsubst %.out,%,$@) another way leave out .out sources = $(shell find . -name '*.cc') objects = $(sources:.cc=.o) executable = $(sources:.cc=) : $(executable) % : %.cc $(cc) $(cflags) $< -o $@

android - Error but I do not know exactly why -

i want know technology of battery in android . have finished , done javacode broadcastreceiver . when use java class battery in qt , intent not run java code . decide make run in qt . qandroidjniobject activity = qandroidjniobject::callstaticobjectmethod("org/qtproject/qt5/android/qtnative", "activity", "()landroid/app/activity;"); if (activity.isvalid()) { qandroidjniobject callconstant = qandroidjniobject::getstaticobjectfield<jstring>("android/content/intent", "action_battery_changed"); qandroidjniobject callintent("android/content/intent", "(ljava/lang/string;)v", callconstant.object()); qandroidjniobject param = qandroidjniobject::fromstring("technology" ) ; mysubstring = callintent.callobjectmethod("getstringextra" ,"(ljava/lang/string;)ljava/lang/string;" ,para...

path - R plspm working with categorical and numeric variables -

i working package plspm in r , i'm trying build partial least squares path model it. i'm having weird results when running analysis categorical variables, because don't fit in blocks (but numeric variables work ok). i wanted ask if possible work both numeric , categorical variables, or if have remove 1 type. would great if lend me hand on this. thanks!

Matlab programming code understanding -

i have come across matlab code unable understand. if knows code means me in regard. lambda(:,1) = [randi([1,4], 1,4), randi([1,30],1)*rand]; i know randi return random integer between [min, max]. know, lambda receive? a row values , a column values or only scalar value ? well.. run code , see happens: [randi([1,4], 1,4), randi([1,30],1)*rand] ans = 4.0000 2.0000 4.0000 1.0000 11.9046 so answer be: row vector 5 entries. but let's @ more detailed: randi([1,4], 1,4) create row vector of size 1 x 4 , containing random integers between [min,max] , i.e. between 1 , 4 . second part creates 1 integer in range [1,30] , multiplies random number interval (0,1) . [x,y] concatenate 2 numbers or vectors. leads row vector of size 1 x 5 , saw in beginning. in end assign lambda(:,1) . in matlab first index rows , second columns, select first column of lambda . trying assign 1 x 5 row vector 5 x 1 column vector. luckily matlab smart enough handle that,...

javascript - How to increase size of pie segment on hover in d3 -

Image
i created pie chart using d3. how increase size of pie segment on hover? can see, green segment small want change size red segment. how can this? my code: var w = 400; var h = 400; var r = h/2; var color = d3.scale.category20c(); var data = [{"label":"category a", "value":20}, {"label":"category b", "value":50}, {"label":"category c", "value":30}, {"label":"category a", "value":20}, {"label":"category b", "value":50}, {"label":"category c", "value":30}, {"label":"category a", "value":20}, {"label":"category b", "value":50}, {"label":"category c", "value":5}]; var vis = d3.sele...

php - How to calculate two values from bracket in javascript -

i creating geofencing featured website. need calculate expression. have 2 values related latitude , longitude. for e.g: var value = '(41.878113,-87.629798)' how separate above 2 values in javascript the google maps latlng api provides .lat() , .lng() functions accessing them individually. can use them this: var coords = new google.maps.latlng(42.878113,-87.629798); console.log(coords.lat()); // 42.878113 console.log(coords.lng()); // -87.629798

django - Heroku: string without NULL bytes with several requirements files -

i'm trying deploy django web application in heroku ubuntu following "two scoops of django 1.6" project structure. after doing heroku create , run git push heroku master , output attached @ end. i googled extensively , i'm aware error this typeerror: must encoded string without null bytes, not str and caused because encoding or rare characters in requirements files. problem tried saving less dependencies , changing encodings in files , achieved nothing (i don't know valid encodings heroku, i'm blind @ this). i'm looking way of finding null characters, cat -e @ command line, can't find anything. i'm asking way finding encoding problem or wrong dependency . thank in advanced. edit: tried doing pip install -r <filename>.txt with several of requirements txt files. installations fine. tried doing git push heroku master commented in main requirements.txt (an empty file) , keeps giving same error. maybe heroku not picking r...

mysql - using stored procedure to insert values in a table -

i'm new mysql , i'm trying use stored procedure insert values table.can me please create procedure insertcust(in lname varchar(30), in fname varchar(30),dob1 date) begin insert customer (lname,fname,dob) values(lname,fname,dob1);//it saying have incorrect syntax ere end if run procedure directly in phpmyadmin should write below create procedure `insertcust`(in `lname ` varchar(30), in `fname` varchar(30), in `dob1` date) not deterministic no sql sql security definer insert customer (lname,fname,dob)values(lname,fname,dob1) i hope you.

c# - Regex from a html parsing, how do I grab a specific string? -

i'm trying string after charactername= , before " >. how use regex allow me catch player name? this have far, , it's not working. not working doesn't print anything. on client.downloadstring returns string this: <a href="https://my.examplegame.com/charactername=atro+roter" > so, know gets string, i'm stuck on regex. using (var client = new webclient()) { //example of string looks on console when console.writeline(html) //<a href="https://my.examplegame.com/charactername=atro+roter" > // want "atro+roter" string html = client.downloadstring(worlddest + world + inordername); string playername = "https://my.examplegame.com/charactername=(.+?)\" >"; matchcollection m1 = regex.matches(html, playername); foreach (match m in m1) { console.writeline(m.groups[1].value); ...

Newbe help on getting from polygon shape file to Leaflet polygon -

learning leaflet. had success point data. want create polygons. the process starts access record parcel identification number. using arcmap desktop, records joined parcel shape file county. what best approach leaflet polygons here? point data, need add fields contain lat/lon data? i don't need lot of detail; pointer in right direction. don't mind doing homework. my approach convert shapefile geojson , load geojson leaflet map. i'm aware of arcgis plugins export geojson, alternative approach use command line tool gdal (ogr2ogr) . see links on answer more details, command end being following... ogr2ogr -f geojson -t_srs "epsg:4326" [name][.geojson|.json] [name].shp from there can preview results in geojson.io or github before creating leaflet map .

database - Mysql Innodb deadlock problems on REPLACE INTO -

i want update statistic count in mysql. the sql follow: replace `record_amount`(`source`,`owner`,`day_time`,`count`) values (?,?,?,?) schema : create table `record_amount` ( `id` int(11) not null auto_increment comment 'id', `owner` varchar(50) not null , `source` varchar(50) not null , `day_time` varchar(10) not null, `count` int(11) not null, primary key (`id`), unique key `src_time` (`owner`,`source`,`day_time`) ) engine=innodb default charset=utf8mb4; however, caused deadlock exception in multi-processes running (i.e. map-reduce). i've read materials online , confused locks. know innodb uses row-level lock. can use table-lock solve business problem little extreme. found possible solutions: change replace into transaction select id update , update change replace into insert ... on duplicate key update i have no idea practical , better. can explain or offer links me read , study? thank you! are building summary table...

date - Don't understand tm_struct (C++) calculations - is there an offset of some kind? -

i can't understand why tm struct in c++ behaves way. let me more specific - if current time, i'd this time_t = time(0); tm *nowtm = gmtime(&now); and upon printing out date, expect 2015/06/13 (the current date of post) cout << nowtm->tm_year << "/" << nowtm->tm_mon << "/" << nowtm->tm_mday; but instead, find out prints out 1150/5/13 instead. month value, added 1 set correct month, playing around year proved troublesome. i came across post: algorithm add or subtract days date? , said subtract 1900 year correct year. tried no avail. i tried adding on difference between current year , 1150, 2015 - 1150 = 865 correct year, gave me 9800 instead of 2015 . i experimented adding year, , found that if +1 year, goes in increments of 10 years. if +0.1 year, divide date 0 , add 0.1 (e.g. 1150 + 1 = 115.01). i'm confused - why happen , how correct year in tm struct? from documentation ...

col-lg starting at 1500px instead of 1200px in bootstrap is it chrome displaying wrong? -

bootstrap behaving awkward, because stated grid system .lg grid starts @ 1200px min width. bootstrap lg starting @ screens of 1500px wide. chrome displaying wrong. or bootstrap failing? please see image ferchocarcho , try hitting f12 key , slide view past 1500 , 1200 , see things change. may place start here. added... add replace current version of bootstrap , see if still have issue. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

php - prepend html data in two section of page at once -

so i'll keep simple can bare me, i'm still learning. i have ajax setup submit code create new category database , prepends page , shows without page refreshing. can pull exact same data on different areas of page @ once. here stuck. goal finding way prepend 2 different data sets. 1 goes under new categories does, , pulls in field on create new post section of page. thought might element id or can't find on looking for. so possible take prepend(html) , submit data differently 2 page areas @ once? here code submission. <script type="text/javascript" > $(function() { $(".update_button").click(function() { var boxval = $("#category").val(); var boxval = encodeuricomponent(boxval); var datastring1 = 'category='+ boxval; var dataconfirm = 'newfaqcategory=true'; var datastring = datastring1+'&'+dataconfirm; if(boxval==...

excel - PowerBI hierarchy creation without the cloud -

right can create hierarchies in powerpivot i'm pretty sure can't in powerbi. create data model in powerpivot , use powerbi think. there other work around more desktop based? thanks! mike you cannot create hierarchy in power bi dashboard preview or in power bi. if want feature encourage add proposed feature list here: https://support.powerbi.com/forums/265200-power-bi or vote item if exists. you can create hierarchies in power pivot , deploy model power bi preview hierarchies not visible.

websocket - Setup Codeigniter and Rachet socket -

i need build real time chat system http://socketo.me/ does know how setup app folder , initialise ratchet ? there's project on github has need use ratchet codeigniter: https://github.com/kishor10d/codeigniter-ratchet-websocket

JavaScript scope issue (this) -

i have tried organize code in object oriented way (as explained in mdn ). in case however, this refers window object. because of error uncaught typeerror: cannot read property 'render' of undefined in this.renderer.render(this.stage); why refer window object when doesn't on mdn? var game = game || {}; game.application = function() { this.renderer = pixi.autodetectrenderer(800, 600,{backgroundcolor : 0x1099bb}); document.getelementbyid("game").appendchild(this.renderer.view); this.stage = new pixi.container(); requestanimationframe(this.render); } game.application.prototype.render = function() { this.renderer.render(this.stage); } var app = new game.application(); lets talk this , context, , functions a way think it, this refers object on left of . of method calls it. var someobj = { name:'someobj', sayname: function(){ console.log(this.name); } }; someobj.sayname(); // prints...

ios - Pin Horizontal Spacing Between Two UIImage Views in Xcode 7 -

Image
i beginner using xcode 7 beta, working off tutorial uses xcode 6. in tutorial, instructor selects editor, pin, , horizontal spacing pin space between 2 images stays same when switching landscape. in xcode 7, editor menu doesn't include pin menu. know how pin horizontal spacing between 2 images in new xcode 7? this close need you can choose view (current distance = 0) drop down menu

NginX rewrite/redirect rule http://www to http:// -

i need basic redirect rule if types: www.site.com redirected site.com. need neat , clean in browser. i tried in nginx serverblock: # trying redirects http:// www.site.com http:// site.com if ($host = "www.site.com") { rewrite ^ $scheme://site.com$uri permanent; } ... location / { try_files $uri $uri/ @modx-rewrite /index.php?/$request_uri; location ~ .php$ { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param script_filename $document_root$fastcgi_script_name; include fastcgi_params; } but reason didn't work , "server not found error". , adds http s in address. without rules site opens fine , runs on https , pages open https: // site.com links. thanks. nb: intentionally added several spaces in code snipets in address, otherwise stackoverflow won't let me post it. make simpler: server { listen 80; server_name example.com; location / { .........; } } s...

ruby on rails - find_or_create from array -

i have array of 2 airport structs , need check if each exists already, and, if not, create it. unique key each airport :iata code. when created or found need add both airports @trip airports = [departure_airport, arrival_airport] airports.each |a| airport.where(iata: a.iata).first_or_create |airport| unless airport.present? air = airport.create(a.to_h) @trip.airports << air else @trip.airports << airport end end end what missing? creates airport not pass variables a.to_h it. for handling of scenario airport exists can rearrange code this: airport = airport.where(iata: a.iata).first_or_create(a.to_h) # airport either first airport found, # or new 1 created depending on if 1 existed or not # either way can added @trip @trip.airports << airport

database - Does PostgreSQL quickly search for columns with arrays of strings? -

according can postgresql index array columns? , postgresql can index array columns. can searches on array column efficiently non array types? for example, suppose have row questions table (like so): title: ... content:... tags: [ 'postgresql', 'indexing', 'arrays' ] and want find questions tag 'postgresql' . storing relationship in join table faster searching? and yes, each column have index. gin , gist indexes bigger simple b-tree, , take longer scan. gin faster gist @ cost of expensive updates. if store tags in array column update row require update index on array. under circumstances hot permit skipped, it's not can rely on. you'll have more index updates , more index bloat. on other hand, you're avoiding need scan b-tree ids of desired objects fetch them main table via join. you're saving fair bit of space using array instead of paying 28 byte per row overhead each tag in join table. if insert , update rat...

ios - Is there a way to determine the order of the self.collectionview.visiblecells? -

on collection view, know first item that's being displayed on collection view. figured @ visiblecells , first item on list, it's not case. returning first item visible on collectionview: uicollectionviewcell *cell = [self.collectionview.visiblecells firstobject]; returning first item from items in collectionview uicollectionviewcell *cell = [self.collectionview cellforitematindexpath:[nsindexpath indexpathforitem:0 insection:0]]; you don't want cell, data: nsindexpath *indexpath = [[self.collectionview indexpathsforvisibleitems] firstobject]; id yourdata = self.datasource[indexpath.row]; but visivlecells array not ordered!! well, need order it: nsarray *indexpaths = [self.collectionview indexpathsforvisibleitems]; nssortdescriptor *sort = [nssortdescriptor sortdescriptorwithkey:@"row" ascending:yes]; nsarray *orderedindexpaths = [indexpaths sortedarrayusingdescriptors:@[sort]]; // orderedindexpaths[0] return position of first cell. //...

raspberry pi - Python bus = smbus.SMBus(1) equivalent in C++? -

i'm writing code access i2c sensor in c++ on raspberry pi using wiringpii2c. i need tell pi whether use smbus 0 or 1 (in case, bus 1). i know in python, be: bus = smbus.smbus(1) do know c++ equivalent of be?

css - Show text label next to the input box? -

Image
how can show label 'regularexpressionvalidator' on right input box , align input box? putting outside div makes label left on other side. <style type="text/css" media="all"> <!-- label{ display:inline-block; width:100px; } --> </style> ........... <div style="text-align:center;"> <label>phone:</label> <asp:requiredfieldvalidator id="req_phone" controltovalidate="formwphone">*</asp:requiredfieldvalidator> <asp:textbox id="formwphone" runat="server" /> <asp:regularexpressionvalidator id="regularexpressionvalidator2" runat="server" controltovalidate="formwphone" validationexpression= "">enter valid phone number</asp:regularexpressionvalidator> </div> your issue you've center-aligned of content in wrapper div: <div...

javascript - CasperJS is not clicking my XPath item -

casper.then(function() { console.log("click change password"); casper.click(x('//*[@id="mainmenu"]/div[1]/ul/li[1]/a')); }); i know it's correct xpath. downloaded chrome's xpath plugin , verified correct xpath my console says caspererror: cannot dispatch mousedown event on nonexistent selector: xpath sele ctor: //*[@id="mainmenu"]/div[1]/ul/li[1]/a c:/casperjs/modules/casper.js:1355 in mouseevent c:/casperjs/modules/casper.js:462 in click g:/projects/index.js:137 c:/casperjs/modules/casper.js:1553 in runstep c:/casperjs/modules/casper.js:399 in checkstep any appreciated html first page <input alt="select" class="image selecticon" name="submit-chn:$internal_password.pss" src="docs/pics/select.png" title="select" type="image" /> html second page (i need enter data password field click submit button) <input class="p...

vb.net - Sending IBM Notes Mail 9.0.1 -

lotus notes updated , became ibm notes 9.0.1 causing code i've written send email attachment fail. here's code: public sub sendnotesmail(byval attachment string, byval torecipients list(of string), byval ccrecipients list(of string), byval saveit boolean) 'set objects required automation lotus notes dim maildb object 'the mail database dim username string 'the current users notes name dim maildbname string 'the current users notes mail database name dim maildoc object 'the mail document dim attachme object 'the attachment richtextfile object dim session object 'the notes session dim embedobj object 'the embedded object (attachment) 'start session notes plswaitfrm.show() try session = createobject("notes.notessession") 'get sessions username , calculate mail file name 'you may or may not need maildbname systems 'can pass empty string ...