Posts

Showing posts from July, 2011

git - How can I delete group in gitlab? -

in our organisation moving git, have created group accidentally appreciate if there way delete group. from top right corner, choose "admin area" (the wrench icon) from left, choose "groups" for older versions: click "destroy" on group want remove for more recent versions: click gears-icon on group choose "remove group" bottom of page

geolocation - Map Coordinates C# -

i have set of latitude longitude points. if wanted test if new point within x metres of of existing points possible? best if use way? foreach(coordinate coord in coordinates) { var distance = geocoordinate.getdistance(lat,lon); if(distance <= x) { addtoqualifyinglist(coord); } } and compare new coordinate every point in set , check see within x metres? here method calculate distance between 2 points (lat1, lon1 , lat2, lon2) public enum distanceunit { miles, kilometers, nauticalmiles } public double getdistance( double lat1, double lon1 , double lat2 , double lon2, distanceunit unit) { func<double, double> deg2rad = deg => (deg * math.pi / 180.0); func<double, double> rad2deg = rad => (rad / math.pi * 180.0); double theta = lon1 - lon2; double dist = math.sin(deg2rad(lat1)) * math.sin(deg2rad(lat2)) + math.cos(deg2rad(lat1)) * math.cos(deg2rad(lat2)) * math.cos(deg2rad(theta)); dist = math.acos(d

php - Symfony, error with routing -

i have 1 symfony controller class apidictionarycontroller extends controller { /** * @route("/api/dictionary_list/{userid}/{sessionkey}", name="api/dictionary_list") */ public function dictionarylistaction($userid=null, $sessionkey=null) { // security check $security = $this->get('app.security'); $security->userid = $userid; $security->sessionkey = $sessionkey; $response = new response(); if (!$security->sessionkeyisvalid()) { $response->setstatuscode(400, 'session key has expiried ['.$sessionkey.'] user ['.$userid.']'); return $response; } // content $statement = $this->get('database_connection') ->prepare('select * main.service_dictionary_cursor()'); $statement->execute(); // set content $response->setcharset('utf-8'

sql - mysqli_real_escape_string with mysqli_num_rows in php -

my problem count sql . <input name='d_n[]'> <input name='d_n[]'> php page post value adam's foreach($ds_director $key => $director){ // problem here // $dnumsql = "select * list ds_name = ?"; $stmt = $con -> prepare($dnumsql); $stmt -> bind_param('s',$director); $stmt -> execute(); $dnum = $stmt->num_rows; echo "$dnum"; // result again '0' ///////////// if($dnum == 0){ $director_sql = mysqli_real_escape_string($con,ucwords($director)); $dsql = "insert movie_ds (ds_m_name, ds_name, ds_status) values ('$director_sql', '$m_name', 'yönetmen')"; $dquery = mysqli_query($con,$dsql); if($dquery){ echo "<p style='color:green'>good</p>"; }else{ echo mysqli_error($con); } }else{ echo "<p style='color:red;'>not save</p>"; } } because

php - Laravel - SimpleXMLElement' not found -

i read this link , examples. want convert array xml using laravel (and php7) . here code : public function sitemap() { if (function_exists('simplexml_load_file')) { echo "simplexml functions available.<br />\n"; } else { echo "simplexml functions not available.<br />\n"; } $array = array ( 'bla' => 'blub', 'foo' => 'bar', 'another_array' => array ( 'stack' => 'overflow', ), ); $xml = simplexml_load_string('<root/>'); array_walk_recursive($array, array ($xml, 'addchild')); print $xml->asxml(); } it's first try . returns me : simplexml functions available. blafoostack my second try : public function sitemap() { $test_array = array ( 'bla' => 'blub

salesforce - Is there a way to create custom settings that could be a representation of JSON structure? -

i have generic json string containing bunch on arrays. list can grow in future , can have n-number of repeating elements. for ex: "parent_node": { "node_1": { "a": "1", "b": "2" }, "node_2": { "a": "1", "b": "2" }, "node_3": { "a": "1", "b": "2" } } i can use static resource, maintenance becomes problem. idea provide user friendly customization. using json easier me salesforce users not aware of json , adds dependency them learn build valid json file. i trying use custom settings, doesn't seems helpful. idea accommodate future enhancements without modifying apex code , every new addition of child elements or parent elements must configurable. take in count custom setting equivalent table on relational database, cannot use "document base

ruby on rails - "Hostname does not match the server certificate" error in Mechanize and HTTParty -

occationally, when visit website httparty or mechanize , error: hostname "www.example.com" not match server certificate i can see there workaround if use open method, i'm not sure how leverage above gems. stacktrace mechanize : agent = mechanize.new agent.read_timeout = 180 agent.open_timeout = 180 agent.user_agent_alias = 'mac safari' agent.redirect_ok = :all agent.follow_meta_refresh = :anywhere agent.follow_meta_refresh_self = true agent.get("https://some-domain.com") /home/me/.rbenv/versions/2.2.2/lib/ruby/2.2.0/openssl/ssl.rb:232:in `post_connection_check' /home/me/.rbenv/versions/2.2.2/lib/ruby/2.2.0/net/http.rb:925:in `connect' /home/me/.rbenv/versions/2.2.2/lib/ruby/2.2.0/net/http.rb:863:in `do_start' /home/me/.rbenv/versions/2.2.2/lib/ruby/2.2.0/net/http.rb:858:in `start' /home/me/applications/myapp/shared/bundle/ruby/2.2.0/gems/net-http-persistent-2.9.4/lib/n

python - How to sum values of particular rows in pandas? -

i not familiar python yet. have pandas data frame looks this: 0 1 2 3 55 alice 12896399 8 45 45 bob 16891982 0 0 90 cybill 1800407 1 1 05 alice 12896399 100 200 33 bob 16891982 0.5 0 42 bob 16891982 -1.5 -0.5 46 bob 16891982 1 0 99 cybill 1800407 0.00 0.00 how can sum values of columns 2 , 3 result each person? this: alice 108 245 bob 0 -0.5 cybill 1 1 thank in advance reply. iiuc can groupby , sum on cols of interest: in [13]: df.groupby('0')[['2','3']].sum() out[13]: 2 3 0 alice 108.0 245.0 bob 0.0 -0.5 cybill 1.0 1.0

java - Error:Configuration with name 'default' not found: GRADLE REFRESH FAILED -

i trying develope app sony smart glass in android studio 2.1.2. tried add sony smart glass sample library functions. getting error that error:configuration name 'default' not found. can please me it.thank you my **settings.gradle** include ':app' include ':libraries:mylib' my build.gradle // top-level build file can add configuration options common sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.1.2' // note: not place application dependencies here; belong // in individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: delete) { delete rootproject.builddir } the best starting place create smarteyeglass app 1 of samples. have of necessary dependencies declared you. basic example try starting "helloworld" sample. in end though settings.gra

Should properties of class in Kotlin be private and how to access them? -

aloha! while reading kotling language reference noticed keyword "private" properties of class never used (always default public). said getters , setters generated automatically. created class , made fields private. however, when create object of class, cannot see fields , no setters , getters available, unless write them myself. what's rule here? leave visibility modifier default (public) or make them private , provide mutator methods? thank you. the whole idea of property encapsulates field , accessors in single entity. if need able access , modify property of class outside, should keep property public. if need able read outside not update it, can define public property private accessor. changing default accessor custom 1 not affect clients of class, because under hood compiler generate accessor methods, , clients of class use methods , not access underlying field directly. you should never write explicit getter or mutator methods separate property acces

php - Problems on uploading image files -

this view file form image , other data exists: <?php echo form_open_multipart('login/client_profile'); ?> <div class="form-group"> <label>company name</label> <input type="text" class="form-control" name="company_name" > </div> <div class="form-group"> <label>upload profile picture</label> <input type="file" name="profile_pic" accept="image/*" class="form-control" required> </div> <div class="form-group"> <label>mobile number</label> <input type="number" cla

javascript - Create property editor with multiple fields added dynamically in Umbraco -

i created own plugin, small one, simple 1 contains 1 input , 2 buttons: add & remove. when press add button new input insert below (also add&remove button beside input) when press remove button input removed. i have 2 problems: when add new field, when type text, changes inputs. don't want that. somehow inputs values binding between them. how fix ? want type different text in different inputs. when save , publish content, umbraco save first input, no matter how many inputs created. mistake ? so package.manifest { propertyeditors: [ { alias: "multiplelist", name: "multiple list", editor: { view: "~/app_plugins/multiplelist/multiplelist.html" }, prevalues: { fields: [ ] } } ], javascript: [ "~/app_plugins/multiplelist/multiple

node.js - Pass a block variable to a callback function that has already arguments -

this callback: function evaluateserviceresponse(err, response){ db.answercollection.insert({id: response["serviceanswer"]["id"]}); //problem line } this callback-user: mysoapclient.invokeservicemethod(jsonrecords,this.evaluateserviceresponse); here whole code. inside process create block reference database: process(function(){ ... let db=null; db = mongoclient.connect(connectionurl); //do whatever create jsonrecords mysoapclient.invokeservicemethod(jsonrecords,this.evaluateserviceresponse); ... }); the invokeservicemethod talks service calls callback passing service response. how db reference callback evaluateserviceresponse ? thanks. use closure : function evaluateserviceresponse(db){ return function(err, response){ db.answercollection.insert({id: response["serviceanswer"]["id"]}); //problem line } } and use like: mysoapclient.invokeservicemethod(jsonrecords,this.evaluateserviceresponse(d

Ajax dont activate php code -

i'm trying remove product session cart.i'm sending request ajax event on click , nothing happens.here code.i don't response,like button @ don't work anything. on button press erase id session data , remove product div. function removefrombasket(item) { var xmlhttp = new xmlhttprequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { alert('item removed') } else if(xmlhttp.status == 400) { alert("request error 400"); } else{ alert("something went wrong"); } }; xmlhttp.open("get","cart.php?remove="+item,true); xmlhttp.send(); } cart.php <?php require "cfg.php"; if(isset($_get['remove'])){ $id = $_get['remove']; $items = $_session["cart"]; if

PowerShell Listing different arrays -

i have 2 different arrays , when list them in script, columns of 2nd one, not appear. if list them individually, list correctly. for example, when listing in script, output: name ipaddress numofconnections ---- --------- ---------------- srv1 12.2.2.2 0 srv2 11.1.1.1 0 vserver1 vserver2 if list each array separately, out: array1 name ipaddress numofconnections ---- --------- ---------------- srv1 12.2.2.2 0 srv2 11.1.1.1 0 array2 name curstate ---- -------- vserver1 vserver2 down i suppose powershell

postgresql - Golang-Postgres ..Closing database connection not working for particular query -

i using golang access postgresql. function for { db, err := database.getnewconnection(dbname) err = db.queryrow("select coalesce(count(1),0) table").scan(&count) if count == 0 { var insert = "insert table(last_update_time,next_update_time,schedule_frequency)" + "values($1,$2,$3)" prep_ins, err := db.prepare(insert) if err != nil { return } _, err = prep_ins.exec(cur_time, 1464718530, 86400) if err != nil { return } defer prep_ins.close() defer db.close() } else { var sel_str = "select next_update_time table" prep_update, err := db.prepare(sel_str) if err != nil { return } _, err = prep_update.exec() if err != nil { defer prep_update.close() return } defer prep_update.close() defer db.close() } ti

c# - override width from _Layout.cshtml -

in shared layout have width specified on body-container div. is there way override width in 1 of views? want keep using remaining parts of shared layout. thanks. there 3 solutions: 1) put body-containers in every view. 2) inside view <style> .body-container {width: 1000px!important} </style> 3) use javascript override css.

apache - How to make http request and send data another server in APACHE2.2 -

i developing 1 apache plugin fetch data request header , need send data server. tried apr_socket_sento() , apr_socket_create() none of them working . please tell me how send or data server in apache2.2 plug in . please find ans how send , receive data server. char* post_data_server_sync(request_rec *r,char *host,char *payload,int timout) { char buffer[1024]; char *hostname=host; char *final_msg; char *msg = "post /getrequestdata http/1.1\r\n"\ "host: %s\r\n" \ "accept: */*\r\n"\ "connection: keep-alive\r\n"\ "content-length: %d\r\n"\ "content-type: application/x-www-form-urlencoded\r\n\n%s"; apr_socket_t *new_sock; apr_sockaddr_t *addr; apr_port_t port_no=80; apr_status_t result; apr_interval_time_t tmout=timout; apr_size_t *size=apr_palloc(r->pool,sizeof(apr_size_t)); apr_size_t *size_rcv=apr_palloc(r->pool,sizeof(apr_size_t)); final_msg=apr_ps

excel - Program code is deleting the data which I want to keep -

i have macro consolidate values on sheet, , based on these values, it´s has go on first sheet , delete. macro deleting want keep. the sheet . the macro: sub deleteothers() dim r1 range, c range dim t string sheets("sheet2") set r1 = .range(.cells(2, "h"), .cells(rows.count, "h").end(xlup)) end each c in r1 if c.text = "<<<keep row" sheets("sheet1").select t = c.offset(0, -1) rows(t).clearcontents end if next end sub change to: if c.text <> "<<<keep row"

IOS and Android arcitecture -

Image
first java backend developer , looking clues in right direction question possibly create app third party developers include in app minimum of effort . background: have numbers of potential customer have existing app made difference developers in house others extern developers now want offer customer extended feature of app, , avoid customers need whole rewrite , cost of app , how possible code app included in existing app with minimum of effort customer (its alright have make change every different app) , side note can somehow protect part being copy have include app/sdk any clue on technical papers appreciated you can use as java suggest xamarin c# , java similar or if html , know little bit of native can go phonegap cordova or if angular js can go ionic framework, cool part can drag , drop build ui all frameworks allow developers write code plateform minimum effort.

java - How to get source code from .jar file -

i have project in .jar file. but lost source code of it. how source code .jar file. first of tell if project big , complex, in trouble. generated source code via external tools(no matter whatever tool is) never same real code. code comments, constants, inner classes, etc gets messy. for simpler code , projects can use - java decompiler (jd-gui) http://jd.benow.ca/ dj java decompiler http://www.neshkov.com/dj.html but know not written in source code.

encryption - How to optimize convertions in encrypted SQL Server database table -

i have encrypted database table , want select data calculations. lot of conversions needed , encrypt again update table. how can optimize query. sample query select @total=cast(convert(varchar, decryptbykey([amount1])) numeric(12, 2))+ cast(convert(varchar, decryptbykey([amount2])) numeric(12, 2))*@percent table1 update table1 set [total]= encryptbykey(key_guid('key_67832'), convert(varchar,@total)) select cast(convert(varchar, decryptbykey([amount1])) numeric(12, 2)) amount1, primarykey -- not sure if need this, added in case... temptable table1 select @total=amount1 + amount1 * @percent temptable -- bit unchanged (so far) update table1 set [total]= encryptbykey(key_guid('key_67832'), convert(varchar,@total))

f# - How do I overload operators for WPF containers? -

type addertype() = /// appends container. static member (+) (cont:dockpanel,child:#uielement) = cont.children.add child |> ignore child when make class above , try this. let dock = dockpanel() let win = window(title = "check window style", content = dock) let menu = dock + menu() i error none of types 'dockpanel,menu' support operator '+'. inspired make above phil trelford's binding example goes this: type dependencypropertyvaluepair(dp:dependencyproperty,value:obj) = member this.property = dp member this.value = value static member (+) (target:#uielement,pair:dependencypropertyvaluepair) = target.setvalue(pair.property,pair.value) target the above reason works. have no idea why. possible overload + or other operator elegantly add controls containers? operators defined inside class work if 1 of arguments instance of class, can define operator global operator:

jquery fileupload formData input name -

i using jquery fileupload , want pass input name of file in formdata , have try fails. i try use this.name seems dont have access of in formdata formdata : { action:'upload', field:this.name , extensions : 'gif|jpeg|jpg|png'} i have try use data attributes dont post in case <input id="input-image2" class="file-upload" type="file" name="image2" data-form-data='{ action:'upload', field:image2 , extensions : 'gif|jpeg|jpg|png'}' > does know how add input name (in case image2) formdata? the fileupload init follows and need fill field param of formdata name of input file image2 $('.file-upload').fileupload({ url: '/myfile.php', formdata : { action:'upload', field:this.name , extensions : 'gif|jpeg|jpg|png'}, acceptfiletypes: /(\.|\/)(gif|jpeg|jpg|png)$/i, add : function (e, data) { var type=data.files[0].

reactjs - how to cancel/abort ajax request in axios -

i use axios ajax requests , reactjs + flux render ui. in app there third side timeline (reactjs component). timeline can managed mouse's scroll. app sends ajax request actual data after scroll event. problem processing of request @ server can more slow next scroll event. in case app can have several (2-3 usually) requests deprecated because user scrolls further. problem because every time @ receiving of new data timeline begins redraw. (because it's reactjs + flux) because of this, user sees movement of timeline , forth several times. easiest way solve problem, abort previous ajax request in jquery . example: $(document).ready( var xhr; var fn = function(){ if(xhr && xhr.readystate != 4){ xhr.abort(); } xhr = $.ajax({ url: 'ajax/progress.ftl', success: function(data) { //do } }); }; var interval = setinterval(fn, 500); ); how cancel/ab

cygwin - How do I change the startup directory in babun? -

searches have suggested should add line @ end of .bashrc reads cd /the/directory but doesn't seem work. ideas? you have set in .babunrc

SQL server error - string or binary data would be truncated - even though SELECT statement returns nothing -

i have written query in stoted procedure, like, insert table1 (uniquestr, col1, col2) select uniquestr, col1, col2 table2 ... it gives me error: string or binary data truncated. here statistics. table1.uniquestr varchar(11) table2.uniquestr varchar(20) table2 has records having uniquestr values of 11 characters , 15 characters. the clause of query written in such way select statement never return records having uniquestr length greater 11. the first weird scenario - though select statement returns nothing (when run separately), gives truncation error when run along insert (i.e. insert...select). second weird scenario - gives error in production environment. gave no error in uat environment. in production environment, ran fine 1 day. can tell me issue? note: fixed error using substring function not find out reason why sql server gives error?

html - Without JavaScript, can I show a different text when a longer one won't fit? -

what i'm trying do i have size-limited box supposed contain text: .box { width: 100px; height: 40px; background-color: yellow; } <div class="box"> text goes here. </div> however, if text becomes long fit in box, want replace text different, shorter version, have prepared in advance. so example, if want populate 2 boxes these 2 names: short version long version ------------------------------------------------------------ rudolf e. raspe rudolf erich raspe baron munchausen hieronymus karl friedrich von munchhausen then first box contain "rudolf erich raspe" since it's short enough fit inside, second box contain "baron munchausen" since baron's full name long fit. how can set such box, using html5 , css3? browser compatibility important but, don't need accommodate old versions or internet explorer prior 11. alternatives i can choose of standard options handling too-long text

sql server - Strange CAST behaviour with INT and a single hyphen ( - ) -

i answered question: concate primary keys in sql there encountered strange behaviour: select 5 + '-' + 8 returns 13 select cast('-' int) returns 0, explains above... but: why single hyphen casted 0 implictly? btw: it's same single + or (multi-)blank string... this related cast hyphen (-) decimal points fact, cast decimal not bring these results... i'm writing answer because it's long/complex comment - it's based off comments. note - not have official source, no confirmation logic "what's implemented". (but makes sense think :)) but suppose you're writing conversion function, needs perform. so have string validate - example cast('-50' int); take each character on own: `-` valid part of conversion, move next character. `5` valid part of conversion, move next character. `0` valid part of conversion, move next character. done. so supposed string cast('-' int); : `-` valid p

c# - EF6, Circular dependency givs DbPpdateException -

i'm using entity framwork 6, code first. i have entity team has list of members 1 member team leader . public class team { public virtual list<member> members { get; private set; } public virtual member teamleader { get; private set; } public team() { members = new list<member>(); } public addmember(member member) { members.add(member); } public addteamleader(member teamleader) { teamleader = teamleader; addmember(teamleader); } } i want following throws dbupdateexception. using(var uow = new unitofwork((new datacontext()))) { var team = new team(); team.addmember(new member("adam")); team.addteamleader(new member("david")); uow.teams.add(team); uow.complete(); } this works not nice , day write first version.. using(var uow = new unitofwork((new datacontext()))) { var theteamleader = new member("david"); uow.members

Python - Class methods with input -

how can create method in class user input? what argument should pass when calling method ? class student: def __init__(self): self._name = '' def getname(self): return self._name def setname(self, newname): newname = input ('inserire nome:') self._name = newname studente = student() studente.setname(newname) this should work: class student: def __init__(self): self._name = '' def getname(self): return self._name def setname(self, newname): self._name = newname studente = student() newname = input('inserire nome:') studente.setname(newname) you defining input inside method passing variable outside. variable newname wasn't defined outside. let me know if doesn't work. haven't tested it, seems conspicuous error here.

c# - An object reference is required for the non-static field, method, or property 'TableManager.UpdateSystemFields' -

i got following error while upgrading kentico 9.0. error1: for updatesystemfields there an object reference required non-static field, method, or property 'tablemanager.updatesystemfields' error2: as in kentico api reference 9.0 'updatetablebydefinition' funtion showing removed. bool old = tablemanager.updatesystemfields;// getting error1 tablemanager.updatesystemfields = true;// getting error1 string schema = forminfo.getxmldefinition(); tablemanager tm = new tablemanager(null); tm.updatetablebydefinition(dci.classtablename, schema);// getting error2 tablemanager.updatesystemfields = old;// getting error1 updatesystemfields not static member, can't access through type directly. this not valid: tablemanager.updatesystemfields this valid: tablemanager tm = new tablemanager("connectionstring"); bool old = tm.updatesystemfields;

c++ - how to send float value in url , im sending float value but getting Null values -

i want send values , insert values database, im getting null values. float phvalue = value/10; float dovalue= 12.22; gprsserial.println("at+httppara=\"url\",\"http://itempurl.com/smartpond/addtemprature?watertemperature=""+celsius+""&phvalue=""+phvalue+""&dovalue=""+dovalue+""&currenttime=06-30-2016\""); you can send separately using print() like: int n_decimals = 3; float phvalue = value/10; float dovalue= 12.22; gprsserial.print("at+httppara=\"url\",\"http://itempurl.com/smartpond/addtemprature?watertemperature="); gprsserial.print(celsius, n_decimals); gprsserial.print("&phvalue="); gprsserial.print(phvalue, n_decimals); gprsserial.print("&dovalue="); gprsserial.print(dovalue, n_decimals); gprsserial.println("&currenttime=06-30-2016\""); with n_decimals number of decimal places want pr

php - Joomla, how to display category name in module latest -

i've been trying display category name after contents of 'latest' module in joomla. i've made query in phpmyadmin , works. when try use in php module template page page stops @ point php should start. $db = &jfactory::getdbo(); $id = jrequest::getstring('id'); $db->setquery("select `title` `#__categories` `id` = " .$item->catid); $category = $db->loadresult(); echo $category; when replace $item->catid fixed number, works in phpmyadmin. can tell me go wrong? thanks $item having category title no need through db query. can in tmpl file. can category using $item->category_title <ul class="latestnews<?php echo $moduleclass_sfx; ?>"> <?php foreach ($list $item) : ?> <li itemscope itemtype="http://schema.org/article"> <a href="<?php echo $item->link; ?>" itemprop="url"> <span itemprop="name">

javascript - consuming a web api and getting a referenceerror -

when trying post , data web api, getting exception in browser: angular.js:13708 referenceerror: $ not defined @ new (gbyg.js:23) @ object.invoke (angular.js:4709) @ $controllerinit (angular.js:10234) @ nodelinkfn (angular.js:9147) @ compositelinkfn (angular.js:8510) @ nodelinkfn (angular.js:9210) @ compositelinkfn (angular.js:8510) @ compositelinkfn (angular.js:8513) @ compositelinkfn (angular.js:8513) @ publiclinkfn (angular.js:8390) here client (written in angular): app.controller('getsamplesbystatus', function($scope, $http) { var serializeddata = $.param({statustype:"received"}); $http({ method: 'post', url: ("http://localhost:36059/api/samples/getsamplesbystatus"), data: serializeddata, headers: { 'content-type': 'application/json' }}).then(function(response) { //$scope.dataset = response; consol

kentico - Kentio UI Permissions on an AD Role -

i've been working ui permissions lock down site editor types. have working role created. if update ui permissions on domain role, there risk of these permissions being lost if changes made on domain controller? if domain role deleted yes can lose settings, don't think kentico ad sync tool deletes ad groups, adds , updates (i wrong though). to safe thought, can hook global kentico events , catch when user assigned role see if role ad role , assign non ad role, need catch removal ad role remove non ad role. did myself client.

c# - Must Inject the Specifications on Business Layer? -

i'm trying learn somethings dependency injection , specification pattern. if have scenario: have 3 methods , have different validation rules. rules validated specifications. so... class must receive on constructor these specifications this? public postservice(irepositorio rep, ispecificationsave ss, specificationget g, ispecificationdelete sd) { // things... } but if correct, when add new method, need change de constructor receive more 1 specification? or, using dependency inject, better, in case, create instance of specification on method how's use specification that: public void dosomething(myobject object) { specification<myobject> specification = new specification<myobject>(); // things... } i know question simple 1 of you, i'm trying learn kinds of patterns yet. you can use these specifications in each validator them adding 1 one in class, using specitication pattern, follow: public class class1 : iclass1 { privat

amazon web services - How to create a folder in AWS S3 using AWS Lambda for a user authenticated by Cognito -

i trying invoke lambda function creates aws resources (s3 folder , dynamodb item) authenticated users. lambda function invoked client side after user logged in through aws cognito. making s3 putobject request client-side works fine. however, if make same request invoked lambda function, fails. client --> s3 --> works client --> lambda --> s3 --> not work here lambda function: s3 = boto3.resource('s3') bucket = s3.bucket('bucket_name') id = str(context.identity.cognito_identity_id) bucket.put_object(key='cognito/users/{}/'.format(id)) i following error clienterror: error occurred (accessdenied) when calling putobject operation: access denied both cognito authenticated role , lambda role pointing same role: { "version": "2012-10-17", "statement": [ { "action": ["lambda:invokefunction"], "effect": "allow", &qu

python - gethostbyaddr Error only on 1 server -

running following on production server throws error import socket socket.gethostbyaddr("<ip address>") traceback (most recent call last): file "<stdin>", line 1, in <module> socket.herror: [errno 1] unknown host running same code, same ip on different server works fine. idea cause this?

apache spark - What is right way of Broadcasting a big Dataframe -

i have need broadcast 1 big file (converted dataframe) in spark 1.6.1 lookup. whether below code right way - val file = sc.broadcast(dataframe_df) then accessing using below code in udf. def abc{ file.value.sqlcontext.sql(query) .... } i read sc.broadcast brings data driver first , sends executors not approach this. right? help.

Android Marshmallow sound only Notification? -

in lollipop , below, send sound notification omitting icon, content title , content text when constructing, so: notificationcompat.builder builder = new notificationcompat.builder(getapplicationcontext()); builder.setsound(uri.parse(ringtone)); notificationmanager.notify(9998, builder.build()); in marshmallow, i'm forced include @ least icon, or 'no valid small icon' exception. want use notification system, don't want display notification in notification bar. possible marshmallow, or should change playing notification sound media player, though i, or user, may want display notification? i read somewhere docs said icon required thought didn't throw exception when omitted in lollipop , below. after looking using mediaplayer, decided use rintonemanager play it. using notification sounds, may save myself typing , quick try { ringtonemanager.getringtone(getapplicationcontext(), uri.parse(ringtone)).play(); } catch (exception e) { e.printsta

wpf - Is it possibly to get Frame.Content from Uri? -

i'm trying load xaml file inkscape https://inkscape.org/ frame. frame1.source = new uri("name.xaml", urikind.relativeorabsolute); it works fine. how can frame1.content after ? <?xml version="1.0" encoding="utf-8"?> <!--this file not compatible silverlight--> <viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" stretch="uniform"> <canvas name="svg2" width="744.09448819" height="1052.3622047"> <canvas.rendertransform> <translatetransform x="0" y="0"/> </canvas.rendertransform> <canvas.resources/> <canvas name="layer1"> <rectangle xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" canvas.left="137.14285" canvas.top="169.50507" width="182.85715" height="320" name="rect3336" fill="#ff0000ff

statistics - Is brute force the best option for multiple regression using Python? -

in linear model 𝑦 = 𝑎0 + 𝑎1 × 𝑥i + 𝑎2 × 𝑥j + 𝑎3 × 𝑥k + 𝜖 , values 𝑖,j,k ∈ [1,100] results in model highest r-squared? the data set consists of 100 independent variables , 1 dependent variable. each variable has 50 observations. my guess loop through possible combinations of 3 variables , compare r-squared each combination. way have done python is: import itertools itr import pandas pd import time t sklearn import linear_model lm start = t.time() #linear regression model lr = lm.linearregression() #import data data = pd.read_csv('csv_file') #all possible combinations of 3 variables combs = [comb comb in itr.combinations(range(1, 101), 3)] target = data.iloc[:,0] hi_r2 = 0 comb in combs: variables = data.iloc[:, comb] r2 = lr.fit(variables, target).score(variables, target) if r2 > hi_r2: hi_r2 = r2 indices = comb end = t.time() time = float((end-start)/60) print 'variables: {}\nr2 = {:.2f}\ntime: {:.1f} mins'.form

jsf - h:selectManyCheckbox converter's getAsObject always retrieves "on" as submitted value -

Image
i have bean: @managedbean(name = "bexam") @sessionscoped public class bexam implements serializable { private list<category> categories; private list<category> categoriesselected; public bexam() { categories = categorydb.getall(); // there ok. categories has filled right. categoriesselected = new arraylist<>(); getters & setters... } there converter: @facesconverter("categoryconverter") public class categoryconverter implements converter<category> { @override public category getasobject(facescontext fc, uicomponent uic, string string) { ... } @override public string getasstring(facescontext fc, uicomponent uic, category t) { return string.valueof(t.getid()); } } there selectmanycheckbox: <h:selectmanycheckbox id="categories" value="#{bexam.categoriesselected}" converter="categoryconverter"> <

cordova - Pinterest posting not working inside inappbrowser -

i trying post text , image pinterest using inappbrowser, throwing error "parameter 'image_url' (value http:null) not valid url format." here sample code. var pinteresturl = "http://www.pinterest.com/pin/create/button/"; pinteresturl += "?url=https://www.google.co.in/"; pinteresturl += "&media=http://www.google.co.ma/images/srpr/logo1w.png"; pinteresturl += "&description=text description"; var pinterest = window.open(pinteresturl, '_blank'); it's working fine in web browser , in system browser (iphone/android) if change code "_blank" "_system". treid inspect url using eventlistener "loadstart" , found inappbrowser automatically adding unnecessary parameters "create next button". any suggestion helpful. per our conversation in comments, believe issue no encoding query parameters. encodeuricomponent method used encode special charac

javafx - Minimal size ignored -

Image
i'm creating ui application using scenebuilder. i created simple layout. but after setting minimal size everywhere, still window can reduced this. the .fxml file contains <anchorpane maxheight="-infinity" maxwidth="-infinity" minheight="400.0" minwidth="600.0" prefheight="400.0" prefwidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1"> <children> <menubar layouty="2.0" minheight="25.0" minwidth="600.0" prefheight="25.0" prefwidth="600.0" anchorpane.leftanchor="0.0" anchorpane.rightanchor="0.0" anchorpane.topanchor="0.0"> <menus> <menu mnemonicparsing="false" text="file"> <items> <menuitem mnemonicparsing="false" text="close" />

opencart - How to add variable in language file opencart2 -

i trying add variable in language file using opencart extension, there no change in file. my code: <file path="admin/language/english/catalog/product.php"> <operation> <search><![cdata[// error]]></search> <add position="before"><![cdata[ $_['entry_a_start_date'] = 'start date/time'; ]]> </add> </operation> </file>` please let me know wrong code. thanks in advance when want call single file use name not path . this should work: <file name="admin/language/english/catalog/product.php"> <operation> <search position="before"><![cdata[// error]]></search> <add><![cdata[ $_['entry_a_start_date'] = 'start date/time'; ]]> </add> </operation> </file>

pep - python multiline comment indent -

i have django project, , in places have multiline comments indented follows: field = models.integerfield(default=0, null=true) # 0-initial_email_sent # 1-second_email_sent # 2-third_email_sent this violates pep, but, in opinion, helps readability. of course, put comments this: # 0-initial_email_sent # 1-second_email_sent # 2-third_email_sent field = models.integerfield(default=0, null=true) , rather prefer first one. is there way indent comments such without violating pep? magic numbers evil, best documentation here use named (pseudo) constants: initial_email_sent = 0 second_email_sent = 1 third_email_sent = 2 field = models.integerfield(default=initial_email_sent, null=true) as general rule, less have comment better (clear code needs no or very few comments). for more general answer place comments, specially multiline ones: having comments before comm

swift - How to copy a struct and modify one of its properties at the same time? -

if want represent view controller's state single struct , implement undo mechanism, how change, say, 1 property on struct and, @ same time, copy of the previous state? struct { let a: int let b: int init(a: int = 2, b: int = 3) { self.a = self.b = b } } let state = a() now want copy of state b = 4. how can without constructing new object , having specify value every property? note, while use placeholder values constants a , b not able construct instance of a other values placeholders. write initializer instead. may write custom method change value in struct also: struct { let a: int let b: int init(a: int = 2, b: int = 3) { self.a = self.b = b } func changevalues(a: int? = nil, b: int? = nil) -> { return a(a: ?? self.a, b: b ?? self.b) } } let state = a() let state2 = state.changevalues(b: 4)

c++ - Return specific map entry instead of map::end if no map entry was found -

in switch statement, can specify default return value if none of other cases apply. i'd similar std::map, i'm not sure if possible: can make map return specific value/entry instead of map::end if no key fits search? example (here i'd ultimatively - aware code doesn't work): std::map<std::string, void* (*) (dataobject*)> commands; //mapping functions keys commands["test"] = function(dataobject d){dosomething();} commands[nothing else applies] = function(dataobject d){dosomethingelse();} commands.find("test")(somedataobject); // dosomething(); happens commands.find("blabla")(somedataobject); //dosomethingelse(); happens because no other entry found would possible? (also, way i'm using function pointers in example doesn't work @ - can use cpp11's lambda expressions accomplish want do?) i not want use switch clause, nor want if(m.find(x) != m.end()) clause, nor want more if-else's. you can use own

excel - Sum value If date are between multiple range of dates (matrix) -

Image
excel print hello, i need sum values on column d if date on cell a2 inside range e2:f5 (matrix?). for example on picture (excel print) result 6 (1+5). any help? sumifs() formula use: =sumifs(d:d,e:e,"<=" & a2,f:f,">=" &a2)

java - Vector to DefaulTableModel -

i have serilize file cntains datavector of jtable. when wanna deserialize throws error telling me vector cann't cast default tablemodel. here serialize method: fileout.writeobject(model2.getdatavector()); //i save data vector. here deserialization process: objectinputstream in = new objectinputstream(new fileinputstream("c:/users/harry/desktop/clients.txt")); defaulttablemodel dtm = (defaulttablemodel)in.readobject(); jtable table = new jtable(dtm); error: exception in thread "awt-eventqueue-0" java.lang.classcastexception: java.util.vector cannot cast javax.swing.table.defaulttablemodel how cast vector default table model can deserialize data vector jtable? broadly speaking have 3 choices: serialize entire defaulttablemodel . ok short-lived applications should not rely on consistent mechanism storing data long term. serialize data vector along column count , column names. deserialize data on reader side , construct n

c - Got stuck in the final part of a program for encryption in Vigenere -

i attending online course cs50 on edx , have assignment in have create program user enters keyword ( used encryption ) , string needs encrypted in vigenere cipher. vigenere works encrypting text following keyword: example if string "hello" , keyword "abc" : a equal 0 in alphabetical characters, b 1, , c 2; letter h in string encrypted without switching characters ( s letter a in keyword = 0), letter e switched 1 position , encrypted f , , on. if keyword has length less of string (like in case) encryption has use again first character of keyword , problem. in fact, think implemented whole program not sure how take consideration if keyword has less characters string entered. program returning first char of string encrypted , first char not encrypted , stops. i not ask complete solution, want understand how can solve program problem. here program: #include <stdio.h> #include <cs50.h> #include <ctype.h> #include <stdlib.h> #in

uiimageview - How to find the pixel location in original image in ios -

i have image size 480x360 , displaying in uiimageview frame (0, 0, 320, 568) aspectfill . when touch image view, location says (150,120) . how can map location in original image (480x360) format? thanks you calculate proportions , apply them touch location point. cgfloat _x = imageview.image.size.width / imageview.frame.size.width; cgfloat _y = imageview.image.size.height / imageview.frame.size.height; //assuming p - cgpoint received touch event cgpoint locationinimageview = cgpointmake(p.x * _x, p.y * _y);

android - More efficient to directly assign or pull from XML? -

i trying reduce gc overhead size. i noticed have several of keys bundle directly assigned string @ start of code , uses assignment later. example: string newtimekey = "newtimekey"; is better if store string in resource xml , call @ start of program this? string newtimekey = getstring(r.string.newtimekey);

css3 - I can't stop the css/jquery animation on focus -

i want stop animation of span on focus of input. when doing hover, there no problem, good. want stop span when focus input. problems here. code here . actualy want css not scss. here and html : <link href='https://fonts.googleapis.com/css?family=open+sans:300' rel='stylesheet' type='text/css'> <section id="text"> <p><span> İsİm</span><input name="name" type="text" placeholder="İsminiz" /></p> <p><span> konu </span><input name="subject" type="text" placeholder="konu"/></p> <p><span> maİl </span><input name="mail" type="email" placeholder="mailiniz"/></p> <p><span> mesaj </span><textarea name="message" type="text" placeholder="mesajınız"></textarea> </section> css: .a