Posts

Showing posts from June, 2010

html - Why is the option text sent when form submitted instead of "value" if value is not set? -

i seeing occur in older version of ie. don't see behavior in chrome or firefox. have form code: <div class="small-12 medium-3 column hide" id="special-set-div"> <label>special set? <select id="special-set" name="special_set"> <option value>select</option> <option value="yes">yes</option> <option value="no">no</option> </select> </label> </div> when form submitted, server reading "select" parameter. need manually assign value empty string? there documentation of behaviour? can't seem find mention of this. thanks in advance help. this w3c specification states value attribute: value = string provides value element. if there isn't, value of option element textcontent of element. so yes, expected behaviour.

java - Add external data to Orika MappingContext while mapping -

i want add external properties (something not in object i'm mapping) mappingcontext. here want accomplish: mapperfactory mapperfactory = new defaultmapperfactory.builder().build(); mapperfactory.classmap(obja.class, objb.class).customize(new custommapper<obja, objb>() { @override public void mapatob(obja obja, objb objb, mappingcontext context) { objb.setname((string) context.getproperty("name")); } }).bydefault().register(); mapperfacade mapper = mapperfactory.getmapperfacade(); obja obja = new obja(); objb objb = new objb(); mappingcontext context = new mappingcontext(); //probleme here: mappingcontext abstract class context.setproperty("name", "some information not in obja nor in objb"); mapper.map(obja, objb, context); how can that? can dynamically add data context? or other way pass additional data mapper? the solution simple: mappingcontext contex

ruby on rails - Trying to display fields from hash but getting undefined method `[]' for nil:NilClass -

i receiving error " undefined method `[]' nil:nilclass " when trying display field json parsed hash. how coll_title data display? the data alinks : [{ "role"=>"source", "relator"=>"dnr", "terms"=>[], "_resolved"=>{ "lock_version"=>0, "publish"=>true, "display_name"=>{ "coll_num"=>"024", "coll_title"=>"collection title" } } }] the code: def display_agents(hash, opts = {}) html = "<div><small>" html << "<ul style='list-style-type:none'>" alinks = json.parse( hash["json"] )["linked_agents"] alinks.each |_resolved| html << "<li>#{_resolved["display_name"]["coll_title"]}</li>" end html << "</ul>" html <&l

html - Creating a stroked frame effect with css -

Image
i have design effect i dont care font styles or details, focused right on creating frame , if possible button well. know how kind of effect in css? here basic html/css code, wont of help. , can modify if suits better. btw using bootstrap 3. /******** html *********/ <div class="col-md-12 bg-img"> <div>italy has never been close</div> </div> /******** css *********/ .bg-img { display: table; width: 100%; height: 100px; text-align: center; background: #999 url("http://p1.pichost.me/i/15/1380265.jpg") no-repeat fixed center; } .bg-img div { display: table-cell; vertical-align: middle; width:10px; font-weight:700; } i using generic image, shouldn't make difference. here fiddle. https://jsfiddle.net/3al4xnr8/ you can :after , :before pseudo-elements. div { display: table; margin: 0 auto; width: 30%; padding: 20px;

Tracking Youtube Video Google Tag Manager Youtube API -

at end of video added ?rel=0 allows video not show related videos @ end of timeline. want track video embedjsapi=1 @ end of iframe url this. https://www.youtube.com/embed/egnk8zmkwls?rel=0embedjsapi=1 do need put (&) sybmol between 2 rel=0 & embedjsapi=1 or link above ok? yes, speaking, need separate query parameters ampersand (&): https://www.youtube.com/embed/egnk8zmkwls?rel=0&embedjsapi=1

amazon web services - Cannot delete item from DynamoDB table (java) -

i've been attempting delete item table in dynamodb through java code, every attempt i've made results in same error: com.amazonaws.amazonserviceexception: provided key element not match schema (service: amazondynamodbv2; status code: 400; error code: validationexception; my current attempt simple , looks this: final dynamodb dynamodb = new dynamodb(new amazondynamodbclient(credentials)); table table =dynamodb.gettable(tablename); deleteitemspec itemspec = new deleteitemspec().withprimarykey("cognitoid", cognitoid); table.deleteitem(itemspec); tablename table name, credentials have been verified correct, , cognitoid actual id of item i'm trying delete. table in question has cognitoid primary key , don't understand why deletion isn't matching schema. table has sort key, or range key (i'm not sure because documentation quite vague). i've been referring documentation here: http://docs.aws.amazon.com/amazondynamodb/la

r - Error when building regression model using lm ( Error in `contrasts<-`(`*tmp*`... contrasts can be applied only to factors with 2 or more levels) -

i error depending on variables include , sequence in specify them in formula: error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isof[nn]]) : contrasts can applied factors 2 or more levels i've done little research on , looks caused variable in question not being factor variable. in case (is_women_owned), factor variable 2 levels ("yes", "no"). > levels(customer_accounts$is_women_owned) [1] "no" "yes" no error: f1 <- lm(combined_sales ~ is_women_owned, data=customer_accounts) no error: f2 <- lm(combined_sales ~ total_assets + market_value + total_empl + empl_growth + sic + city + revenue_growth + revenue + net_income + income_growth, data=customer_accounts) regressing on above formula plus factor variable "is_women_owned": f3 <- lm(combined_sales ~ total_assets + market_value + total_empl + empl_growth + sic + city + revenue_growth + revenue + net_income + income_growth + is_women_owned,

jsf facelets cannot find property in tomcat 7 but works in glassfish 3.1 -

i trying figure out jar need download tomcat 7. making call , passing argument method such "availableemployees(departmentname)" in faces web page. not work in tomcat 7 works in glassfish 3.1. have added javax.faces.2.1.20.jar "mojarra" web app jsf dependency. have javax.servlet.jsp.jstl.1.2.1 in tomcat library folder. did run such problem ? need add more above jars jsf support ? thanks. not using maven since else' project. i using netbeans , linked eclipse project. added own primefaces library. when looked @ build output netbeans, have noticed there 2 copies of primefaces library. 1 3.4.2 , 3.3.1. removed 1 of them , worked.

sql - Debugging Coldfusion Query with cfloop inside -

i'm trying debug cf query , cannot because of complex structure.the code following: <cfquery name="qquery" datasource="#variables.datasource#"> <cfloop index="i" from="1" to="#arraylen(asql)#" step="1"> <cfif issimplevalue(asql[i])> <cfset temp = asql[i]>#trim(dmpreservesinglequotes(temp))# <cfelseif isstruct(asql[i])> <cfset asql[i] = queryparam(argumentcollection=asql[i])> <cfswitch expression="#asql[i].cfsqltype#"> <cfcase value="cf_sql_bit"> #getbooleansqlvalue(asql[i].value)# </cfcase> <cfcase value="cf_sql_date,cf_sql_datetime"> #createodbcdatetime(asql[i].value)# </cfcase> <cfdefaultcase> <!--- <cfif listfindnoc

matplotlib - Delaunay triangularization of Polyhedron (Python) -

Image
i'm trying delaunay triangulation of polyhedron in python can calculate centroid. see there delaunay function in scipy.spatial , works in n-dimensions. trouble documentation shows 2d use , gives me no indication of higher dimensions. being able decompose object array solve issue me, don't know how that. the problem i'm running not know how verify working correctly outputting object. can find nothing on google how graph polyhedron or how use object scipy spitting back. if do import numpy np scipy.spatial import delaunay points = np.array([[0,0,0],[1,0,0],[1,1,0],[1,0,1],[1,1,1],[0,1,0],[0,1,1],[0,0,1]]) delaunay(points) i able coordinates of these tetrahedrons can calculate centroids of polyhedrons. nice if able graph tesselated polyhedron too. saw in matlab can fuction called trimesn, , found 1 matplotlib seems different , documentation not great. from matplotlib.collections import trimesh trimesh.__doc__ u'\n class efficient drawing of triangul

html - IE not maintaining aspect ratio when using max-width with svg image -

i'm using svg image , setting max-width property, ie uses original height , doesn't try maintain aspect ratio, when setting height: auto explicitly. fiddle here html <img src="http://dauntless.herokuapp.com/assets/images/who-we-are-nav-f35af64a3b.svg"> css img { max-width: 50px; height: auto; } update1 actually problem particularly present svgs, other svg files working ie. have no idea wrong them, they're working fine other browsers. update2 the answer provided solved problem new problem popped :( now when using max-width image scales correctly, when wrapping in div wrapper takes image's original full height. fiddle you've explicitly set width , height in opening tag of svg. if remove them, works in ie (tested in ie11): img, svg { max-width: 50px; height: auto; } has height set: <img src="http://dauntless.herokuapp.com/assets/images/who-we-are-nav-f35af64a3b.svg" alt="">

Attempting to deploy a python pyramid application with uWSGI -

i'm attempting deploy pyramid application using uwsgi. the application works fine when served included pyramid development server. also, have set before, , swear worked @ 1 time. however, putting in magic phrases right resulting in "this webpage not available" i'm trying keep of configuration parameters similar possible have don't have worry firewall issues. uwsgi section in development.ini looks (from: setup uwsgi webserver pyramid (no nginx) ): [uwsgi] socket = localhost:8080 virtualenv = /var/www/finance/finance-env die-on-term = 1 master = 1 #logto = /var/log/wsgi/uwsgi.log enable-threads = true offload-threads = n py-autoreload = 1 wsgi-file = /var/www/finance/wsgi.py wsgy.py looks this: from pyramid.paster import get_app, setup_logging ini_path = '/var/www/finance/corefinance/development.ini' setup_logging(ini_path) application = get_app(ini_path, 'main') here's output right now. seems listening fine on port 8080.

excel - C4D python openpyxl cannot save .xlsm, but raises TypeError in zipfile.py -

this first post, , i've been searching diligently answer, please bear me! i want able modify existing .xslm file fill motion data i've extracted within cinema-4d via python. i did try keep_vba=true suggested here , still got error described below. macro-enable workbook excel 2013, functioning macro wrote. working code is: import os openpyxl import load_workbook homedir = os.path.expanduser('~') openname = 'timing_chart.xlsm' openpath = os.path.dirname(__file__) + "\\" + openname savename = raw_input('please enter save name: ') savepath = homedir+'\\desktop\\'+savename+'.xlsm' wb = load_workbook(openpath, keep_vba = true) ws = wb.active ws['b10'].value = 'loader' #just test ws['d10'].value = 25 wb.save(savepath) when run code via enthought canopy environment (python 2.7.6 64-bit) works expected--fantastic. when try run same code in same python version used in cinema-4d installation (py

python - Filter object has no attribute pop -

colorramps = re.split("#ramp\[([0-9a-fa-f]{6})\](.+?)#rampend\[([0-9a-fa-f]{6})\]", message) colorramps.reverse() if len(colorramps) > 1: starttext = colorramps.pop() starttext = starttext.replace("$message", getsavestring(text)) starttext = starttext.replace("$playername", getsavestring(username), 1) complete = [starttext] while len(colorramps): startcolor = getcolor(colorramps.pop()) colors = filter(none, re.split("#over\[([0-9a-fa-f]{6})\]", colorramps.pop())) middletxt = colors.pop() endcolor = getcolor(colorramps.pop()) middletxt = middletxt.replace("$message", getsavestring(text)) middletxt = middletxt.replace("$playername", getsavestring(username), 1) middletxt = middletxt.decode("utf") if len(colors) > 0: colors = map(getcolor, colors) colors.append(endcolor) middletxt = rangeoverc

c++ - Order dates from a vector -

i read multiple dates file , put every date in vector of struct this: struct value { string code; string date; string name; }; (the format of date “ yyyy-mm-dd hh:mm:ss ") now want order dates of vector. any suggestion? you can use std::sort() algorithm on vector : vector<value> v; ... std::sort (v.begin(), v.end(), [](value&a, value&b)->bool { return a.date<b.date; }); fortunately , date format using alphabetical order corresponds chronological order. if not case, you'd have add date conversion. live demo

c - STM32 USB OTG HOST Library hangs trying to create file with FatFs -

i trying create file fatfs on usb flash, f_open call trying read boot sector first time file system mount hangs on function. dresult disk_read ( byte drv, /* physical drive number (0) */ byte *buff, /* pointer data buffer store read data */ dword sector, /* start sector number (lba) */ byte count /* sector count (1..255) */ ) { byte status = usbh_msc_ok; if (drv || !count) return res_parerr; if (stat & sta_noinit) return res_notrdy; if(hcd_isdeviceconnected(&usb_otg_core)) { { status = usbh_msc_read10(&usb_otg_core, buff,sector,512 * count); usbh_msc_handlebotxfer(&usb_otg_core ,&usb_host); if(!hcd_isdeviceconnected(&usb_otg_core)) { return res_error; } } while(status == usbh_msc_busy ); // loop wich create hanging state } if(status == usbh_m

Drawing matrix plot in Python? -

Image
i have matrix stored list of lists, , 2 more lists representing labels x , y axes. a = [[1, 3, 4, 5, 6, 7], [3, 3, 0, 7, 9, 2], [1, 3, 4, 5, 6, 6]] x = ["a", "b", "c", "e", "f", "g"] y = ["r", "s", "t"] i want draw matrix table (like picture below). is possible in python? i think can use plt.text purposes. code below uses obtain result want. import matplotlib.pyplot plt import numpy np matplotlib import rcparams rcparams['font.family'] = 'serif' rcparams['font.size'] = 16 = [[1, 3, 4, 5, 6, 7], [3, 3, 0, 7, 9, 2], [1, 3, 4, 5, 6, 6]] x = ["a", "b", "c", "e", "f", "g"] y = ["r", "s", "t"] m = len(y) n = len(x) plt.figure(figsize=(n + 1, m + 1)) krow, row in enumerate(a): plt.text(5, 10*krow + 15, y[krow], horizontalal

c++ - reserve() Implementation for std::vector in STL -

consider implementation of std::vector::reserve() book "the c++ programming language, 4th ed., bjarne stroustrup: template<class t, class a> void vector<t,a>::reserve(size_type newalloc) { if (newalloc<=capacity()) return; vector_base<t,a> b {vb.alloc,newalloc}; // new storage // (see ps of question details on vb data member) t* src = elem; // ptr start of old storage t* dest = b.elem; // ptr start of new storage t* end = elem+size(); // past-the-end ptr old storage (; src!=end; ++src, ++dest) { new(static_cast<void*>(dest)) t{move(*src)}; // move construct src–>~t(); // destroy } swap(vb,b); // install new base (see ps if needed) } // implicitly release old space(when

c++ - Creating number pools -

i created simple container class, holds number pool of unique numbers. returns number pool before container destroyed. //pooled.hpp #pragma once #include <queue> class pooled { public: pooled(); ~pooled(); //edit: disable copy , copy assignment here const int number; private: int getnumber(); static std::queue<int> pool; static int currentsize; }; and //pooled.cpp #include "pooled.hpp" std::queue<int> pooled::pool; int pooled::currentsize = 1; pooled::pooled() : number(getnumber()) {} pooled::~pooled() { pool.push(number); } int pooled::getnumber() { if (pool.empty()) { pool.push(currentsize); currentsize++; } int newnumber = pool.front(); pool.pop(); return newnumber; } but let's wanted create multiple pools of numbers. define arbitrary number of std::queue<int> s somewhere, have every pooled object hold reference specific one. doubles size of every pooled obje

mysql - SQL Many to Many - Very simple -

i have 3 tables student: id int (pk), name varchar(255) discipline: id int (pk), name varchar(255) student_discipline: student_id int, discipline_id int i know has many-to-many relationship, , more 1 joins necessary, i'm new sql, question is: how can make query returns students 'john' starting name have 'math' discipline, student id , student name, example ? any appretiated ! select * student tp join student_discipline tpt on tpt.sid = tp.sid join discipline t on tpt.did = t.did tp.name 'john%' , t.name = 'math'

python - Copy duplicate file and change name -

so i'm looking make backup of file every 2 times, maximum of 30 backups @ once. once there 30 backups, function deletes backups , starts on again (again, creating 30 backups, once every 2 seconds). because i'm creating 30 copies of same file, need change name python dosen't overwrite file (main0.db, main1.db, main2.db, main3.db...etc). in order this, i've created variable gets appended filename (i) , increased 1 each time function runs. the problem because have to(?) decalre variable inside function, every time runs variable gets reset, , file created main0.db. any ideas? hey, i'm looking make backup of file every 2 times, maximum of 30 backups @ once. once there 30 backups, function deletes backups , starts on again (again, creating 30 backups, once every 2 seconds). because i'm creating 30 copies of same file, need change name python dosen't overwrite file (main0.db, main1.db, main2.db, main3.db...etc). in order this, i've created variabl

design - C++ allocators_trait::construct: motivation, trade-offs in ignoring -

i'm wrestling pain being caused std::allocator_traits::construct . in order container "conforming" user of allocator concept, needs use construct rather placement new construct objects. sticky me. have class (class a) designed allocator aware, , @ point needs create instance of other class (class b) in allocated memory. problem class b implements construction of new object. if use placement new, wouldn't issue: handle allocation, pass b memory address, , b construct that. since construction needs performed via construct, need inject allocator type b, templating it, creates huge mess. it's bad enough considering using placement new, , static asserting instance of allocator not have construct method (note static construct function calls instance method if exists, otherwise calls placement new). have never felt tiniest urge write construct method allocator. cost of making part of allocator concept seems high me; construction has gotten entangled allocation, al

C# Visual Studio 2015 - Automatic jump into brackets -

this first question on stackoverflow, here goes: i've got annoying problem/feature in visual studio 2015. problem every time create if statement, for, while, etc. autocomplete (tab-tab). when go line of end bracket , try create new line (simple press of enter) right after it, text cursor jump brackets, instead of making new line. i've looked far wide trying disable "feature" incredibly annoying. have not been able find information on anywhere, asking question. thank you! how produce problem: anywhere in c# project, make new if statement (while, for, etc. can used too). navigate after end bracket. press enter make new line. the marker have jumped inside of statement, instead of making new line. the 'problem' when using tab key activating snippets feature. after typing tab in 'snippet editing' mode, each tab (and shift + tab ) used navigate placeholders defined snippet. in snippet mode, enter key takes wherever person de

ruby on rails - Update ElasticSearch mapping in production (Tire) -

i have clear understanding on how deal following scenario: i'm adding or removing attribute activerecord model, want update mapping in elasticsearch, in production. from understood, should... 1- create new index , import mysql is right command? rake environment tire:import class='bow' index='new-bows' create right mapping, should have updated mapping in model, right? 2- delete old mapping , create alias named bows new-bows i that, correct? old_index_name = bow.tire.index.name bow.tire.index.delete alias = tire::alias.new alias.name(old_index_name) alias.index('new-bows') alias.save 3- restart app am missing something, or there simpler way achieve want using tire? at point should delete old index? before creating alias same name, or can after? you should keep old index around until you're sure new index 100% want. can flip alias if not case. there's integration test in tire test suite "flipping aliases&q

css - Scaling sprites below 100% alters their position -

i've followed tutorial on scaling sprites http://tobyj.net/responsive-sprites/ - when set images 100% fine when use value of 35% in media queries sprite images displaced. any ideas why? site here http://edharrisondesign.com/pocketpictograms/ here's css: #icon-container { position: absolute; top: 50%; margin-top: -225px; left: 50%; width: 400px; margin-left: -200px; } .icon img{ padding-bottom: 150%; } /*set max-width width of individual sprites:*/ .stretchy { display:block; position:relative; overflow:hidden; width: 100%; max-width:400px; margin: 0 auto; } .stretchy .spacer { width: 100%; height: auto; } .stretchy .sprite { position:absolute; top:0; left:0; max-width:none; max-height:100%; } .stretchy .sprite.s2 {left:-100%;} .stretchy .sprite.s3 {left:-200%;} .stretchy .sprite.s4 {left:-300%;} .stretchy .sprite.s5 {left:-400%;} .stretchy .sprite.s6 {left:-500%;} .stretchy .sprite.s7

javascript - How to get HTML5 Range Slider's value in PHP? -

i have html5 range slider. can send value php? send email value. html: <div class="unit"> <div class="slider-group"> max value: <label id="1-h"></label> </div> <div id="slider-1-h"></div> </div> javascript: $(function() { $( '#slider-1-h' ).slider({ range: "min", min: 0, max: 300, value: 99, slide: function( event, ui ) { $( '#1-h' ).html( ui.value ); } }); $( '#1-h' ).html( $( '#slider-1-h' ).slider( 'value' ) ); }); ok fine. , now, can send this? have no input box. can`t use $_post[""] or? :/ in jquery add: change: function(event, ui) { $('#slidervalue').attr('value', ui.value); } in form add: <input type="hidden" name="slidervalue" id="slidervalue" value="

c++ - What should I replace num with? -

i'm trying write program determine whether both sum , product of 2 integers either or odd. everything seems fine, except when run program, comes out: "the product of 2 , 3 5 , even." even? why when should odd? understanding, reading num since put (num%2==0) , that's why saying even. how can make read outcome of 2 numbers (sum/product)? #include<iostream> using namespace std; int main () { int num; cout << "please enter integer: "; cin >> num; int num2; cout << "please enter integer: "; cin >> num2; if ( num % 2 == 0 ) { cout << "the product of " << num << " , " << num2 << " " << num*num2 << " , even." << endl; cout << "the sum of " << num << " , " << num2 << " " << n

Why isn't it possible to use prepared statements (based on ALTER TABLE) to set default values of MySQL fields from PHP? -

i'm writing php code change default value of varchar field in mysql database. in order code secure, use prepared statement, reason seemingly impossible php/mysql accept in particular situation, why that? (i'm using php 5.5.11) here code using prepared statements, not work (the mysqli_stmt_execute() call returns null, , default value of field remains unaltered): $new_field_default_value = 'test'; $field_modification_sql_command = "alter table mytable alter column mycolumn set default ?"; $stmt = mysqli_stmt_init($db_conn_handle); mysqli_stmt_prepare($stmt, $field_modification_sql_command); mysqli_stmt_bind_param($stmt, 's', $new_field_default_value); $temp_db_res = mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); here (insecure) code using concatenation , pure query execution, work (the mysqli_query() call returns true, , default value of field indeed altered): $new_field_default_value = 'test'; $field_modification_sql_command

jquery - Javascript Not Running or Working? -

Image
i have project includes login form password meter. followed a tutorial cssdeck , tried copy-pasting code jsfiddle see results. works on demo, not on my jsfiddle . issue password meter not working. have read through javascript , can not see wrong it. suggestions nice. why exact same code not work in fiddle? $(function(){ var pass1 = $('#password1'), pass2 = $('#password2'), email = $('#email'), form = $('#main form'), arrow = $('#main .arrow'); // empty fields on load $('#main .row input').val(''); // handle form submissions form.on('submit', function(e){ // entered correctly? if ($('#main .row.success').length == $('#main .row').length) { // yes! alert("thank trying out demo!"); e.preventdefault(); // remove allow actual submission } else { // no. preven

Blackberry app version update deletes persistent store object on some devices -

i have blackberry app stores object in persistent store. after updating app, supposed read existing value persistent store, if any, , continue use value. works on devices, not work on others. tested on several devices running os version 7, of work expected. on device using version 5 , using version 6, object no longer readable in persistent store. this case if don't change app other version number. same exact class/object being saved & loaded persistent store, , same object id used access it. the process i'm following reproduce is: completely delete app & it's data using command line. load version of app, downloading .jad file browser, verify stores data in persistent store. while app running in background, load later version via browser download of .jad file. after downloading later version, system asks if want replace previous version, , confirm do. the system loads new version, , prompts must reboot change take effect. select "reboot". d

How to generate byte arrays for sending data over a network in Java -

i trying connect postgresql server (implementing wire protocol) can't figure out how dynamically generate message frames of byte arrays. example, in following code i'm doing lot of system.arraycopy calls push generated bytes single byte array , seems there has better way. import java.io.*; import java.net.socket; import java.nio.bytebuffer; public class connection { public void connect(string hostname, int port) { try { socket dbsocket = new socket(hostname, port); dataoutputstream dout = new dataoutputstream(dbsocket.getoutputstream()); byte[] message = buildstartupmessage("sa"); dout.write(message); datainputstream din = new datainputstream(dbsocket.getinputstream()); byte bytes; while((bytes = din.readbyte()) != 0) { system.out.println(bytes); } } catch(exception e) { system.out.println("got exception"

elasticsearch - Error:Class cast exception in elastic search while sorting buckets in aggregation -

error: classcastexception[org.elasticsearch.search. aggregations.support.valuessource$bytes$withordinals$fielddata cannot cast org.elasticsearch.search.aggregations.support.valuessource$numeric]}{[vthdfzputegmgr8mes_b9g] my query: _search { "size" : 0, "query" : { "filtered" : { "query" : { "dis_max" : { "tie_breaker" : 0.7, "queries" : [ { "bool" : { "should" : [ { "match" : { "post.body" : { "query" : "check", "type" : "boolean" } } }, { "match" : { "post.parentbody" : { "query" : "check", &qu

python - Anaconda activate environment "The syntax of the command is incorrect" -

probably simple (i hope) activate environment_name giving me message "the syntax of command incorrect." i'm using windows 7, conda 3.19.0, python 2.7.11, , message both cmd.exe , anaconda command prompt. it may relevant has never worked me before installed anaconda - admin - (and environment i'm referencing tutorial example). even after remove environment , re-create still same thing: c:\anaconda>conda create -n snowflakes biopython fetching package metadata: .... solving package specifications: ............ package plan installation in environment c:\anaconda\envs\snowflakes: following new packages installed: biopython: 1.66-np110py27_0 msvc_runtime: 1.0.1-vc9_0 [vc9] numpy: 1.10.1-py27_0 pip: 7.1.2-py27_0 python: 2.7.11-0 setuptools: 19.2-py27_0 wheel: 0.26.0-py27_1 proceed ([y]/n)? y linking packages ... [ complete ]|##################################################| 1

bash - Grep N times from pipe using xargs -

i have file named input contains list of wikipedia or substring of wikipedia titles. want print out lines wikipedia titles, not substring. i have file named wikititle contains list of wikipedia titles. want grep each line input , if matches ^{string}$, want print out line. i came below command: cat input | xargs -0 -i{} bash -c 'grep -q -w ^{}$ wikititle && { echo {}; }' but gives me error of: xargs: command long how make happen? thanks! the right way print out lines found in both of 2 files comm : comm -12 <(sort input) <(sort wikititle) this vastly more efficient trying do: runs single pass, , needs store little content in memory @ time ( sort can have larger memory requirements, gnu implementation supports using disk-backed temporary storage). another more efficient approach following: grep -f -x -f input wikititle ...this run grep only once , using (newline-separated) strings given in input , against contents of wi

groovy - For loop variable initialisation from a list -

groovy allows unfolding lists in assignment, in: (x, y) = [1, 2] so assumed similar work in loop, in: list = [[1, 2], [2, 4], [3, 6]] ((elm1, elm2) in list) {...} which turns out syntax error. style not possible or there trick i'm missing? i guess won't work for loop (or don't know syntax), two-argument closure can used iterate such list , unfold tuples: def list = [[1, 2], [2, 4], [3, 6]] assert list.collect { a, b -> + b } == [3, 6, 9, ]

How to set android MediaPlayer volume according to ringtone volume? -

how can set mediaplayer sound volume according ringtone volume? i did method, doesn't work: mediaplayer player = mediaplayer.create(myactivity.this, r.raw.sound); audiomanager audio = (audiomanager) getsystemservice(context.audio_service); int currentvolume = audio.getstreamvolume(audiomanager.ringer_mode_normal); player.setvolume(currentvolume, currentvolume); instead of adjusting volume, should use setaudiostreamtype() set audio stream want play audio on - automatically uses volume of selected stream. example, if want audio play @ same volume notification would, use audiomanager.stream_notification : mediaplayer.setaudiostreamtype(audiomanager.stream_notification);

javascript - Click event only triggers once, after the page is loaded -

i have click event in jquery. desired behavior function execute every time link clicked. however, actual behavior page loads , function executed once , never again. offending code follows. thanks! <!doctype html> <head> <meta charset="utf-8"> <style> #sub { position:fixed; z-index:999; margin-top:180px; margin-left:200px; display:none;} </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function showdiv(divid) { $('.menu').hide(); $('#'+divid).fadetoggle('slow'); }; $(document).ready(function(){ $('a#opt1').click(showdiv('sub')); $('a#opt2').click(function(){$('.menu').hide();}); }); </script> </head> <body> <li><a id="opt1" href="#">option1</a></li> <li><a id="opt2" href="#">optio

c - unrolling loops macros needed -

consider following code: extern int conn_fds[max_clients]; extern int fl_conn_indexes[max_clients]; extern int fl_req_bufs[max_clients]; extern struct epoll_event estab_events[max_threads]; extern req_buf_t req_bufs[max_req_bufs]; extern int fl_req_bufs_top; extern int conn_statuses[max_clients]; extern int fl_conn_indexes_top; extern tcpl_nc_t nc_http_list; extern struct sockaddr_in conn_addresses[max_clients]; void accept_connections(unsigned int num_conns) { int fds[max_threads]; int conn_indexes[max_threads]; int conn_idx=0; int new_bottom; socklen_t slenghts[max_threads]; void *labels1[max_threads] = {&&a0,&&a1,&&a2,&&a3,&&a4,&&a5,&&a6,&&a7,&&a8,&&a9,&&a10,&&a11,&&a12,&&a13,&&a14,&&a15}; void *labels2[max_threads] = {&&b0,&&b1,&&b2,&&b3,&&b4,&&b5,&&b6,&&b7,