javascript,json,mongodb,meteor,data
Simple use underscores _.extend function. Like this: var newProfile = _.extend( JSON.parse(Assets.getText('test.json')), {user: id} ) Profiles.insert(newProfile) ...
This relates to column oriented databases versus row oriented. Your first example is a row oriented data structure, and the second is column oriented. In the particular case of Python, the first could be made notably more efficient using slots, such that the dictionary of columns doesn't need to be...
For basics, you should check out the JSON library from Python: https://docs.python.org/2/library/json.html Here's a quick example: >>> import json # grabs config.json in same directory as python file >>> with open("config.json", "r") as e: ... myconfig = json.load(e) >>> print myconfig {u'4': u'5', u'6': 7} # dump to string representation...
.asc means you likely chose the ASCII Grid download option from CCAFS. These are simple text files with a 6 line header containing the geographic information. If you just want to load the data into a numpy array you can use the loadtxt function. You just have to skip the...
You can use dplyr for this: df %>% mutate(new.date = cut.Date(as.Date(Date, format = '%Y-%m-%d'), "month")) %>% group_by(new.date) %>% summarise(count = n()) mutate will create a new column with cutted dates, group_by by month and summarise will count the number of entries. Also, if you need year and abbreviation month, just...
You are using "%d" to print a float. That leads to undefined behavior. Instead of printf("\nEl valor del cociente es: %d",(polinomio_->polinomio->cociente)); use printf("\nEl valor del cociente es: %f",(polinomio_->polinomio->cociente)); // ^^^ ...
java,string,data,transform,simpledateformat
I don't believe you need to do any conversion, as there is a natural order of those strings (at least I can't see a counterexample). So Collections.sort() should do the trick....
This is a complete code for compression and decompression of positive long integers based on h3n's idea of using 1 byte for 2 characters, thanks! It uses 15 numeral system: from 0000 to 1110 binary and 1111 (0xF) as a separator. compression: public List<byte> EncodeNumbers(List<long> input) { List<byte> bytes =...
What language are you using? In Java, you can get the page HTML content using something like this: URL url; InputStream is = null; BufferedReader br; String line; try { url = new URL("http://hazmat.globalincidentmap.com/home.php"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine())...
Replace $('#stars').html('*'); with $('#stars')[0].innerHTML += '*'; That will append the string to the innerHTML of the DOM element that your selector selected...
Your question is answered here: jQuery .data() Not Updating DOM $('#foo li[data-my-key="54321"]') is a attribute selector. Using .data(..) changes the elements properties which you cannot select from without using a filter. If you want to get all the elements with a certain property you can do this (using filter(...)): $('#foo...
ios,data,filepath,nsdocumentdirectory
The pngData is written to a incorrect path /path/to/sandbox/Documents1431292149 which is not exist. You should replace filePath = [documentsPath stringByAppendingString:timeTag]; with filePath = [documentsPath stringByAppendingPathComponent:timeTag]; ...
javascript,json,node.js,data,dynamic-data-exchange
You can, however the changes you make will NOT be persisted. Also, if you use cluster, every process will have a different version of your object. myJsonFile.json { "files": { "rootNeeded": [], "folders": [], "files": [], "images": [], "text": [], "unknown": [] } } mod1.js var json = require('./myJsonFile'); function...
Call this.notifyPath('navigator.currentStep', this.navigator.currentStep). See https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#set-path. Sometimes imperative code needs to change an object’s sub- properties directly. As we avoid more sophisticated observation mechanisms such as Object.observe or dirty-checking in order to achieve the best startup and runtime performance cross-platform for the most common use cases, changing an object’s sub-properties directly...
You're going in the right direction, but there are some other things that need to be more clearly thought out. You're going to have to define what constitutes a "hack" vs a "fail". Especially with new systems, users get confused and it's pretty easy for them to make honest mistakes....
Json.loads will also decode that dictionary. So to access cpu_count for example it would be json_data["Hosts"]["cpu_count"]. The json library will turn everything into a standard python data type (dict, list, int, str) or from those data type into a json readable format. You can also define a parser to parse...
django,data,scikit-learn,analysis
Django is a python framework meaning that you need to have python installed to use it. Once you have python, you can use whatever python package you want (compatible with the version of python you are using).
I handled this by adding my array data as option in Wordpress using add_option inner function.
java,dictionary,data-structures,data
This implementation already promises constant time get/put operations. The worst case is when inserting a new value that has never been seen yet. In this case you will: Attempt to find the value in the values map - O(1), since it's a HashMap. Not find it, and put the value...
Try this code NSArray *Sunday=[[dict objectForKey:@"Sunday"] allValues]; NSLog(@"Sunday: %@",[Sunday description]); ...
You can load the .txt file into MatLab: load audio.txt then save them save audio audio (the first "audio" is the ".mat" file, the second "audio" is the name of the variable stored in it. Hope this helps....
Try this: $PCname = Read-Host "Please enter the PC Name" $Userid = Read-Host "Please enter the Uder ID" Copy-Item -LiteralPath \\$PCname\C`$\Users\$UserID\AppData\Roaming\Nuance\NaturallySpeaking12\Dragon.log -Destination "\\Static PC\C`$\Users\MyName\Desktop\Dragon Logs" -Force $PCname and $Userid are examples of powershell variables. The values are to be entered when you run the script. The other answer is trying...
python,math,random,data,latitude-longitude
I think this is what you are trying to do. I understand you are writing to a file; I took that off here just for the sake of this example. import random import sys import math latitude = 19.99 longitude = 73.78 def generate_random_data(lat, lon, num_rows): for _ in xrange(num_rows):...
I think I know what's going on. If you look at the exception, your stack trace indicates Cayenne version being v.3.0RC2. This is a version of the runtime. 2 files (one of which is called something like "cayenne-project.xml"), were generated by the Modeler version 3.1. You need to ensure that...
angularjs,spring,model-view-controller,data,hateoas
To be truly HATEOAS compliant, the service (spring) needs to provide to the client all the hypermedia controls (links) to perform sorting. The client should never sort by some data field...it should only sort by what sort options are provided to the client by the server. This sorting may itself...
javascript,json,meteor,data,startup
Ok, you'll want to check out Structuring your application. You'll have to make the file with the definition load earlier, or the one with the fixture later. Normally you have your collections inside lib/ and your fixtures inside server/fixtures.js. So if you put your insert code into server/fixtures.js it'll work....
Well the most reliable way to do this would be to use an HTML (or XML) parser. However, if the HTML is always formatted the same way, i.e. like this: <tr> <td width="10%" valign="top"><p>City:</p></td> <td colspan="2"><p> ******* </p></td> </tr> with the city name appearing where the asterisks are, then the...
There are a lot of options: you might switch from Excel to Access (if your customer has a license for it) and have Access read the same database your PHP program writes to. To notify them of changes you can send an email (only for notification, not for transfer of...
r,data,statistics,analytics,outliers
I believe that "outlier" is a very dangerous and misleading term. In many cases it means a data point which should be excluded from analysis for a specific reason. Such a reason could be that a value is beyond physical boundaries because of a measurement error, but not that "it...
data,tooltip,visualization,linechart
I got this to work using google.visualization.LineChart instead of google.charts.Line. It gives me both points and tooltips, see here: and here: http://crclayton.com/example.html Instead of using google.load('visualization', '1.1', {packages: ['line']}); Just try including <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> Then instead of: var chart = new google.charts.Line(document.getElementById('linechart'));...
function,excel-vba,data,filter
Try this (off the top of my head) Sub Macro1() Static Filter as Integer Columns("C:C").Select if Filter = 0 then ActiveSheet.ListObjects("Table_Query1_added_columns2").Range.AutoFilter _ Field:=3, Criteria1:="102" Filter = 1 ElseIf Filter = 1 then ActiveSheet.ListObjects("Table_Query1_added_columns2").Range.AutoFilter _ Field:=3, Criteria1:="103" Filter = 2 Else ActiveSheet.ListObjects("Table_Query1_added_columns2").Range.AutoFilter _ Field:=3, Criteria1:="101" Filter = 0 End Sub By...
If one applies Law of Demeter, which is also known as "principle of least knowledge", and Single Responsibility Principle, then one would like to write a code like this: Quotation q = dao.fetchQuotation(someCondition); totalPrice = q.getTotalPrice(); //Computation inside it If the computation is bit complicated and does not involve just...
Write it in activity that passing data Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class); custaddress.putExtra("key",value); startActivity(custaddress); Write below code in activity that catching data Intent intent=getIntent(); String mString=intent.getStringExtra("key"); hope this will help you...
Some of the arguments in write.table are by default TRUE. Change it to FALSE and it should work write.table(c, "~/XXX/XXX.txt", sep="\t", quote=FALSE, row.names=FALSE, col.names=FALSE) NOTE: c is a function. So, it is better to give object names that are not functions....
pickle would also work, for storing data between programs, or even between different runs of the same program:: from module 1: import pickle f = open(file_Name,'wb') pickle.dump(assignment_data, f) f.close() from module 2: import pickle f = open(file_Name,'rb') pickle.load(assignment_data, f) f.close() (more elegantly with 'with ......') pickle.load knows that it's getting...
You can use zip function to get the columns of your file and also use csv module for reading a csv file : import csv with open('file_.csv','rb') as f : csvreader=csv.reader(f,delimiter=' ') print zip(*csvreader) And for huge files use itertools.izip : import csv from itertools import izip with open('file_.csv','rb') as...
database,spring,data,transactions,transactional
Its not about stored data in transaction. Its about running some operations in one transaction. Imagine that you create banking system, and you have method for making money transfer. Lets assume that u want to transfer amount of money from accountA to accountB You can try sth like that in...
Hopefully this will help: http://lightblue.sourceforge.net/ This is an API for python's bluetooth feature...
javascript,data,google-analytics
Sure. Just be sure each account has it's own tracking ID. Then, something like the following (after including the analytics code, of course): ga('create', trackingId1, window.location.hostname); ga('send', 'pageview'); ga('create', trackingId2, 'auto', {'name': 'secondAccount'}); ga('secondAccount.send', 'pageview'); I'm sure there is documentation for this on Google, but the Analytics docs are a...
EDIT I have updated the code to give you a better understanding of the process: % An empty array: importedarray = []; % Open the data file to read from it: fid = fopen( 'dummydata.txt', 'r' ); % Check that fid is not -1 (error openning the file). % read...
If I understand your question correctly, you should do something like this: class MyPickerController : UIViewController { @IBOutlet weak var myLabel: UILabel! var pickerData:[String] func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { myLabel.text = pickerData[row] performSegueWithIdentifier( "mySegueName", sender: self ) } func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if...
Best part in Python is that creating new objects on the fly is very easy. You can make a method return a tuple of two values. def dataPrinter(): gen1 = headerBody(columns_no) gen2 = dataBody(columns_no) return gen1, gen2 And from the calling side, you can get them either as a single...
data,data-mining,market-basket-analysis
You can try Association Rules (apriori for example), Collaborative Filtering (item-based or user-based) or even Clustering. I don't know what you are trying to do, but if you have a data-set and you need to find the most frequent item-set you should try some of the above techniques. If you're...
javascript,input,data,datatable
I created the whole solution on codepen. This is the function used: var clicks = 0; function csv() { var box = document.getElementsByName('text')[0]; if(clicks === 0){ var newcsv = ""; var tds = document.getElementsByTagName("TD"); for(var i = 0; i < tds.length; i++) { newcsv += tds[i].innerHTML; if(i != tds.length-1) newcsv...
c#,multithreading,user-interface,data,control
It looks like, with the this.cb_currentProfile.SelectedItem = 2 statement, you intend to set the selection of the ComboBox by index. The ComboBox.SelectedItem Property accepts an Object and attempts to find it in its collection of items, selecting it if successful, and doing nothing otherwise. To select a particular index of...
python,table,data,beautifulsoup,scrape
Try this import urllib2 from lxml import etree url = 'http://www.nfl.com/stats/categorystats?archive=false&conference=null&role=OPP&offensiveStatisticCategory=null&defensiveStatisticCategory=INTERCEPTIONS&season=2014&seasonType=REG&tabSeq=2&qualified=false&Submit=Go' response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.parse(response,htmlparser) text = tree.xpath('//a[contains(text(),"Miami Dolphins")]/parent::td/following-sibling::td[10]/text()') if text: print...
You can use Guava's Table. For instance using a HashBasedTable: Table<RowType, ColumnType, String> table = HashBasedTable.create(); ...
python,csv,pandas,data,grouping
I can get the data sorted using: import csv import pandas from collections import Counter from collections import defaultdict, Counter data = pandas.read_csv(filename.csv', delimiter =',') byqualityissue = data.groupby(["CompanyName","QualityIssue"]).size() But not in the format I want, and then it's not sorting by the top number of callers....
does this answer your need ? merge(df1, df2, by.x=c("ID","DOB")) ...
python,data,matplotlib,matplotlib-basemap,imshow
I now understand. You are trying to combine answers you received from here-imshow and here-hexbin. Your problem boils down to the fact that you want to use your Basemap as the "canvas" on which you plot your 2D histogram. But instead of doing that, you are making a Basemap then...
php,database,sqlite,data,hierarchical
There are a couple of answers in SO exactly about your problem: Move node in nested set Move node in Nested Sets tree About the time your delete method is taking to run, 30ms it's very little for this kind of operation, so there's nothing to worry about. Don't fall...
javascript,node.js,asynchronous,data,return
For any asyn function you need to have a callback function which gets executed once the operation is complete. You can modify your code like this and try. var diskspace = require('diskspace'); var fs = require('fs'); var aux; function getDiskSpace(cb){ diskspace.check('C',function(err, total, free, status){ var arr = []; var aux=new...
No, your understanding of % (modulo) is incorrect. Specifically you seem to ignore the reason for the right-hand argument, and assume it's always a constant 10 which is simply false. The expression x % y will return a value in the range 0 to (y - 1), inclusive (assuming both...
Your approach is too complex: the loop is trying to maintain the state, and has a long chain of conditions to decide what to do with the next token. Rather than doing your strtoks one at a time, do the first one to get the word, the second one to...
r,datetime,data,survival-analysis,poisson
I hope this does what you need. I've used lubridate and dplyr because they make things easier but the same results could be achieved in base. There's no need to retain year_done or first_jan_done, these can be removed with %>% select(-year_done, -first_jan_done) but I thought I would leave them in...
From standard 23.3.6.1 Class template vector overview The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size() so &v[0] indeed...
There are probably some more performant ways to do this, but I'd just use a simple for loop. var arr1 = [.84, .01, .95, 1, .22, .453, .194, .43]; var arr2 = [.54, .09, .10, 0, .76, .12, .41, .99]; var arr3 = [1, .26, .90, .65, .88, .33, .854,...
Say we put your data in column A: and run this short macro: Sub croupier() Dim N As Long, K As Long, i As Long, ary(), bry() Dim v As String N = Cells(Rows.Count, "A").End(xlUp).Row ReDim ary(1 To N) ReDim bry(1 To N) For i = 1 To N v...
it is probably giving you the data as a string try: $('body').on('click', 'a.status', function() { var $this = $(this); var data = $this.data("set"); data.result = data.result == 3 ? 4 : 3; $this.data("set", JSON.stringify(data)); console.log(data) }); ...
spring,data,gradle,neo4j,spring-data-neo4j
The neo4j-ogm-test artifact was not fully published in M1, but it is available. You will need to set the following gradle dependency: dependencies { testCompile(group: 'org.neo4j', name: 'neo4j-ogm-test', version: '1.0.0.BUILD-SNAPSHOT', classifier: 'tests') } repositories { maven { url 'http://repo.spring.io/libs-snapshot-continuous-local' } } ...
As the first comment says, your question is quite large. When you say 'one form on several view', I consider it as 'one form per view'. Keep It Simple S... ;) (Except if you use page control for your form.) Basically, you have three ways to store data : NSUserDefaults...
c#,algorithm,data,graph,statistics
A simple way is to calculate the difference between every two neighbouring samples, eg diff= abs(y[x point 1] - y[x point 0]) and calculate the standard deviation for all the differences. This will rank the differences in order for you and also help eliminate random noise which you get if...
I've looked at the text file you supplied and tried to draw a few general conclusions - When there are two integers on a line, the second integer corresponds to the number of rows following. You always have (two integers (A, B) followed by "B" floats), repeated twice. After that...
Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...
php,jquery,database,select,data
Try this, It may help you. I have used JQuery Ajax. Also include JQuery library before use the below code. $('#myselect').change(function(){ var size = $('#myselect').val(); if(size != ''){ $.ajax({ type:'post', url:"/index.php/average_incomes_by_customer/" + size, cache:false, success: function(returndata){ console.log(returndata); //"returndata" is the result got from the DB. Use it where you want....
One way would be just to take a slice and then overwrite the columns: In [71]: df1 = df.loc[3:] df1.columns = df.loc[2].values df1 Out[71]: a b c d 3 6 4 2 1 You can then assign back to df a slice of the rows of interest: In [73]: df...
python,variables,csv,pandas,data
The problem is that n = df2['Name'] is actually a Pandas Series: type(df.loc[df.Name == 'Jake Wong'].Name) pandas.core.series.Series If you just want the value, you can use values[0] -- values is the underlying array behind the Pandas object, and in this case it's length 1, and you're just taking the first...
data,elasticsearch,model,nested,parent-child
Yes, indeed, that's possible with ES 1.5.* if you map projects as nested type and then retrieve nested inner_hits. So here goes the mapping for your sample document above: curl -XPUT localhost:9200/resumes -d ' { "mappings": { "resume": { "properties": { "name": { "type": "string" }, "position": { "type": "string"...
haskell,data,wrapper,monads,xmonad
You can use, for example, the Writer monad for that: import Control.Monad.Writer data DirtyThing = Keyboard | Mouse newtype Dirty m a = Dirty { unDirty :: WriterT [DirtyThing] m a } doFoo :: Dirty IO () doFoo = -- doing something dirty cleanup :: Dirty m a -> m a...
Not sure if you got it to work or not. But I got it to work with this. public class TestingForSO extends ActionBarActivity { private static final String ENAME = "ENAME"; EditText etename; String name = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_testing_for_so); if (savedInstanceState != null) {...
python,data,matplotlib,offline,heatmap
You use a heat map as the background for a geographical map (which I think is what you are asking about) using basemap and imshow. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np m = Basemap(width=12000000,height=9000000,projection='lcc', resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.) m.drawcoastlines(linewidth=0.25) data = 100*np.random.rand(10,10) m.imshow(data, interpolation = 'none') plt.show()...
try this df <- data.frame(Email.Address, First.Name, Last.Name, Company, stringsAsFactors = FALSE) Corp <- sapply(strsplit(sapply(strsplit(df$Email.Address,"@"),"[[",2),"[.]"),"[[",1) F.Name <- sapply(strsplit(sapply(strsplit(df$Email.Address,"@"),"[[",1), "[.]"),"[[",1) L.Name <- sapply(strsplit(sapply(strsplit(df$Email.Address,"@"),"[[",1),"[.]"),tail,n=1) L.Name[L.Name == F.Name] <- NA OUT <- data.frame(df$Email.Address, F.Name, L.Name, Corp) df[df=="NA" |is.na(df)] <- OUT[df=="NA" |is.na(df)] df the function...
Your table seems to have some serious normalization issues. You have to perform an INNER JOIN on AssessmentCode first: SELECT t1.StudentID, t1.AssessmentCode, t1.Result AS Level, CAST(t2.Result AS INT) AS Mark FROM ( SELECT StudentID, AssessmentCode, Result FROM mytable WHERE ResultGroup = 'IBLevel' ) AS t1 INNER JOIN ( SELECT StudentID,...
I'd like to randomly generate 32 lines of hex strings Random rnd = new Random(); int bits = 12; // bits in "byte" int length = 10; // number of "bytes" in string int n = 32; // number of strings for (int i = 0; i < n;...
There is not a shortcut as I was hoping. For a gps tracker device that sends TCP/UDP data to an ip address and port we really need a server. There will be no POST/GET data. The server will receive data through a port that needs to be decoded. But it...
Create a second entity (java class) e.g. UserPost: @Entity @Table(...) public class UserPost { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private long userId; ... } Then add @OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User: @OneToMany(cascade={...}) @JoinColumn(name="userId")...
java,database,database-design,data
If you can populate D via a single query, then back a view with that query and you're done (I'm pretty sure most popular sql servers don't allow, say, procedure backed views). Otherwise, yea, you'll have some process that turns data from a,b,c into d. That can be through stored...
This should work: data want; set have; array Bins{*} Bin:; array freq_Bin{4}; do k=1 to dim(Bins); if Bins(k) ne . then freq_Bin(Bins(k))=1; end; drop k; run; I tweaked your code somewhat, but really the only problem was that you need to check that Bins(k) isn't missing before trying to use...
OK, what you need is a regression (see: Wolfram, Wiki) or aproximation (see: Wiki). General idea of both is exactly what you need: finding a function that will match a function for which you have samples as close as possible. There are several methods, you can google them up as...
There is no "name" for this that I know of, but an array of linked list nodes would work quite well for this. Traditionally linked lists are separate and simply a row of items pointing to the next. However, there is no reason why certain linked list nodes cannot point...
matlab,data,integration,splines
First of all, you should not use the same letter for a bunch of things; your code is pretty hard to read because one has to figure out what T means at every instance. Second, pure math helps: after a change of variables and simple computation, the double integral becomes...
python,data,matplotlib,analysis
This seems like it would be a lot simpler using a Pandas dataframe. Then, part of your problem is analogous to this question: Read multiple *.txt files into Pandas Dataframe with filename as column header import pandas as pd import matplotlib.pyplot as plt filelist = ['data1.txt', 'data2.txt'] dataframe = pd.concat([pd.read_csv(file,...
data,spreadsheet,rdbms,flat-file
They are handling data in fixed-size blocks and indexing.
you have to add this attribute to the div then hide it: [data-id="b5c3cde7-8aa1"] { display:none; } <div data-id="b5c3cde7-8aa1">hide me</div> ...
I don't clearly see why this got downvoted, but nevermind. I found the solution myself: The Ambari Metrics API can deliver the data in question, e.g. CPU load, memory usage, Network bandwith or load factors by sending a GET Request to http://<ambari-server>:8080/api/v1/clusters/<cluster-name>?fields=metrics/<metric>[<start>,<end>,<step>] while the metric can be network, cpu, cpus,...
When you want to pass datas from one page to another, Session is your best bet All you have to do is initiate session. page1.php --> This page contains your datas. Below code in your page1.php <?php session_start(); $_SESSION['username'] ='Mr.x'; $_SESSION['usertype'] = 'level1'; ?> page2.php --> Page from where you...
try this code $output['data'] = []; $fh = fopen("pv1_consultafolioTorre".".json", 'w'); while($row = mssql_fetch_array($query_result)) { $output['data'][] = array( $row['folio'], $row['MATNR'], $sucursalSolcitante, $sucursalResponsable, $row['fechaSolicitud'], $row['cantidadSolicitada'], $row['MATNR'], $row['fechaConfirmacion'], $row['cantidadConfirmada'], $result, 'Pendiente' ); } print $jsonencoded = json_encode($output, 128); fwrite($fh, $jsonencoded); ...