Posts

Showing posts from February, 2014

c++ - Substitution Cipher, Strings and Functions -

where stuck @ encryptstring function. encryptfile function take .txt file , convert .txt c string equivalent, pass encrpytstring function. when pass in, substitution function work cipher string , encrypt individual characters, spit out new string called encrypted_string. however, cannot function accept argument passed it. guidance? this program is: #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; char substitution_cipher(string cipher_key, char char_to_encrypt); char reverse_substitution_cipher(string cipher_key, char char_to_encrypt); string encryptstring(string &cipher_key, string string_to_be_encrypted); string decryptstring(string &cipher_key, string string_to_be_decrypted); void rotatecipherkey(string &cipher_key); void displayfile(string filename); void encryptfile(string cipher_key, string filename_from, string filename_to); void decryptfile(string cipher_key, string filename_from,

android - How do I check when my ListView has finished redrawing? -

i have listview . updated adapter, , call notifydatasetchanged() . want wait until list finishes drawing , call getlastvisibleposition() on list check last item. calling getlastvisibleposition() right after notifydatasetchanged() doesn't work because list hasnt finished drawing yet. hopefully can help: setup addonlayoutchangelistener on listview call .notifydatasetchanged(); this fire off onlayoutchangelistener once completed remove listener perform code on update ( getlastvisibleposition() ) mlistview.addonlayoutchangelistener(new view.onlayoutchangelistener() { @override public void onlayoutchange(view v, int left, int top, int right, int bottom, int oldleft, int oldtop, int oldright, int oldbottom) { mlistview.removeonlayoutchangelistener(this); log.e(tag, "updated"); } }); madapter.notifydatasetchanged();

c - Is it possible to pass a variable as a structure member? -

if have struct this: /* defined structure 3 integer members */ typedef struct mystruct mystruct; struct myscruct{ int x; int y; int z; }; int main() { mystruct example; // declared "example" type "mystuct" example.x=1; // member 1 have value 1 example.y=2; // member 2 have value 2 example.z=3; // member 3 have value 3 char c; printf("\nchoose witch member want print [ x, y or z]"); scanf("%c", &c); while(getchar() != '\n'); printf("%d", example.c); // part don't know possible. return 0; } it possible pass different member last printf instead of use combination of if example? if so, what's syntax of it? no, cannot use runtime data reference symbols source code. can accomplish apparent aim of particular code bit more effort, though: typedef struct mystruct mystruct; struct myscruct{ int x; int y; int z;

How can I do scripted aggregation in Kibana + Elasticsearch? -

let's have log of events of ad displays , ad clicks stored via logstash in elasticsearch , displayed in kibana 4. calculate simple metric ctr (click-through-rate) of events , : ctr = #clicks/#displays. first of all, know if it's possible in elasticsearch + kibana? don't see possibility in kibana. thinking doing in raw elasticsearch scripted aggregation . don't know how define such in kibana. any ideas on how welcome! comments explaining it's impossible valuable. kibana 4 includes support elasticsearch scripting. can go settings > indices (pick pattern) > scripted fields , add new scripted field computes ctr. take @ " scripted fields " @ elastic blog more info.

android - Custom Spinner's context menu -

how customize spinners' context menu? have done customization selector view ( http://i.stack.imgur.com/ujzyp.png ) have no idea how such content menu. for example selector different color, rounded corners, bigger font etc. now looks like: http://i.stack.imgur.com/jnh31.png fragment's layout : <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:background="@color/white" tools:context="tenkol.design.com.imbrecords.fragmenteditprofile"> ..... <spinner android:id="@+id/spinner_countrie

vim - How to I reduce the indentation in my Mac terminal shell? -

this question has answer here: redefine tab 4 spaces 8 answers how change tab size in vim? 5 answers i have started using vi in terminal write shell scripts. however, noticed indentation large. in preference panel, change indentation? if you're using vi, have set tab size using vi options. when first open file, type : enter set ts=4 and set tab spacing 4 spaces per tab.

C - Trying to build a simple shell in linux and having trouble with strtok, realloc in a loop -

trying build shell implementation in linux assignment , having trouble. following error after running 3/4 times loop * error in `./1': realloc(): invalid next size: 0x000000000132c150 * aborted (core dumped) i have left parts of code out it's long , know there's no issues them. if there's other parts need can add them too. in advance :) note: argc , argv global variables int argc = 0; char **argv = null; int main(void) { while(1) { catch_signal(); printdate(); readcommand(); if(strcmp(argv[0], "cd") == 0) { changedirectory(); } else { executecommand(); } //free(argv); } } void readcommand() { char *buffer = null; char *token = " "; char *p; size_t len = 0; int = 0; getline(&buffer, &len, stdin); p = strtok(buffer, "\n"); p = strtok(buffer, token); while(p)

Windows command to Read text file from specific position -

i trying write first batch file, hence simple question: have file (say "myfile.txt") has names of 10 cities in different rows. want print these names on command prompt 1 one, constraint don't want first 2 letters of city names displayed, how can it? i tried following code not seem work: /f "eol=: tokens=1" %%g in (myfile.txt) ( echo %%g:~2% ) you need temporarily copy line variable, , substring of that. you'll want enabledelayedexpansion , change tokens * (for cities spaces in them). , turn echo off if want cities output. @echo off setlocal enabledelayedexpansion /f "eol=: tokens=*" %%g in (myfile.txt) ( set line=%%g echo !line:~2! )

swift - Automatic Label Resize in UICollectionViewCell Not Working -

Image
i having trouble getting label in uicollectionviewcell dynamically resize based on length of string. have subclassed cell , linked label it. have set number of lines 0 , still not dice. i call sizetofit() method. compiling ios 8.2 here custom cell code: class itemcollectioncell: uicollectionviewcell { @iboutlet weak var titlelabel: uilabel! @iboutlet weak var reviewerlabel: uilabel! @iboutlet weak var statusimageview: uiimageview! override func awakefromnib() { super.awakefromnib() self.selected = false titlelabel.numberoflines = 0 titlelabel.sizetofit() } } make sure didn't uncheck autoresize subviews in interfacebuilder:

mysql - PHP+SQL Shuffle results from one table and save to onother one -

i have write script in php shuffle players ids, pair them , save 1 table. from first table player ids using simple sql query: select id table1 it gives me e.g. result ids: 1, 2, 3, 4, 5 now issue begins. i have shuffle sql result e.g. result 2, 5, 4, 1, 3 then need pair players ids (after shuffle) that: first row - first player second player second row - second player third player third row - third player fourth player fourth row - fourth player fifth player fifth row - fifth player first player in sql table2 if should below: 2-5 5-4 4-1 1-3 3-2 what looking is: 1. way shuffle sql result players id 2. way pair results shuffled result 3. way save table2 what should use shffle(). takes array , shuffles it. can use each array in order. example array1 [1] [2] [3] [4] array2 [1] [2] [3] [4] $array3 = shuffle($array2); array3 [2] [1] [4] [3] then loop through them for($i=0;$i<4;i++){ echo $array1[$i] .' vs '. $array3[$i]; }

ruby - Elegant Rails: multiple routes, same controller action -

what elegant way have multiple routes go same controller action? i have: 'dashboard', to: 'dashboard#index' 'dashboard/pending', to: 'dashboard#index' 'dashboard/live', to: 'dashboard#index' 'dashboard/sold', to: 'dashboard#index' this quite ugly. "more elegant" recommendations? bonus points 1 liner. why not have 1 route , 1 controller action, , differ functionality based on params passed it? config/routes.rb: get 'dashboard', to: 'dashboard#index' app/controller/dashboard_controller.rb def index ... if params[:pending] # pending related stuff end if params[:live] # live related stuff end if params[:sold] # sold related stuff end ... end links in views pending: <%= link_to "pending", dashboard_path(pending: true) %> live: <%= link_to "live", dashboard_path(live: true) %> sold: <%= link

ios - How to implement Cora Data Persistent Management -

i have following structure far: - singleton networkingmanager (login, logout api calls) - subclass nsmanagedobject (with son extension) i don't know how structure part of app? need persistentmanager/global objectmanagedcontext? here classes: networkingmanager (api-call) func getcontacts() { get(apiurl.url_contacts ,parameters: nil, { (operation : nsurlsessiondatatask!, response : anyobject!) -> void in var contacts = [contacts]() contacts <<<<* response //_sharedpersistentmanager.save(contacts!) }, { (operation : nsurlsessiondatatask!, error : nserror!) -> void in println("error contacts") }) } model import foundation import coredata class contacts: nsmanagedobject, deserializable { @nsmanaged var firstname: string @nsmanaged var lastname: string @nsmanaged var id: string required init(data: [string: anyobject]) { let managedcontext = (uiapplication.sha

sqlite - Calling SQL in JavaScript for loop -

i writing set of functions in javascript user can either add new trip or edit existing trip. each trip can have (0-n) guns associated trip. either way, save , edit function both call rangesavegun. when called “save new trip” function, function (below) executes perfectly. new record added db , displayed. however, when called “edit trip” function, sql same as shown in alert(sql) , record never saves db. idea why? in both scenarios, called add new guns trip (not edit existing guns). my question : in below function, why row not being inserted db when exact same function called “edit” function instead of “new” function? either way “sql” text exactly same (as verified in “alert”). missing? both "new" , "edit" functions called via button click, , save or edit trip , call rangesavegun function @ end. i using standard workaround ensure closure. can confirm 3 variables (tripnum, input2temp, , input3temp) showing expected values in scenarios. values numbe

c++ - memory allocation details using strcat -

i'm using following code print strings. #include<bits/stdc++.h> using namespace std; int main(){ char s[100]; while(1){ char f[10000]; cin>>s; strcat(f,s); cout<<f<<endl; } return 0; } in each iteration new allocation of f character array done. input a b c d i expected output this: a b c d but actual output is: a ab abc abcd why happening ? though i'm declaring new array in each iteration why kind of output ?? because: undefined behavior. you not initializing array. you're declaring it. because declare char f[10000]; does not mean it's going initialized empty array, automatically. so, declared array, containing random data. at point, cannot expect predictable behavior. results got 1 plausible outcome. not one. edit: each time around loop, array ends @ same place on stack. first time in, operating system set new page, stack, cleared 0. strcat()ed string it. next ti

c - Created file has nothing in it -

so suppose make program persistent when opened , closed assume have file, program payroll program uses structs. 2 questions here 1. when comes type binary files easier? hear txt files complicated not sure why. 2. here code runs without error when go file nothing written inside. these 2 structs typedef struct{ int day; int month; int year; }date; typedef struct{ char name[100]; int age; float hrsworked; float hrlywage; float regpay; float otpay; float totalpay; date paydate; }payroll; and code void backup(payroll employee[], long int *pcounter) { file *record = fopen_s(&record, "c:\\record.bin", "wb"); if (record != null){ fwrite(employee, sizeof(payroll), 1, record); fclose(record); } employee has stuff in structs know not empty if 1 explain parameters fwrite that'd great! you seem mixing usage of longtime-standard fopen() function usage of new-in-c11 fopen_s()

java - Placing average cost of something into a table -

i've been trying add average cost of petshop 6th slot of table , can't work. no errors appear , i'm totally lost on how so. below method calculates average cost of pets in shop. public string getcalculatepetshopaverage(string shop) { arraylist<pets> petshoppets = new arraylist<pets>(); arraylist<pets> petslist = new arraylist<pets>(); petslist.addall(dogs); petslist.addall(fishes); for(pets pet : petslist) { if(pet != null && pet.getshop().equals(shop)) { petshoppets.add(pet); } } double totalaverage = 0; int = 0; for(pets pet : petshoppets) { i++; totalaverage = totalaverage + pet.getprice(); } system.out.println("there "+i+" pets in here"); t

c - Struct copied into byte array .. wrong alignement? -

i'm trying send manually crafted arp packets on network,more arp request mac address of host. can't final packet right, on wireshark stills shows inconsistency. let me walk through : here struct & typedef use on program , i've defined a ip struct ( => in_addr ) a mac struct ( => ether_addr ) a host struct composed of mac & ip custom struct represent ethernet frame & arp frame. the code: #define eth_addr_size 6 #define ip_addr_size 4 typedef u_char packet; typedef struct in_addr ip; typedef struct ether_addr mac; struct host { ip ip; mac mac; }; typedef struct pkt_eth { mac dest; mac src; u_short type; } pkt_eth; typedef struct pkt_arp { u_short htype;/* hardware type => ethernet , etc */ u_short ptype; /*protocol type => ipv4 or ipv6 */ u_char hard_addr_len; /* 6 bytes ethernet */ u_char proto_addr_len; /*usually 8 bytes ipv4 */ u_short opcode; /* type of arp */ mac hard_addr_send; ip

javascript - Getting data from an object with a generated key -

lets assume have object this. var foo = { "dfsghasdgsad":{ "name":"bob", "age":"27" } }; foo have 1 object key generated. how retrieve "bob" , "27" in situation won't know generated key name be? use object.keys : var key = object.keys(foo)[0]; var name = foo[key].name;

javascript - How to use requirejs to load a directory recursivelly? -

how use requirejs require files on directory , subdirectories of 1 recursivelly? for example, if have directory like: vendor vendor1 vendor11.js vendor2 vendor21.js vendor22.js vendor23.js vendor3 vendor31.js how can load entire directory vendor? using function require(['vendor/*'], mycallbackfunction) ? this function should load equivalent: require( ['vendor/vendor1/vendor11.js'], require( ['vendor/vendor2/vendor21.js'], require( ['vendor/vendor2/vendor22.js'], ...and on ... require( ['vendor/vendor3/vendor31.js'], mycallbackfunction ) ) ) ); requirejs not provide facilities load modules according pattern. pass require has list of actual module names. one option when build application, scan modules according pattern want , create module l

pdfclown - Create two or three columns spreadsheet having multiple rows? -

i understand table , cells supported in pdfclown version 2.0 few months away. so, being stuck version 1.2, how create spreadsheet having 2 columns (& spreadsheet having 3 columns)? anything examples point me in right direction. as noticed, the layout engine supporting tables , lots of other high-level typographic elements scheduled 0.2.0 (its java implementation pre-released evaluation , beta-testing); in meantime can coarsely arrange table way: define table partition (columns) on page , draw corresponding rectangles through primitivecomposer; insert in each column area contents through blockcomposer, keeping track of maximum y occupied contents (this calculated when call blockcomposer.end(), after can retrieve bounding box of contents via blockcomposer.boundbox); when complete columns current table row, use maximum y saved in step 2 draw bottom line closes row , iterate step 2 until run out of rows; if run out of space while inserting contents , keep trac

java - Having a trouble getting List of Strings from array.xml file and parsing them to array of floats android -

Image
getting strings array file , parsing them array of float numbers. once run code null pointer exception array not empty. help... code inside oncreate method: string[] lat = getresources().getstringarray(r.array.latitudes); list<float> latitudes = new arraylist<>(); (string l : lat) { latitudes.add(float.parsefloat(l)); } the code inside array.xml file: <?xml version="1.0" encoding="utf-8"?> <resources> <array name="latitudes"> <item >51.885375</item><!-- cit main campus --> <item >51.884774</item><!-- library --> <item >51.884966</item><!-- nexus student centre --> <item >51.885651</item><!-- admin office --> <item >51.883761</item><!-- canteen --> <item >51.884694</item><!-- stadium --> <item >51.884721</item><!-- gym --> &l

PHP extract string between delimiters allow duplicates -

i'm trying text between 2 delimiters , save array. wrote function, problem code removes duplicates $this->getinnersubstring('{2}{a}{a}{a}{x}','{', '}'); returns array [0] =>2, [1]=>a, [2] =>x , yet want: [0] =>2, [1]=>a, [2]=>a, [3]=>a, [4] =>x, without regex patterns there substr flag lets me keep duplicates? what's best approach here: function getinnersubstring($string,$start, $end){ $s = array(); { $startpos = strpos($string, $start) + strlen($start); $endpos = strpos($string, $end, $startpos); $s[] = substr($string, $startpos, $endpos - $startpos); //remove entire occurance string: $string = str_replace(substr($string, strpos($string, $start), strpos($string, $end) +strlen($end)), '', $string); } while (strpos($string, $start)!== false && strpos($string, $end)!== false); return

How to implement undo in Spring REST API -

i need ideas on how implement simple undo function. spring web-app js frontend , typical spring rest api. undo feature should work similar undo in google keep, e.g. user clicks delete, ui appears delete object, small popup appears in corner undo link approximately 10 sec, after disappears , undo no longer available. my initial thoughts use async message queue. perhaps commandqueue , undocommandqueue. when message enters commandqueue delayed 10sec. after delay service activator recieves message , checks see if there corresponding undo message in undocommandqueue matching id, if not proceeds delete. if possible(and not more complicated) i'd avoid using msg queue. perhaps async delete method has 10 sec sleep built in. how notify async method after it's done sleeping separate undo rest api call made? i know command pattern de-facto approach undo, given want 1 level of undo short amount of time seems overkill. simplest solution delay delete api call altogether using

ember.js - Ember save needs headers. Doesnt seem to pass thru RESTAdapter headers function -

i need pass authorization token via header , works fine find , findquery save doesn't seem invoke header function?! createrecord: function(store, type, record) { var data = {}; var serializer = store.serializerfor(type.typekey); var snapshot = record._createsnapshot(); serializer.serializeintohash(data, type, snapshot, { includeid: true }); return this.ajax(this.buildurl(type.typekey, null, record), "post", { data: data }); }, no call header in above restadapter i quite add header call ... seems odd missing. instead of overwriting store methods extend restadapter app.applicationadapter = ds.restadapter.extend({ headers: { 'api_key': 'secret key', 'another_header': 'some header value' } }); arbitrary headers can set key/value pairs on restadapter's headers property , ember data send them along each ajax request. see http://emberjs.com/guides/models/connecting-to-an-http-server/

How to reverse a string in C? -

i trying reverse string when run code , program crashes . doing wrong? program supposed show @ first , string without being reversed , reversed. p.s: if haven't noticed totally new in c. #include <stdio.h> #include <stdlib.h> #include <string.h> void reversestring(char* str); int main() { char* str = "hello world"; printf(str); reversestring(str); return 0; } void reversestring(char* str) { int i, j; char temp; i=j=temp=0; j=strlen(str)-1; (i=0; i<j; i++, j--) { temp=str[i]; str[i]=str[j]; str[j]=temp; } printf(str); } reversing function fine, problem lies elsewhere. char* str = "hello world"; here, str points string literal, immutable. placed in data segment of program , modification of it's content result in crash. try this: #include <stdio.h> #include <stdlib.h> #include <string.h> void reversestring(char* str); int m

objective c - Display Facebook login data on multiple UIViews -

this might simple solution, i'm not sure how approach of right now. simply put, want have data pulled users facebook account (where prompted sign in upon opening app) shown later in main app under view called profile. want have profile view under settings display fb profile picture, name, email, , logout button fb tutorial shows. great. thanks i suggest looking parse. parse makes easy handle backend services. lot of example code , tutorials found here: https://www.parse.com/tutorials/integrating-facebook-in-ios , here http://www.raywenderlich.com/44640/integrating-facebook-and-parse-tutorial-part-1

r - When plotting heatmap using ggplot2, how can I gave NA data a shape -

i using ggplot2 generate heatmap this http://i61.tinypic.com/1zf321e.png i use code ggplot(meltdata, aes(variable, ids)) + theme(axis.ticks = element_blank())+ scale_y_discrete(expand = c(0, 0)) + scale_x_discrete(labels=null,expand = c(0, 0)) + labs(x = "",y = "") + geom_tile(aes(fill = value),colour = "white") + scale_fill_gradient2(na.value ="black",midpoint = -log(0.05,10), +high = "red", low = "steelblue",guide="colourbar") so far plot this http://i61.tinypic.com/2nitgm1.jpg my question is there anyway can change na data points (which black in plot) shape of cross in first plot. less important question can make color more rainbowish first plot instead blue , red?

swift - update viewcontroller from appdelegate - best practice? -

i playing around ibeacons implementing corelocation methods inside appdelegate.swift (methods implemented in appdelegate ensure app background capabilities) in singleview application comes "viewcontroller.swift", best practice pass data appdelegate viewcontroller update views, uiimages, uilabels or uitableviews ? i have implemented 2 different approaches: 1) delegation, firing viewcontroller delegation methods inside appdelegate.swift: protocol beaconlocationdelegate { func minorbeaconchanged(minorvalue:nsnumber) } var locationdelegate: beaconlocationdelegate locationdelegate?.minorbeaconchanged(nearestbeacon.minor) viewcontroller.swift: in viewdidload method: (uiapplication.sharedapplication().delegate appdelegate).locationdelegate = self (i find rather ugly - better way declare property delegate?) protocol implementation: func minorbeaconchanged(minorvalue: nsnumber) { // fancy stuff here } 2) creating reference viewcontroller inside appdelegat

xml - How can I edit a JSON file using Python? -

i've looked @ several questions , made appropriate changes, python script still isn't working. still new python apologize if i'm making simple mistake... i'm sending xml response webpage display value json file. tested xml portion of script , works fine - when add code edit json file, xml response doesn't load. here's i've got - doing wrong? #!/usr/bin/env python import cgi import cgitb import json open('../../../var/www/data.json', 'r+') f: json_data = json.load(f) json_data[0]['a'] = '7' f.seek(0) f.write(json.dumps(json_data)) f.truncate() open('../../../var/www/data.json') data_file: data = json.load(data_file) cgitb.enable() print "content-type: text/xml" print # blank line, end of headers print "<?xml version='1.0' encoding='utf-8' ?><inputs><data>"+data[0]["a"]+"</data></inputs>&quo

python - Parallelism Speed -

i'm trying handle on python parallelism. code i'm using import time concurrent.futures import processpoolexecutor def listmaker(): in xrange(10000000): pass #without duo core start = time.time() listmaker() end = time.time() nocore = "total time, no core, %.3f" % (end- start) #with duo core start = time.time() pool = processpoolexecutor(max_workers=2) #i have 2 cores results = list(pool.map(listmaker())) end = time.time() core = "total time core, %.3f" % (end- start) print nocore print core i under assumption because i'm using 2 cores speed be close double. when run code of time nocore output faster core output. true if change def listmaker(): in xrange(10000000): pass to def listmaker(): in xrange(10000000): print in fact in runs no core run faster. shed light on issue? i'm setup correct? i'm doing wrong? you're using pool.map() incorrectly. take @ pool

Is it possible to call the code command from c# to javascript function? -

this tricky me , don't know how solve one.. have 2 identical database table [table1,table2] want transfer database item database , delete data previous database avoid duplication.. used listbox1 , listbox2 after transfer data, next step want save changes.. have insert code on c# , i'm using on asp.net problem after transfer item listbox1 listbox2 click save changes button item move listbox2 go listbox1 run c# code -_- delay? think submit first before run c# code.. save code save same items :-/ that's why come idea of calling c# code function since javacript comes first .. if have better idea please share here's tranfer item javascript code <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("#left").bind("click", function () { var options = $(&q

android - Need Web service for Google Fit API? -

i'm designing develop java predicting application analyzing human movements. inputs i'm planing use google fitness api. but i'm unfamiliar fitness api. do need have web service collect , store data google fitness api? can describe pre-requirement of fit api? you can go through tutorial: google fit - rest api

matlab - Unable to apply coefficient of Kaiser window in C++ visual studio 2010 -

i trying pass data through low pass filter having cutoff frequency 1 hz in c++ visual studio 2010. design kaiser window through matlab , 20 coefficient. here matlab code:- fc = 1; % cutoff frequency 1 hz wn = (2/fs)*fc; b = fir1(20,wn,'low',kaiser(21,3)); now i, got this link low pass filter. here code given in link. /* c function implementing simplest lowpass: * * y(n) = x(n) + x(n-1) * */ double simplp (double *x, double *y, int m, double xm1) { int n; y[0] = x[0] + xm1; (n=1; n < m ; n++) { y[n] = x[n] + x[n-1]; } return x[m-1]; } but don't know how apply coefficient of kaiser window in given example in link. so, please tell me how this.

ios - Update badge icon when app is in background/suspended mode -

i want update application badge icon when notification received. works fine when app running (active mode),but having trouble when trying set when app in suspended/background mode. want achieve same without using 'badge' field in apns dictionary. here doing, -(void) incrementonebadge{ nsinteger numberofbadges = [uiapplication sharedapplication].applicationiconbadgenumber; numberofbadges +=1; [[uiapplication sharedapplication] setapplicationiconbadgenumber:numberofbadges]; } -(void) decrementonebadge{ nsinteger numberofbadges = [uiapplication sharedapplication].applicationiconbadgenumber; numberofbadges -=1; [[uiapplication sharedapplication] setapplicationiconbadgenumber:numberofbadges]; } -(void) application:(uiapplication *)application didreceiveremotenotification:(nsdictionary *)userinfo fetchcompletionhandler:(void (^)(uibackgroundfetchresult))completionhandler { uiapplicationstate state = [application applicationstate]; if (state == uiapplicationstate

regex - ASP.NET - define a variable in an ASP page, then use it for a web control attribute's value -

is possible in asp page define variable, use variable web control's attribute value? i'm trying add validation controls asp.net page, , 1 of them regex control. expression want check field contains numbers, spaces, plus sign , round brackets. (for phone numbers) round brackets special character can't escaped slash (as far can tell), did use regex.escape() construct regular expression, stored string variable. want use variable value regex validation control's expression attribute. possible? if not, how can achieve validation want? edit1: so, in tag of asp page have this: <% string phonenumber = "[^0-9 |^" + regex.escape("(") + " |^" + regex.escape(" "); %> then further down have this: <asp:regularexpressionvalidator id="mobilephonevalidator" runat="server" controltovalidate="mobilephone" errormessage="mobile phone number must contain numbers." forecolor="red"

c# - How i can split comma separated string in a group using LINQ -

i have string of comma separated ids 1,2,3,4,5,6,7,8,9...... etc. please suggest how can split them in group of "quantity" means if quantity=3 group (list) ["1,2,3"], ["4,5,6"], ["7,8,9"] etc. range of quantity 1-75. try this: var quantity = 3; yourlist.select((x, i) => new { index = i, value = x }) .groupby(x => x.index / quantity ) .select(x => x.select(v => v.value).tolist()) .tolist();

email - Sending mail not send in java -

i trying send mail in java code. fail send email public static void main(string[] args) { string = "abc@gmail.com"; string = "xtz@gmail.com"; string host = "localhost"; properties properties = system.getproperties(); properties.setproperty("mail.smtp.host", host); session session = session.getdefaultinstance(properties); try { mimemessage message = new mimemessage(session); message.setfrom(new internetaddress(from)); message.addrecipient(message.recipienttype.to, new internetaddress(to)); message.setsubject("this subject"); message.settext("this message body"); transport.send(message); system.out.println("sent message successfully...."); } catch (messagingexception ex) { system.out.println("this exception part >-------->"+ex); } } but found exception javax.mail.messagingexception: not connect s

multithreading - Batch search multiple strings simultaneously -

i have large database of equipment: equipment500 equipment501 .......... equipment998 equipment999 as larger database details equipment: equipment1:details.... equipment2:details.... .................. equipment9998:details.... equipment9999:details.... what need, select details equipment need: for /f "tokens=* delims= " %%a in (%cd%\equipment.db) ( findstr /i /c:"%%a" details.db > output\%%a ) the output be, of course, folder files: in equipment500 equipment500:details.... in equipment501 equipment501:details.... .................. in equipment998 equipment998:details.... in equipment999 equipment999:details.... the problem takes lot of time. i need multithreaded runs more instances of findstr (preferably 500) @ sametime processing instantly. idea appreciated. thank you! @echo off echo building input files (this needs time): del *.db /l %%i in (500,1,999) @echo equipment%%i>>equipment.db /l %%i in (1,1,9999) @echo equipme

Howto change the fontsize of an attributes array (swift, ios) -

i have function follow, creates attributes array. reuse attributes lot of textdrawing. func getfontattributes(ftextsize:cgfloat, color:uicolor, alignment:string) -> [nsobject : anyobject]{ let fieldfont = uifont(name: "helvetica neue", size: ftextsize) var parastyle = nsmutableparagraphstyle() parastyle.linespacing = 6.0 if (alignment=="left"){ parastyle.alignment = nstextalignment.left; }else if(alignment=="right"){ parastyle.alignment = nstextalignment.right; }else{ parastyle.alignment = nstextalignment.center; } var skew = 0.1 let attributes = [ nsforegroundcolorattributename: color, nsparagraphstyleattributename: parastyle, nsobliquenessattributename: skew, nsfontattributename: fieldfont! ] return attributes; } how can change 1 single attribute of attributes (for example fontsize) afterwards ? don't call function getfontattributes again.

lambda - Multiline anonymous function in Matlab? -

this question has answer here: how execute multiple statements in matlab anonymous function? 6 answers is possible create multiline anonymous function in matlab? there no appropriate examples in documentation , no direct denials. in web discussions found derisions of askers if silly wish. nowadays, when languages introducing lambda expressions multiline capability looks strange. no, unfortunately not possible.

javascript - I want to count how many questions are attended by user -

i want count how many question user attended. if user click 1 options 1 question want increment 1 value. ex: if user attend 7/10 count 7. <div id="ques1" class="showquestion"> <div class="ques"> <p>questions ////////////</p> </div> <div> a) <input id="op-1-0" name="answers19" value="2918" type="radio" /> </div> <div> b) <input id="op-1-1" name="answers19" value="2919" type="radio" /> </div> <div> c) <input id="op-1-2" name="answers19" value="2920" type="radio" /> </div> <div> b) <input id="op-1-3" name="answers19" value="2921" type="radio" /> </div> </div> <div id="ques

Recode Python or Ruby or PHP to Java Chatango Chatroom connection -

i want recode pseudo code java: use sockets (low level tool sending raw data on network / server). create new tcp socket. use socket make connection chatango. send authorization string chatango join room. send message. close connection chatango. i tried recode it, it's not working or don't know if doing right. i have code in python, ruby , php, want code in java: -python- import socket s = socket.socket(socket.af_inet, socket.sock_stream) s.connect(('s14.chatango.com', 443)) s.send(b'bauth:deinos\x00') s.send(b"bmsg:hi, i'm connecting via python :3\r\n\x00") s.close() -ruby- require 'socket' s = tcpsocket.open('s14.chatango.com', 443) s.print "bauth:deinos\x00" s.print "bmsg:hi, i'm connecting via ruby :3\r\n\x00" s.close() -php- $socket = socket_create(af_inet, sock_stream, 0); $s = socket_connect($socket, 's14.chatango.com', 443); socket_write($socket, "bauth:deinos

cordova - How to send email with webintent plugin - Monaca IDE -

somebody kindly guide me sending email through webintent plugin monaca send email using "template_a" template var username = 'john'; monaca.cloud.mailer.sendmail("useroida", "template_a", {"name": username}) .done ( function() { /* after sending email success. */ } );

actionscript 3 - Flash Develop with Flex4.6: How to match width and height of SWF to resolution automatically -

my question simple, haven't found answer fits problem. have in main class: [swf(framerate = "60", width = "900", height = "600", backgroundcolor = "0x333333")] i want change width , height match resolution of screen automatically. capabilities.screenresolutionx , capabilities.screenresolutiony return width , height of computer screen, cant do: [swf(framerate = "60", width = capabilities.screenresolutionx.tostring(), height = capabilities.screenresolutiony.tostring(), backgroundcolor = "0x333333")] because returns error: "error: invalid metadata". is possible ask? , if possible, how do that?

java - How to combine two arraylists into one arraylist and pass it to procedure -

i need , assistant in combining 2 arraylists new arraylist passed procedure. once user selected certificates type list, stored in: private list<string> selectedtypeacertificates = new arraylist<string>(); and once user selected certificates type b, stored in: private list<string> selectedtypebcertificates = new arraylist<string>(); now in procedure need pass 2 string variables. 1 staff code , other selectedtypes both types & b. callablestatement callablestatement = connection.preparecall("{call processcertificates(?, ?)}"); callablestatement.setint(1, staff_code); callablestatement.setstring (2, ); //i need pass selectedtypebcertificates & selectedtypeacertificates you can add elements both lists newly created one, , use stringbuilder build string in order pass procedure: list<string> selectedcertificates = new arraylist<string>(); selectedcertificates.addall(selectedtypeacertificates); selectedcerti

regex - php - need a regular expression to find and append website url to img src -

this question has answer here: how parse , process html/xml in php? 27 answers i have got search within html message image tags , append website url image url tag found using regular expression e.g if image src in html message /images/my_image.jpg i need append url , make this: http://mywebsite.com/page/images/my_image.jpg you should use html parsing solution instead of regex , avoid surprises badly formatted code. this: // example source $source = <<<eos <html><body> images have host appended: <img src="foo.png" /> , <img src="images/en/87a%20-zzq.png" /> image left is: <img src="https://www.gravatar.com/avatar/1b1f8ad9a64564a9096056e33a4805bf?s=32&amp;d=identicon&amp;r=pg" /> </body></html> eos; // create dom document , read html $do

javascript - jQuery animate zoom requires me to click body? -

i trying allow zooming of specific element like so: jquery('#center-of-attention').animate({"zoom": "+=5%"}, 5); it works fine, in order zoom, need have clicked on body @ least once seems? i'm not sure why. i've trying running animate it's self still doesn't work. edit: this full code, jquery(document).ready(function() { var currentzoom = 100; jquery(window).bind('mousewheel', function(e){ if(e.originalevent.wheeldelta > 0) { zoom('in'); } else { zoom('out'); } }); function zoom(zoomstate) { if(zoomstate == 'in') { if(currentzoom < 150) { jquery('#center-of-attention').animate({"zoom": "+=5%"}, 5); currentzoom += 5; } } else { if(currentzoom > 100) { jquery('#center-of-attention').animat

Auto Scroll Down with Javascript -

i me make javascript code autoscroll down in 1 particular div in 1 page, , while scrolls down want make 1 procedure. im new in javascript know these things out <div class="uiscrollableareawrap scrollable" data-reactid=".c6.0"> this div of box scrollable. could give me example of how can make javascript code take class , scroll down until end of wrap?? update one. http://screencast.com/t/8wnifzb8ryg check out photo see divs of box want scroll down. relevant link just case: this scroll down bottom of div var objdiv = document.queryselector("._5tee .uiscrollableareawrap"); objdiv.scrolltop = objdiv.scrollheight; demo update: based on screenshot, assuming want scroll ul list bottom. var ullist= document.queryselector("._5tee .uiscrollableareawrap"); ullist.scrolltop = ullist.scrollheight; in case want other div, use pattern .uiscrollableareawrap.scrollable yourdivselector

has many through - Rails User Groups - Set Group Owner In Another Model -

i have user created groups in application. i'm confused how set user creates group owner. want there able multiple owners it's 'has-many-through' relationship. can create/edit/delete group. so question how insert current user_id , group_id group_owners table @ time group created? here have works far: user model class user < activerecord::base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_many :group_owners has_many :user_groups, through: :group_owners end group model class usergroup < activerecord::base has_many :goup_owners has_many :users, through: :groups_owners validates :name, presence: true, length: {minimum: 5} validates :visibility, presence: true, length: {minimum: 5} visibility_types = ["public", "private"] end group owner model class groupowner < activerecord::base belongs_to :user belongs_to :use

php - AngularJS json output format -

i have problem outputting data json file { "movie": { "rowcount": 0, "result": [ { "movieid": "124", "moviename": "hello" }, { "movieid": "123", "moviename": "world" } ] } } i dont know why {{}} statement wont work kind of json file. if json file format following { "disccount": 0, "results":[ { "disccode": "abc123" }, { "disccode": "abcd123" } ] } it works perfect calling {{variablename.disccode}} can me please? thank you from edit, appeared resolving wrong property. should resolve : defer.resolve({ data: response.movie.result, rowcount: response.movie.rowcount }); then, because controller stores data in $scope.movies , following ng-repeat ok : <t

netbeans - How do I change jButton text and save it when Java application is closed? -

how change jbutton text , save when java application closed? i change name of jbutton @ runtime, save these new values future use, possible? thank you you try serialize button object after click , insert code (in main method) initialize button serialized file. modified code illustrate this. hope helps! import javax.swing.*; import java.awt.*; import java.io.*; import java.nio.file.*; import java.awt.event.actionlistener; import java.awt.event.actionevent; class buttonframe extends jframe { public static jbutton bchange ; //button appears in window public static jtextfield btext ; //text field appears in window // constructor buttonframe buttonframe(string title, jbutton button) { super( title ); // invoke jframe constructor setlayout( new flowlayout() ); // set layout manager //initialize textfield btext = new jtextfield(40); btext.settext("place new button name here , c