I have a array like this
`
(lldb) po list
(NSArray *) $1 = 0x0759f120 <__NSArrayI 0x759f120>(
{
EmployeeCode = 7593;
InDate = "27/02/2013";
InTime = "08:11";
InTime2 = "00:00";
OutDate = "27/02/2013";
OutDate2 = "01/01/1901";
OutTime = "17:42";
OutTime2 = "00:00";
Present = 1;
}
)
`
How can I access each an individual elements in here. Plz help me
Thanks
Your NSArray contains values in NSDictionary format, so at each index within array you'll get a NSDictionary, so you can access it like this,
NSLog(#"Employee Code = %#", [[yourArray objectAtIndex:index] valueForKey:#"EmployeeCode"]);
where, index = 0 & index < [yourArray count]
Related
In the code below cohort_counts_4 is a dataframe that has 3 columns g,samplingRate and samplingRate1. In the rowDF variable I am collecting the columns samplingRate and samplingRate1 (which are percentages). And in the
percentages variable I am converting it to Array[Double].
When I am trying to run this, I am getting the error below during runtime in the percentages. I need it to be Array[Double] as I have to randomSplit in the next step.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.Double.
Please let me know your thoughts.
sample data of percentages -
percentages: Array[Seq[Double]] =
Array(WrappedArray(0.06449504858964898, 0.9355049514103511)
, WrappedArray(0.015861918725594032, 0.9841380812744059)
, WrappedArray(0.22082241578907924, 0.7791775842109208)
, WrappedArray(0.14416119376185044, 0.8558388062381496)
, WrappedArray(0.10958692395592619, 0.8904130760440738)
, WrappedArray(1.0, 0.0)
, WrappedArray(0.6531128743810083, 0.3468871256189917)
, WrappedArray(0.04880653326943304, 0.9511934667305669))
val cohortList = cohort_counts_4.select("g").collect().map(_(0)).toList
var cohort_list = new ListBuffer[org.apache.spark.sql.DataFrame]()
var total_rows: Int = 0
for (igroupid<-cohortList){
val sample_rate = cohort_counts_4.filter(col("g")===igroupid).select("samplingRate","samplingRate1")
cohort_list += sample_rate
val curr_rows = sample_rate.count().toInt
total_rows += curr_rows
}
val customers_new = cohort_list.reduce(_ union _)
val rowDF = customers_new.select(array(customers_new.columns.map(col):_*) as "row")
var percentages =Array(rowDF.collect.map(_(0)).asInstanceOf[Double])
// var percentages = rowDF.collect.map(_.getSeq[Double](0))
val uni = customers_2.select("x","g").distinct
.randomSplit(percentages)
I changed the code from
var percentages =Array(rowDF.collect.map(_(0)).asInstanceOf[Double])
to below
var percentages =rowDF.collect.map(_(0).asInstanceOf[Seq[Double]]).flatten
and it worked.
I am trying to create a node programatically like so,
$newNode = (object) NULL;
$newNode->type = 'job';
$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->tid = 0;
$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][2] = 2;
$newNode->field_job_category['und'][4] = 4;
//die(print_r($newNode));
// save node
node_save($newNode);
Here I have potentially 4 taxonomies to pick from (their id indicated in brackets) Creative (2), Technical (3), Marketing (4), Client Services (6).
On node_save I am getting the following error,
500 Internal Server Error : An error occurred (23000):
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tid'
cannot be null
How do I overcome this this I would have thought setting the field_job_category to the id of the taxonomy would be enough?
Delete $newNode->tid = 0; and prepare object :
$newNode = new stdClass();
$newNode->type = 'job';
node_object_prepare($node);
$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][]['tid'] = 2; // right syntax
$newNode->field_job_category['und'][]['tid']= 4; // right syntax
//die(print_r($newNode));
// save node
node_save($newNode);
If you want to have only one term id associated:
$newNode->field_category[LANGUAGE_NONE][0]['tid'] = <actual term id>
If you have multiple term ids to associate:
Iterate over your array of term ids, and increment index. Something like:
$newNode->field_category[LANGUAGE_NONE][0]['tid'] = <actual term id>
$newNode->field_category[LANGUAGE_NONE][1]['tid'] = <actual term id>
$newNode->field_category[LANGUAGE_NONE][2]['tid'] = <actual term id>
Note the index values above.
And, I usually set following attributes set for a new node:
I get "IndexError: list is out of range" when I input this code. Also, the retmax is set at 614 because that's the total number of results when I make the request. Is there a way to make the retmode equal to the number of results using a variable that changes depending on the search results?
#!/usr/bin/env python
from Bio import Entrez
Entrez.email = "something#gmail.com"
handle1 = Entrez.esearch(db = "nucleotide", term = "dengue full genome", retmax = 614)
record = Entrez.read(handle1)
IdNums = [int(i) for i in record['IdList']]
while i >= 0 and i <= len(IdNums):
handle2 = Entrez.esearch(db = "nucleotide", id = IdNums[i], type = "gb", retmode = "text")
record = Entrez.read(handle2)
print(record)
i += 1
Rather than using a while loop, you can use a for loop...
from Bio import Entrez
Entrez.email = 'youremailaddress'
handle1 = Entrez.esearch(db = 'nucleotide', term = 'dengue full genome', retmax = 614)
record = Entrez.read(handle1)
IdNums = [int(i) for i in record['IdList']]
for i in IdNums:
print(i)
handle2 = Entrez.esearch(db = 'nucleotide', term = 'dengue full genome', id = i, rettype = 'gb', retmode = 'text')
record = Entrez.read(handle2)
print(record)
I ran it on my computer and it seems to work. The for loop solved the out of bounds, and adding the term to handle2 solved the calling error.
I made a type, but I don't know how to use it properly and I don't found any solution on google.
type Sample =
{
TrackPosition : int
TubePosition : int
Barcode : string
}
let arraySamples = Array.create Scenario.Samples.NumberOfSamples **Sample**
BarcodeGenerieren.Samples.Sample
let mutable trackPosition = Scenario.Samples.StartTrackPositions
let mutable index = 1
for i in 1 .. Scenario.Samples.NumberOfSamples do
let randomNumber = System.Random().Next(0,9999)
if index > 24 then
trackPosition <- trackPosition + 1
index <- 1
arraySamples.[index] <- **new Sample{TrackPosition= trackPosition, TubePosition = index, Barcode = sprintf "100%s%06d" ((trackPosition + 1) - Scenario.Samples.StartTrackPositions) randomNumber}**
So my question is, what should I changed so that it works, when I will give the type of the array and when I will give the sample with data to the array?
You have created what is referred to as a record type. You can initialise it with the following syntax
{TrackPosition = 0;TubePosition = 0;Barcode = "string"}
your syntax in the last line is almost correct - it should be
arraySamples.[index] <- Sample{
TrackPosition= trackPosition;
TubePosition = index;
Barcode = sprintf "100%s%06d" ((trackPosition + 1) - Scenario.Samples.StartTrackPositions) randomNumber}
The changes are
Eliminate new
replace , with ;
I'm building a web app with django. I use postgresql for the db. The app code is getting really messy(my begginer skills being a big factor) and slow, even when I run the app locally.
This is an excerpt of my models.py file:
REPEATS_CHOICES = (
(NEVER, 'Never'),
(DAILY, 'Daily'),
(WEEKLY, 'Weekly'),
(MONTHLY, 'Monthly'),
...some more...
)
class Transaction(models.Model):
name = models.CharField(max_length=30)
type = models.IntegerField(max_length=1, choices=TYPE_CHOICES) # 0 = 'Income' , 1 = 'Expense'
amount = models.DecimalField(max_digits=12, decimal_places=2)
date = models.DateField(default=date.today)
frequency = models.IntegerField(max_length=2, choices=REPEATS_CHOICES)
ends = models.DateField(blank=True, null=True)
active = models.BooleanField(default=True)
category = models.ForeignKey(Category, related_name='transactions', blank=True, null=True)
account = models.ForeignKey(Account, related_name='transactions')
The problem is with date, frequency and ends. With this info I can know all the dates in which transactions occurs and use it to fill a cashflow table. Doing things this way involves creating a lot of structures(dictionaries, lists and tuples) and iterating them a lot. Maybe there is a very simple way of solving this with the actual schema, but I couldn't realize how.
I think that the app would be easier to code if, at the creation of a transaction, I could save all the dates in the db. I don't know if it's possible or if it's a good idea.
I'm reading a book about google app engine and the datastore's multivalued properties. What do you think about this for solving my problem?.
Edit: I didn't know about the PickleField. I'm now reading about it, maybe I could use it to store all the transaction's datetime objects.
Edit2: This is an excerpt of my cashflow2 view(sorry for the horrible code):
def cashflow2(request, account_name="Initial"):
if account_name == "Initial":
uri = "/cashflow/new_account"
return HttpResponseRedirect(uri)
month_info = {}
cat_info = {}
m_y_list = [] # [(month,year),]
trans = []
min, max = [] , []
account = Account.objects.get(name=account_name, user=request.user)
categories = account.categories.all()
for year in range(2006,2017):
for month in range(1,13):
month_info[(month, year)] = [0, 0, 0]
for cat in categories:
cat_info[(cat, month, year)] = 0
previous_months = 1 # previous months from actual
next_months = 5
dates_list = month_year_list(previous_month, next_months) # Returns [(month,year)] from the requested range
m_y_list = [(date.month, date.year) for date in month_year_list(1,5)]
min, max = dates_list[0], dates_list[-1]
INCOME = 0
EXPENSE = 1
ONHAND = 2
transacs_in_dates = []
txs = account.transactions.order_by('date')
for tx in txs:
monthyear = ()
monthyear = (tx.date.month, tx.date.year)
if tx.frequency == 0:
if tx.type == 0:
month_info[monthyear][INCOME] += tx.amount
if tx.category:
cat_info[(tx.category, monthyear[0], monthyear[1])] += tx.amount
else:
month_info[monthyear][EXPENSE] += tx.amount
if tx.category:
cat_info[(tx.category, monthyear[0], monthyear[1])] += tx.amount
if monthyear in lista_m_a:
if tx not in transacs_in_dates:
transacs_in_dates.append(tx)
elif tx.frequency == 4: # frequency = 'Monthly'
months_dif = relativedelta.relativedelta(tx.ends, tx.date).months
if tx.ends.day < tx.date.day:
months_dif += 1
years_dif = relativedelta.relativedelta(tx.ends, tx.date).years
dif = months_dif + (years_dif*12)
dates_range = dif + 1
for i in range(dates_range):
dt = tx.date+relativedelta.relativedelta(months=+i)
if (dt.month, dt.year) in m_y_list:
if tx not in transacs_in_dates:
transacs_in_dates.append(tx)
if tx.type == 0:
month_info[(fch.month,fch.year)][INCOME] += tx.amount
if tx.category:
cat_info[(tx.category, fch.month, fch.year)] += tx.amount
else:
month_info[(fch.month,fch.year)][EXPENSE] += tx.amount
if tx.category:
cat_info[(tx.category, fch.month, fch.year)] += tx.amount
import operator
thelist = []
thelist = sorted((my + tuple(v) for my, v in month_info.iteritems()),
key = operator.itemgetter(1, 0))
thelistlist = []
for atuple in thelist:
thelistlist.append(list(atuple))
for i in range(len(thelistlist)):
if i != 0:
thelistlist[i][4] = thelistlist[i-1][2] - thelistlist[i-1][3] + thelistlist[i-1][4]
list = []
for el in thelistlist:
if (el[0],el[1]) in lista_m_a:
list.append(el)
transactions = account.transactions.all()
cats_in_dates_income = []
cats_in_dates_expense = []
for t in transacs_in_dates:
if t.category and t.type == 0:
if t.category not in cats_in_dates_income:
cats_in_dates_income.append(t.category)
elif t.category and t.type == 1:
if t.category not in cats_in_dates_expense:
cats_in_dates_expense.append(t.category)
cat_infos = []
for k, v in cat_info.items():
cat_infos.append((k[0], k[1], k[2], v))
Depends on how relevant App Engine is here. P.S. If you'd like to store pickled objects as well as JSON objects in the Google Datastore, check out these two code snippets:
http://kovshenin.com/archives/app-engine-json-objects-google-datastore/
http://kovshenin.com/archives/app-engine-python-objects-in-the-google-datastore/
Also note that the Google Datastore is a non-relational database, so you might have other trouble refactoring your code to switch to that.
Cheers and good luck!