text
stringlengths
29
850k
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django_fsm import FSMField, transition from django.utils.encoding import python_2_unicode_compatible from listenclosely import managers from django.utils.timezone import now import datetime class NoAgentFound(Exception): """ Raised when strategy can not find agent to attend chat """ class AbstractContact(models.Model): id_service = models.CharField(_("Id Service"), unique=True, db_index=True, max_length=128) created = models.DateTimeField(_("Date created"), auto_now_add=True) class Meta: abstract = True verbose_name = _("Contact") verbose_name_plural = _("Contacts") @python_2_unicode_compatible class Asker(AbstractContact): """ Customer, client, ... the who ask a question and starts a chat """ class Meta: verbose_name = _("Asker") verbose_name_plural = _("Askers") def __str__(self): return _(u"Asker(id_service: %(id_service)s") % {'id_service': self.id_service} @python_2_unicode_compatible class Agent(AbstractContact): """ One who answer chat """ OFFLINE, ONLINE, BUSY = "Offline", "Online", "Busy" STATE_CHOICES = ( (OFFLINE, _("Offline")), (ONLINE, _("Online")), (BUSY, _("Busy"))) state = FSMField(default=OFFLINE, choices=STATE_CHOICES) class Meta: verbose_name = _("Agent") verbose_name_plural = _("Agents") objects = models.Manager() offline = managers.OfflineAgentManager() online = managers.OnlineAgentManager() busy = managers.BusyAgentManager() def __str__(self): return _(u"Agent(id_service: %(id_service)s, state:%(state)s") % {'id_service': self.id_service, 'state': self.state} @transition(field=state, source=OFFLINE, target=ONLINE) def register(self): """ Agent is registered into the system so now is online to answers """ @transition(field=state, source=ONLINE, target=OFFLINE) def unregister(self): """ Agent is not online anymore """ @transition(field=state, source=ONLINE, target=BUSY) def attend(self, chat): """ Agent is assigned to a chat so it is busy answering """ chat.agent = self @transition(field=state, source=BUSY, target=ONLINE) def release(self, chat): """ Agent finishes chat """ @python_2_unicode_compatible class Chat(models.Model): asker = models.ForeignKey(Asker, verbose_name=_("Asker"), related_name="chats") agent = models.ForeignKey(Agent, null=True, blank=True, verbose_name=_("Agent"), related_name="chats") created = models.DateTimeField(_("Date created"), auto_now_add=True) last_modified = models.DateTimeField(_("Last modified"), auto_now=True) PENDING, LIVE, TERMINATED = "Pending", "Live", "Terminated" STATE_CHOICES = ( (PENDING, _("Pending")), (LIVE, _("Live")), (TERMINATED, _("Terminated"))) state = FSMField(default=PENDING, choices=STATE_CHOICES) class Meta: verbose_name = _("Chat") verbose_name_plural = _("Chats") objects = models.Manager() pending = managers.PendingChatsManager() live = managers.LiveChatsManager() terminated = managers.TerminatedChatsManager() def __str__(self): return _(u"Chat(asker: %(asker)s, agent: %(agent)s, state: %(state)s") % {'asker': self.asker, 'agent': self.agent, 'state': self.state} @transition(field=state, source=[PENDING, LIVE], target=LIVE) def handle_message(self, message_id_service, contact_id_service, content, listenclosely_app): message = Message(id_service_in=message_id_service, chat=self, content=content, type=Message.INCOMING if contact_id_service == self.asker.id_service else Message.OUTGOING) if not self.agent: # get free online agents free_agent = listenclosely_app.strategy.free_agent() if free_agent: free_agent.attend(self) free_agent.save() else: message.save() # TODO: raise especific exception when no free agent to attend. Send auto message raise NoAgentFound("No agent to attend %s created by %s" % (self.id, contact_id_service)) sent_id = listenclosely_app.service_backend.send_message(message.chat.agent.id_service if message.incoming() else message.chat.asker.id_service, content) if sent_id: message.id_service_out = sent_id message.t_sent = now() message.save() @transition(field=state, source=PENDING, target=LIVE) def attend_pending(self, agent, listenclosely_app): agent.attend(self) agent.save() for message in self.messages.all(): sent = listenclosely_app.service_backend.send_message(message.chat.agent.id_service if message.incoming() else message.chat.asker.id_service, message.content) if sent: message.t_sent = now() message.save() @transition(field=state, source=LIVE, target=TERMINATED) def terminate(self): """ Chat is finished and Agent is free """ self.agent.release(self) self.agent.save() def is_obsolete(self, time_offset): """ Check if chat is obsolete """ return now() > datetime.timedelta(seconds=time_offset) + self.last_modified @python_2_unicode_compatible class Message(models.Model): id_service_in = models.CharField(_("Id Service In"), unique=True, db_index=True, max_length=128) id_service_out = models.CharField(_("Id service Out"), null=True, blank=True, max_length=128) chat = models.ForeignKey(Chat, verbose_name=_("Chat"), related_name="messages") created = models.DateTimeField(_("Date created"), auto_now_add=True) t_sent = models.DateTimeField(_("Date sent"), null=True, blank=True) content = models.TextField(_("Content")) INCOMING, OUTGOING = "Incoming", "Outgoing" TYPE_CHOICES = ((INCOMING, _("Incoming")), (OUTGOING, _("Outgoing")), ) type = models.CharField(_("Type"), max_length=128, default=INCOMING, choices=TYPE_CHOICES) class Meta: verbose_name = _("Message") verbose_name_plural = _("Messages") def incoming(self): return self.type == self.INCOMING def outgoing(self): return self.type == self.OUTGOING def __str__(self): return _(u"Chat(id_service: %(id_service)s, chat: %(chat)s") % {'id_service': self.id_service_in, 'chat': self.chat}
Cues for days at a new Byron Bay cafe: Owners Ben Gordon and Phil Taylor said they were absolutely blown away by the response they have received. ONE week since their official opening and the Byron Bay General Store has already made a huge splash. Queues outside the door, running down Bangalow Road, have been a common occurrence after the much anticipated store finally opened last Thursday. It is owned by Ben Gordon - the drummer in Byron-based metalcore band Parkway Drive - and Phil Taylor. They said they were absolutely blown away by the response they had received. "It's nice to see and it just shows you how great this town can be," Phil said. "It excites me personally to be a part of the community that we live in and this has become a social gathering point and that's pretty much why we did it." Ben said since the minute they opened their doors it had been non-stop busy. "I've had really good feedback from friends, family and the community at large," he said. "It has been a good three or four months of getting this place into shape and we did a lot of it ourselves, so it's been a lot of work but it is all worth it seeing people enjoy the space." Their vision was to create a great hangout for locals, while bringing back the block to its original roots. "What we've tried to create is a good, friendly atmosphere with healthy, good local food and I think we've done that," Ben said. "One of the reasons that makes this so special is because it is an historic building in Byron, it's been standing since 1947 and been a general store for the first 50 years of its existence. "It only changed to take-away in the late 90s." Having a personal affinity to Byron, Ben and Phil said it was important to them for a local to retain the business. "The main thing that made me want to open it was so many businesses in this town are getting sold and bought by non-locals, and I really think the more that locals own our businesses is how we retain the heart and true soul of this town," Ben said. "Rather than sit back and think someone else will do something, we decided to be pro-active and do it ourselves." One of the biggest things they wanted to focus on was making the shop as environmentally friendly as possible. "We've got solar on the roof so we are 80% solar powered, we made this fit out from all recyclable timber, we use as little plastic as possible, and are constantly looking for ways to soften our eco footprint," Ben said. The Byron Bay General Store is open seven days a week from 6.30am to 2pm. "Keep them rolling, keep on coming, don't stop, summer has just begun," Phil said.
#!/usr/bin/env python import matplotlib.pyplot as plt import sys filename = "reports/configuration.conftemperatureReport.txt" if (len(sys.argv) > 1): filename = sys.argv[1] with open(filename) as f: print f.readline() time = [] temp = [] for line in f: entry = line.split(":") #if (float(entry[0]) > 90000000): time.append(float(entry[0])) temp.append(float(entry[1])) #f = open("reports/energyReport.txt") #line = f.readline() #time2 = [] #power = [] #for line in f: # entry = line.split(":") # time2.append(float(entry[0])) # power.append(float(entry[1])) #f.close() #avg = [] #buf = [] #bufindex = 0 #for i in range(0,20001): # buf.append(temp[i]) #for i in range (0,10000): # avg.append(0.0) #sum = 0 #for i in range(0,20001): # sum += buf[i] #avg.append(sum/20001) #for i in range(10001, len(temp)-10000): # sum -= buf[bufindex] # buf[bufindex] = temp[i+10000] # sum += buf[bufindex] # avg.append(sum/20001) # bufindex += 1 # if (bufindex == 20000): # bufindex = 0 #for i in range (len(temp)-10001,len(temp)-1): # avg.append(0) #avg = [] #alpha = 0.0001 #avg.append(0.0) #for i in range(1,len(temp)): # a = temp[i]*alpha + (1-alpha)*avg[i-1] # avg.append(a) plt.plot(time, temp, 'ro') #plt.plot(time2, power, 'bo') #plt.plot(time, avg, 'b-') plt.show()
Fashion week brings out the best street style looks so I was inspired to channel my favorite trends into a look of my own. For spring I am still loving the pink and blue Pantone colors from a few years back, you know the classic millennial pink and blue? Since more subtle colors are in, excluding the bright pink that popped up on some runways, the pale blue and pink are still on trend. By far my favorite trend this season is the use of sheer fabrics and lace, seen already by Oscar de la Renta, Anna Sui, and Jonathan Simkhai to name a few. When I found this powder blue dress with sheer lace detailing, I fell in love. The main fabric of the dress was a nice, soft velvet that juxtaposed the delicate lace. Since I chose such a light color for the dress I decided to do all of my accessories in black to match the vibe in NYC more (trust me, black is the staple of all NYC closets). I decided to invest in a new pair of black boots, and this pointed toe, lace up pair is perfect to walk in with only a slight heel. They are more versatile than I expected and can easily be dressed up or down depending on the occasion. I added a basic black purse with a silver chain and a black suede jacket to complete the look. Although it is still warm in the city, I wanted to have a more fall appropriate outfit which is why I added the black jacket. With the current end of summer / beginning of fall weather it is best to dress in layers as the temperature changes drastically throughout the day. What did you / would you wear to NYFW?
# -*- coding: utf-8 -*- # Authors: Sung Jun Joo; Jason Yeatman; Kambiz Tavabi <ktavabi@gmail.com> # # # License: BSD (3-clause) import numpy as np import mnefun import os #import glob os.chdir('/home/sjjoo/git/BrainTools/projects/NLR_MEG') from score import score from nlr_organizeMEG_mnefun import nlr_organizeMEG_mnefun import mne import time #import pycuda.driver #import pycuda.autoinit t0 = time.time() mne.set_config('MNE_USE_CUDA', 'true') # At Possum projects folder mounted in the local disk raw_dir = '/mnt/diskArray/projects/MEG/nlr/raw' # At local hard drive out_dir = '/mnt/scratch/NLR_MEG4' if not os.path.isdir(out_dir): os.mkdir(out_dir) subs = ['NLR_102_RS','NLR_105_BB','NLR_110_HH','NLR_127_AM', 'NLR_132_WP','NLR_145_AC','NLR_150_MG', 'NLR_152_TC','NLR_160_EK','NLR_161_AK','NLR_163_LF', # 'NLR_162_EF', 'NLR_164_SF','NLR_170_GM','NLR_172_TH','NLR_174_HS','NLR_179_GM', 'NLR_180_ZD','NLR_201_GS','NLR_203_AM', 'NLR_204_AM','NLR_205_AC','NLR_207_AH','NLR_210_SB','NLR_211_LB', 'NLR_GB310','NLR_KB218','NLR_GB267','NLR_JB420', 'NLR_HB275','NLR_GB355'] # 'NLR_187_NB', # tmin, tmax: sets the epoch # bmin, bmax: sets the prestim duration for baseline correction. baseline is set # as individual as default. Refer to _mnefun.py bmax is 0.0 by default # hp_cut, lp_cut: set cutoff frequencies for highpass and lowpass # I found that hp_cut of 0.03 is problematic because the tansition band is set # to 5 by default, which makes the negative stopping frequency (0.03-5). # It appears that currently data are acquired (online) using bandpass filter # (0.03 - 326.4 Hz), so it might be okay not doing offline highpass filtering. # It's worth checking later though. However, I think we should do baseline # correction by setting bmin and bmax. I found that mnefun does baseline # correction by default. # sjjoo_20160809: Commented #params = mnefun.Params(tmin=-0.1, tmax=0.9, n_jobs=18, # t_adjust was -39e-3 # decim=2, n_jobs_mkl=1, proj_sfreq=250, # n_jobs_fir='cuda', n_jobs_resample='cuda', # filter_length='5s', epochs_type='fif', lp_cut=40., ## hp_cut=0.15,hp_trans=0.1, # bmin=-0.1, auto_bad=20., plot_raw=False, # bem_type = '5120-5120-5120') # This sets the position of the head relative to the sensors. These values a # A typical head position. So now in sensor space everyone is aligned. However # We should also note that for source analysis it is better to leave this as # the mne-fun default ==> Let's put None!!! """ Organize subjects """ #out,ind = nlr_organizeMEG_mnefun(raw_dir=raw_dir,out_dir=out_dir,subs=subs) """ The directory structure is really messy -- let's not use this function. """ os.chdir(out_dir) # #print(out) #params.subjects.sort() # Sort the subject list #print("Done sorting subjects.\n") """ Attention!!! 164_sf160707_4_raw.fif: continuous HPI was not active in this file! 170_gm160613_5_raw.fif: in _fix_raw_eog_cals...non equal eog arrays??? 172_th160825_6_raw.fif: origin of head out of helmet 201_gs150729_2_raw.fif: continuous HPI was not active in this file! 174_hs160620_1_raw.fif: Too many bad channels (62 based on grad=4000e-13, mag=4.0e-12) 174_hs160829_1_raw.fif: Too many bad channels (62 based on grad=4000e-13, mag=4.0e-12) 163_lf160707 : Too many bad channels --> Use grad=5000e-13, mag=5.0e-12 163_lf160920 : : Too many bad channels --> Use grad=5000e-13, mag=5.0e-12 """ #for n, s in enumerate(badsubs): # subnum = out.index(s) # print('Removing subject ' + str(subnum) + ' ' + out[subnum]) # out.remove(s) # ind[subnum] = [] # ind.remove([]) out = ['102_rs160815','105_bb161011','110_hh160809','127_am161004', '132_wp161122','145_ac160823','150_mg160825', '152_tc160623','160_ek160915','161_ak160916','163_lf160920', #'162_ef160829', '164_sf160920','170_gm160822','172_th160825','174_hs160829','179_gm160913', '180_zd160826','201_gs150925','203_am151029', '204_am151120','205_ac160202','207_ah160809','210_sb160822','211_lb160823', 'nlr_gb310170829','nlr_kb218170829','nlr_gb267170911','nlr_jb420170828', 'nlr_hb275170828','nlr_gb355170907'] # 187_nb161205: EOG channel number suddenly changes at run4 #%% out = ['170_gm160822'] #'162_ef160829', # '164_sf160920','170_gm160822','172_th160825','174_hs160829','179_gm160913', # '180_zd160826','201_gs150925','203_am151029', # '204_am151120','205_ac160202','207_ah160809','210_sb160822','211_lb160823', # 'nlr_gb310170829','nlr_kb218170829','nlr_gb267170911','nlr_jb420170828', # 'nlr_hb275170828','nlr_gb355170907'] for n, s in enumerate(out): print(s) for n, s in enumerate(out): params = mnefun.Params(tmin=-0.1, tmax=0.9, n_jobs=18, # t_adjust was -39e-3 decim=2, n_jobs_mkl=1, proj_sfreq=250, n_jobs_fir='cuda', n_jobs_resample='cuda', filter_length='5s', epochs_type='fif', lp_cut=40., # hp_cut=0.15,hp_trans=0.1, bmin=-0.1, auto_bad=20., plot_raw=False) # bem_type = '5120-5120-5120') params.subjects = [s] params.sss_type = 'python' params.sss_regularize = 'in' # 'in' by default params.tsss_dur = 8. # 60 for adults with not much head movements. This was set to 6. params.st_correlation = 0.9 params.auto_bad_meg_thresh = 10 # THIS SHOULD NOT BE SO HIGH! params.trans_to = None #'median' params.t_adjust = -39e-3 # time delay from the trigger. It's due to set trigger function. I don't know why... #print("Running " + str(len(params.subjects)) + ' Subjects') # print("\n\n".join(params.subjects)) print("\n\n") print("Running " + str(params.subjects)) print("\n\n") params.subject_indices = np.arange(0,len(params.subjects)) params.structurals =[None] * len(params.subjects) if s == '187_nb161205': params.run_names = ['%s_1', '%s_2', '%s_3', '%s_5','%s_6'] elif s == '172_th160825': params.run_names = ['%s_1', '%s_2', '%s_3', '%s_4', '%s_5'] else: params.run_names = ['%s_1', '%s_2', '%s_3', '%s_4', '%s_5', '%s_6'] #params.subject_run_indices = np.array([ # np.arange(0,ind[0]),np.arange(0,ind[1]),np.arange(0,ind[2]),np.arange(0,ind[3]), # np.arange(0,ind[4]),np.arange(0,ind[5]),np.arange(0,ind[6]),np.arange(0,ind[7]), # np.arange(0,ind[8]),np.arange(0,ind[9])#,np.arange(0,ind[11]) ## np.arange(0,ind[12]),np.arange(0,ind[13]),np.arange(0,ind[14]),np.arange(0,ind[15]), ## np.arange(0,ind[16]),np.arange(0,ind[17]),np.arange(0,ind[18]),np.arange(0,ind[19]), ## np.arange(0,ind[20]),np.arange(0,ind[21]),np.arange(0,ind[22]),np.arange(0,ind[23]), ## np.arange(0,ind[24]) #]) params.dates = [(2014, 0, 00)] * len(params.subjects) #params.subject_indices = [0] params.score = score # scoring function to use params.plot_drop_logs = False params.on_missing = 'warning' #params.acq_ssh = 'kambiz@minea.ilabs.uw.edu' # minea - 172.28.161.8 #params.acq_dir = '/sinuhe/data03/jason_words' # params.acq_ssh = 'jason@minea.ilabs.uw.edu' # minea - 172.28.161.8 # params.acq_dir = '/sinuhe/data03/jason_words' params.sws_ssh = 'jason@kasga.ilabs.uw.edu' # kasga - 172.28.161.8 params.sws_dir = '/data05/jason/NLR' #params.mf_args = '-hpie 30 -hpig .8 -hpicons' # sjjoo-20160826: We are doing SSS using python # epoch if s == '174_hs160620': params.reject = dict(grad=3000e-13, mag=4.0e-12) else: params.reject = dict(grad=3000e-13, mag=4.0e-12) # params.reject = dict(grad=4000e-13, mag=4.0e-12) params.ssp_eog_reject = dict(grad=params.reject['grad'], mag=params.reject['mag'], eog=np.inf) params.ssp_ecg_reject = dict(grad=params.reject['grad'], mag=params.reject['mag'], ecg=np.inf) params.flat = dict(grad=1e-13, mag=1e-15) params.auto_bad_reject = dict(grad=2*params.reject['grad'], mag=2*params.reject['mag']) params.auto_bad_flat = params.flat params.cov_method = 'shrunk' params.get_projs_from = range(len(params.run_names)) params.inv_names = ['%s'] params.inv_runs = [range(0, len(params.run_names))] params.runs_empty = [] params.proj_nums = [[0, 0, 0], # ECG: grad/mag/eeg [1, 1, 0], # EOG # sjjoo-20160826: was 3 [0, 0, 0]] # Continuous (from ERM) # The scoring function needs to produce an event file with these values params.in_names = ['word_c254_p20_dot', 'word_c254_p50_dot', 'word_c137_p20_dot', 'word_c254_p80_dot', 'word_c137_p80_dot', 'bigram_c254_p20_dot', 'bigram_c254_p50_dot', 'bigram_c137_p20_dot', 'word_c254_p20_word', 'word_c254_p50_word', 'word_c137_p20_word', 'word_c254_p80_word', 'word_c137_p80_word', 'bigram_c254_p20_word', 'bigram_c254_p50_word', 'bigram_c137_p20_word'] params.in_numbers = [101, 102, 103, 104, 105, 106, 107, 108, 201, 202, 203, 204, 205, 206, 207, 208] # These lines define how to translate the above event types into evoked files params.analyses = [ 'All', 'Conditions' ] params.out_names = [ ['ALL'], ['word_c254_p20_dot', 'word_c254_p50_dot', 'word_c137_p20_dot', 'word_c254_p80_dot', 'word_c137_p80_dot', 'bigram_c254_p20_dot', 'bigram_c254_p50_dot', 'bigram_c137_p20_dot', 'word_c254_p20_word', 'word_c254_p50_word', 'word_c137_p20_word', 'word_c254_p80_word', 'word_c137_p80_word', 'bigram_c254_p20_word', 'bigram_c254_p50_word', 'bigram_c137_p20_word'] ] params.out_numbers = [ [1] * len(params.in_numbers), [101, 102, 103, 104, 105, 106, 107, 108, 201, 202, 203, 204, 205, 206, 207, 208] ] params.must_match = [ [], [], ] # Set what will run mnefun.do_processing( params, fetch_raw=False, # Fetch raw recording files from acquisition machine do_score=False, # Do scoring to slice data into trials # Before running SSS, make SUBJ/raw_fif/SUBJ_prebad.txt file with # space-separated list of bad MEG channel numbers push_raw=False, # Push raw files and SSS script to SSS workstation do_sss=False, # Run SSS remotely (on sws) or locally with mne-python fetch_sss=False, # Fetch SSSed files from SSS workstation do_ch_fix=False, # Fix channel ordering # Before running SSP, examine SSS'ed files and make # SUBJ/bads/bad_ch_SUBJ_post-sss.txt; usually, this should only contain EEG # channels. gen_ssp=True, # Generate SSP vectors apply_ssp=True, # Apply SSP vectors and filtering plot_psd=False, # Plot raw data power spectra write_epochs=True, # Write epochs to disk gen_covs=True, # Generate covariances # Make SUBJ/trans/SUBJ-trans.fif using mne_analyze; needed for fwd calc. gen_fwd=False, # Generate forward solutions (and src space if needed) gen_inv=False, # Generate inverses gen_report=False, # Write mne report html of results to disk print_status=False, # Print completeness status update # params, # fetch_raw=False, # do_score=True, # True # push_raw=False, # do_sss=True, # True # fetch_sss=False, # do_ch_fix=True, # True # gen_ssp=True, # True # apply_ssp=True, # True # write_epochs=True, # True # plot_psd=False, # gen_covs=False, # gen_fwd=False, # gen_inv=False, # print_status=False, # gen_report=True # true ) print('%i sec' % (time.time() - t0))
For every time in the last two years you wondered who in the hell was going to save us from this godawful mess. You are. The time is now. Vote.
# This program averages a variable for each value of r for each files specified by the user # This program must be launched from the main folder of a case from which you can access ./CFD/ and ./voidfraction/ # A FOLDER ./voidfraction/averaged must exist! # Author : Bruno Blais # Last modified : 15-01-2014 #Python imports #---------------- import os import sys import numpy import math import matplotlib.pyplot as plt #---------------- #******************************** # OPTIONS AND USER PARAMETERS #******************************** #Initial time of simulation, final time and time increment must be specified by user t0=2.0 tf=100. dT=0.5 #Number of x and y cell must be specified nz=1 nr = 10 #====================== # MAIN #====================== # Directory to work within os.chdir("./voidFraction") # go to directory nt=int((tf-t0)/dT) t=t0 for i in range(0,nt): #Current case print "Radially averaging time ", t fname='voidfraction_' + str(t) x,y,z,phi = numpy.loadtxt(fname, unpack=True) #Pre-allocate phiAvg=numpy.zeros([4*nr*nr]) r = numpy.zeros([4*nr*nr]) lr = numpy.zeros([nr]) # list of possible radiuses phiR = numpy.zeros([nr]) # radially averaged variable #Calculate radiuses r = numpy.sqrt(x*x + y * y) #Establish list of possible radiuses nlr = 0 # counter on how many radiuses were found for j in range (0,len(r)): cr = r[j] # current radius present = 0; for k in range(0,nlr): if (numpy.abs(cr - lr[k]) < 1e-5): present =1 phiR[k] += phi[j] if (present == 0): lr[nlr] = cr nlr +=1 #Do the final average for j in range (0,nr): phiR[j] = phiR[j] / (4*nr) #Create output file back in the averaged folder outname='./averaged/radialVoidFraction_' + str(t) outfile=open(outname,'w') for i in range(0,nr): outfile.write("%5.5e %5.5e\n" %(lr[i],phiR[i])) outfile.close() t = t+dT #Go back to main dir os.chdir("..") print "Post-processing over"
What is Backflow, does it effect my business in Balcatta? Backflow occurs when the water pressure of your home or business property plumbing drops below the pressure at the mains. This causes the water in your supply pipes to flow in the wrong direction. As a result the water is flowing back into the water supply pipes, which can mix pollutants with the fresh water. Once water has been contaminated in your Balcatta property it can cause serious sickness or death. Backflow issues can effect any business or property in Balcatta. There are a variety of causes for backflow to occur such as a burst or ruptured water main, an excessive demand during a fire-fighting operation, a cross connected bore pump system with the internal water plumbing system. The fully qualified plumbers at Universal Plumbers are able to test and repair all backflow prevention devices for your Balcatta property. Our experienced plumbers can provide a risk assessment for the potential for backflow on the property. After this we will be able to provide an estimate on what is required to ensure that you have safe, fresh and clean water and avoid contamination from backflow. By identifying the backflow risk rating at your property Universal plumber’s are able to determine the best type of backflow prevention device or system for your Balcatta property. While testing the backflow prevention system in Balcatta the water will be required to be turned off. Our plumbers will work with you to determine the best time to reduce any inconvenience and ensure that the water is turned off for the shortest time possible. If you would like to find out more about backflow or would like to book in our backflow prevention and testing service in Balcatta contact us on 0412 919 777 or fill out our enquiry form here. So again if f you would like to get a quote for your backflow testing in Balcatta, then contact us on 0412 919 777 or fill out our enquiry form here.
# coding=utf-8 # Author: CristianBB # # URL: https://sickrage.ca # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickRage is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function, unicode_literals import re import sickrage from sickrage.core.caches.tv_cache import TVCache from sickrage.core.helpers import bs4_parser, try_int from sickrage.providers import TorrentProvider class EliteTorrentProvider(TorrentProvider): def __init__(self): super(EliteTorrentProvider, self).__init__('EliteTorrent', 'https://www.elitetorrent.eu', False) self.urls.update({ 'search': '{base_url}/torrents.php'.format(**self.urls) }) self.onlyspasearch = None self.minseed = None self.minleech = None self.cache = TVCache(self) def search(self, search_strings, age=0, ep_obj=None): results = [] lang_info = '' if not ep_obj or not ep_obj.show else ep_obj.show.lang """ Search query: http://www.elitetorrent.net/torrents.php?cat=4&modo=listado&orden=fecha&pag=1&buscar=fringe cat = 4 => Shows modo = listado => display results mode orden = fecha => order buscar => Search show pag = 1 => page number """ search_params = { 'cat': 4, 'modo': 'listado', 'orden': 'fecha', 'pag': 1, 'buscar': '' } for mode in search_strings: sickrage.app.log.debug("Search Mode: {}".format(mode)) # Only search if user conditions are true if self.onlyspasearch and lang_info != 'es' and mode != 'RSS': sickrage.app.log.debug("Show info is not spanish, skipping provider search") continue for search_string in search_strings[mode]: if mode != 'RSS': sickrage.app.log.debug("Search string: {0}".format(search_string)) search_string = re.sub(r'S0*(\d*)E(\d*)', r'\1x\2', search_string) search_params['buscar'] = search_string.strip() if mode != 'RSS' else '' try: data = sickrage.app.wsession.get(self.urls['search'], params=search_params).text results += self.parse(data, mode) except Exception: sickrage.app.log.debug("No data returned from provider") return results def parse(self, data, mode): """ Parse search results from data :param data: response data :param mode: search mode :return: search results """ results = [] def _process_title(title): title = title.encode('latin-1').decode('utf8') # Quality, if no literal is defined it's HDTV if 'calidad' not in title: title += ' HDTV x264' title = title.replace('(calidad baja)', 'HDTV x264') title = title.replace('(Buena calidad)', '720p HDTV x264') title = title.replace('(Alta calidad)', '720p HDTV x264') title = title.replace('(calidad regular)', 'DVDrip x264') title = title.replace('(calidad media)', 'DVDrip x264') # Language, all results from this provider have spanish audio, we append it to title (avoid to download undesired torrents) title += ' SPANISH AUDIO' title += '-ELITETORRENT' return title.strip() with bs4_parser(data) as html: torrent_table = html.find('table', class_='fichas-listado') torrent_rows = torrent_table('tr') if torrent_table else [] if len(torrent_rows) < 2: sickrage.app.log.debug("Data returned from provider does not contain any torrents") return results for row in torrent_rows[1:]: try: title = _process_title(row.find('a', class_='nombre')['title']) download_url = self.urls['base_url'] + row.find('a')['href'] if not all([title, download_url]): continue seeders = try_int(row.find('td', class_='semillas').get_text(strip=True)) leechers = try_int(row.find('td', class_='clientes').get_text(strip=True)) # seeders are not well reported. Set 1 in case of 0 seeders = max(1, seeders) # Provider does not provide size size = -1 item = {'title': title, 'link': download_url, 'size': size, 'seeders': seeders, 'leechers': leechers, 'hash': ''} if mode != 'RSS': sickrage.app.log.debug("Found result: {}".format(title)) results.append(item) except Exception: sickrage.app.log.error("Failed parsing provider") return results
Shouldn't your writer be experienced in the legal industry and certified in content marketing? With my background, education, and experience, I am the ideal copywriter for legal vendors. Get insightful content from a writer who knows the ins and outs of working in law firms, large and small. I started working in law firms back when Word Perfect and fax machines were the height of legal tech. Trust that I know how your audience feels. I've experienced firsthand the growing pains law firms leaders and staff feel when integrating new processes and technologies into existing workflows. I understand their concerns about change. My go-to writing style is relaxed and conversational - though always highly professional. The idea is to explain technical concepts in straightforward, concise terms, always appreciating that our audience is smart, discerning, and above all BUSY. The effects of the digital transformation and how they drive tomorrow's needs. How various technologies (AI, automation, data analytics, etc.) help legal professionals meet those needs and improve their businesses. The pain points and concerns of in-house counsel, law firm leaders, CTOs, CFOs, procurement officials, and so on. While I've learned the old-school methods for creating persuasive copy, I also stay well-informed on the latest marketing concepts and trends. I always seek new ways to create better content and promote it more effectively. Because of my professional background in both journalism and the legal field, I know where to find authoritative sources and how to work supporting stats and quotes into content so it packs the most punch. I'm well aware of the delicate intricacies involving word choice and language usage when communicating with legal professionals. And I'm always eager to help companies like yours use the best words better and build success through engaging copy and content. 1 Contact me to discuss your needs and how I can help. We'll develop a client-centric approach to help you better engage your target audience. 2We'll discuss the proper content formats for your needs, which topics to write about, and the distribution platforms your audience prefers. 3You decide how little or how much you want to be involved in drafting and editing copy. I ensure your unique voice is heard in everything we create. Still curious? Read a step-by-step description of what it's like working with me.
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-17 18:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('book_pk', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, unique=True)), ('index', models.FileField(blank=True, null=True, upload_to=b'model_filefields_example.BookIndex/bytes/filename/mimetype')), ('pages', models.FileField(blank=True, null=True, upload_to=b'model_filefields_example.BookPages/bytes/filename/mimetype')), ('cover', models.ImageField(blank=True, null=True, upload_to=b'model_filefields_example.BookCover/bytes/filename/mimetype')), ], ), migrations.CreateModel( name='BookCover', fields=[ ('book_cover_pk', models.AutoField(primary_key=True, serialize=False)), ('bytes', models.TextField()), ('filename', models.CharField(max_length=255)), ('mimetype', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='BookIndex', fields=[ ('book_index_pk', models.AutoField(primary_key=True, serialize=False)), ('bytes', models.TextField()), ('filename', models.CharField(max_length=255)), ('mimetype', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='BookPages', fields=[ ('book_pages_pk', models.AutoField(primary_key=True, serialize=False)), ('bytes', models.TextField()), ('filename', models.CharField(max_length=255)), ('mimetype', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='SoundDevice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('instruction_manual', models.FileField(blank=True, null=True, upload_to=b'model_filefields_example.SoundDeviceInstructionManual/bytes/filename/mimetype')), ], ), migrations.CreateModel( name='SoundDeviceInstructionManual', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('bytes', models.TextField()), ('filename', models.CharField(max_length=255)), ('mimetype', models.CharField(max_length=50)), ], ), ]
we are a 501(c) (3) non-profit and can accept donations to help the company with its mission. Donations are a tax write-off. ​Use our EIN 81-1260535. We also accept checks that can be mailed to 406 Main Street, Suite D, Vacaville, CA 95688.
""" MIDI input controls """ import weakref from PyQt5.QtCore import QSettings, Qt from PyQt5.QtWidgets import (QCheckBox, QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QRadioButton, QToolButton, QVBoxLayout, QWidget) import app import midiinput class Widget(QWidget): def __init__(self, dockwidget): super(Widget, self).__init__(dockwidget) self._document = None self._midiin = midiinput.MidiIn(self) self._dockwidget = weakref.ref(dockwidget) signals = list() self._labelmidichannel = QLabel() self._midichannel = QComboBox() signals.append(self._midichannel.currentIndexChanged) self._labelkeysignature = QLabel() self._keysignature = QComboBox() signals.append(self._keysignature.currentIndexChanged) self._labelaccidentals = QLabel() self._accidentalssharps = QRadioButton() signals.append(self._accidentalssharps.clicked) self._accidentalsflats = QRadioButton() signals.append(self._accidentalsflats.clicked) self._groupaccidentals = QGroupBox() self._groupaccidentals.setFlat(True) hbox = QHBoxLayout() self._groupaccidentals.setLayout(hbox) hbox.addWidget(self._accidentalssharps) hbox.addWidget(self._accidentalsflats) self._accidentalssharps.setChecked(True) self._chordmode = QCheckBox() signals.append(self._chordmode.clicked) self._relativemode = QCheckBox() signals.append(self._relativemode.clicked) self._labeldamper = QLabel() self._damper = QComboBox() self._labelsostenuto = QLabel() self._sostenuto = QComboBox() self._labelsoft = QLabel() self._soft = QComboBox() ac = self.parentWidget().actionCollection self._capture = QToolButton() self._capture.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._capture.setDefaultAction(ac.capture_start) self.addAction(ac.accidental_switch) self._notemode = QLabel() layout = QVBoxLayout() self.setLayout(layout) grid = QGridLayout(spacing=0) layout.addLayout(grid) layout.addStretch() grid.addWidget(self._labelmidichannel, 0, 0) grid.addWidget(self._midichannel, 0, 1) grid.addWidget(self._labelkeysignature, 1, 0) grid.addWidget(self._keysignature, 1, 1) grid.addWidget(self._labelaccidentals, 2, 0) grid.addWidget(self._groupaccidentals, 2, 1) grid.addWidget(self._chordmode, 3, 0) grid.addWidget(self._relativemode, 3, 1) grid.addWidget(self._labeldamper, 4, 0) grid.addWidget(self._damper, 4, 1) grid.addWidget(self._labelsostenuto, 5, 0) grid.addWidget(self._sostenuto, 5, 1) grid.addWidget(self._labelsoft, 6, 0) grid.addWidget(self._soft, 6, 1) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._capture) hbox.addStretch() app.translateUI(self) self.loadsettings() for s in signals: s.connect(self.savesettings) def mainwindow(self): return self._dockwidget().mainwindow() def channel(self): return self._midichannel.currentIndex() def keysignature(self): return self._keysignature.currentIndex() def accidentals(self): if self._accidentalsflats.isChecked(): return 'flats' else: return 'sharps' def chordmode(self): return self._chordmode.isChecked() def relativemode(self): return self._relativemode.isChecked() def startcapturing(self): self._midiin.capture() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_stop) def stopcapturing(self): self._midiin.capturestop() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_start) def switchaccidental(self): if self.accidentals() == 'flats': self._accidentalssharps.setChecked(True) else: self._accidentalsflats.setChecked(True) def savesettings(self): s = QSettings() s.beginGroup("midiinputdock") s.setValue("midichannel", self._midichannel.currentIndex()) s.setValue("keysignature", self._keysignature.currentIndex()) if self._accidentalsflats.isChecked(): s.setValue("accidentals", 'flats') else: s.setValue("accidentals", 'sharps') s.setValue("chordmode", self._chordmode.isChecked()) s.setValue("relativemode", self._relativemode.isChecked()) def loadsettings(self): s = QSettings() s.beginGroup("midiinputdock") self._midichannel.setCurrentIndex(s.value("midichannel", 0, int)) self._keysignature.setCurrentIndex(s.value("keysignature", 7, int)) if s.value("accidentals", 'sharps', str) == 'flats': self._accidentalsflats.setChecked(True) else: self._accidentalssharps.setChecked(True) self._chordmode.setChecked(s.value("chordmode", False, bool)) self._relativemode.setChecked(s.value("relativemode", False, bool)) def translateUI(self): self._labelmidichannel.setText(_("MIDI channel")) self._midichannel.addItems([_("all")]+[str(i) for i in range(1,17)]) self._labelkeysignature.setText(_("Key signature")) self._keysignature.addItems([ _("C flat major (7 flats)"), _("G flat major (6 flats)"), _("D flat major (5 flats)"), _("A flat major (4 flats)"), _("E flat major (3 flats)"), _("B flat major (2 flats)"), _("F major (1 flat)"), _("C major"), _("G major (1 sharp)"), _("D major (2 sharps)"), _("A major (3 sharps)"), _("E major (4 sharps)"), _("B major (5 sharps)"), _("F sharp major (6 sharps)"), _("C sharp major (7 sharps)") ]) self._keysignature.setCurrentIndex(7) self._labelaccidentals.setText(_("Accidentals")) self._accidentalssharps.setText(_("sharps")) self._accidentalsflats.setText(_("flats")) self._chordmode.setText(_("Chord mode")) self._chordmode.setToolTip(_( "Enter simultaneously played notes as chords. " "See \"What's This\" for more information.")) self._chordmode.setWhatsThis(_( "Notes which are played simultaneously are written " "as chords. As a consequence they are not written " "before the last key is lifted. Of course single " "can also be entered.")) self._relativemode.setText(_("Relative mode")) self._relativemode.setToolTip(_( "Enter octaves of notes relative to the last note. " "See \"What's This\" for more information.")) self._relativemode.setWhatsThis(_( "Enter octaves of notes relative to the last note. " "This refers to the last key pressed on the MIDI keyboard, not the last note in the document." "Hold Shift with a note to enter an octave check.")) self._labeldamper.setText(_("Damper pedal")) self._labelsostenuto.setText(_("Sostenuto pedal")) self._labelsoft.setText(_("Soft pedal"))
The Navy's Mobile Diving and Salvage Unit 2 has taken over recovery operations for a Marine Corps AV-8B Harrier that crashed off the coast of Wilmington, North Carolina, nearly two weeks ago. A team of 20 workers will try to salvage the aircraft, said 1st Lt. Maida Zheng, a spokesman for 2nd Marine Aircraft Wing. The Harrier, with Marine Attack Squadron 54, Marine Aircraft Group 14, out of Cherry Point, North Carolina, went down just after 5 p.m. on May 6. While officials have not formally identified the cause of the crash, a Naval Safety Center report says the Harrier "lost thrust" prior to going down. The pilot, who has not been identified, was able to eject from the aircraft and inflate a personal inflation device he was wearing in flight. He also inflated a life raft which held him until he was picked up in a rescue by an H-60 Seahawk, Zheng said. The pilot was transported to Naval Hospital Camp Lejeune, North Carolina in stable condition and released May 7. Zheng said divers have so far conducted a preliminary survey of the crash site and found no fuel or fluid leaks. The Harrier wasn't carrying any weapons when it went down, Zheng said. The squadron has requested that the entire aircraft, which cost roughly $24 million new, be recovered. It's not clear how long salvage efforts will take. Now three different investigations into the crash are ongoing, Zheng said: an aircraft mishap board investigation, a JAGMAN command investigation, and a Field Flight Performance Board investigation. The crash did not prompt a safety stand-down at the squadron, however. "The Harrier Fleet has not been grounded, there currently is no evidence from this mishap to indicate there is a systemic problem with the fleet's AV-8B aircraft," Zheng told Military.com. "If, during the mishap investigation, such a problem were to be discovered, the Marine Corps would take appropriate steps to address the issue with any fleet aircraft considered at risk." The Harrier pilot had departed Wilmington International Airport to conduct flight training the night of the crash and had intended to return to the airport, officials said. He was rescued by Navy responders with Naval Station Norfolk, Virginia, who were operating from the amphibious assault ship USS Wasp in support of Camp Lejeune's 22nd Marine Expeditionary Unit. The Harrier has been used by the Marine Corps since 1985, and is set to be replaced in the coming decade by the F-35B Joint Strike Fighter.
__author__ = 'Aaron J. Masino' import numpy as np def extractBy(condition, data, tol = 1e-6): not_condition = condition[:]==False return (data[condition], data[not_condition]) def partion(condition, data, ratios=[.6,.2,.2]): ''' returns two lists (l1,l2). l1 is a list of numpy arrays where each array contains indices into the data where the condition is True and l2 is a list of numpy arrays where each array contains indicies into the data where the condition is False. The len(l1)=len(l2)=len(ratios) and the lists in l1 and l2 have lengths determined by the ratio values.''' pos = np.where(condition)[0] neg = np.where(condition[:]==False)[0] #SHOULD ALSO USE np.where(condition) to split data #NEED TO MODIFY TO RETURN MASKS ONLY #MASK SHOULD BE AN 1D NUMPY ARRAY #if not (np.sum(ratios) == 1 or np.sum(ratios) == 1.0): raise Exception('Ratios must sum to 1, got {0}'.format(np.sum(ratios))) #(pos, neg) = extractBy(condition, data) pos_row_count = pos.shape[0] neg_row_count = neg.shape[0] s1 = 0 s2 = 0 s3 = 0 s4 = 0 pdata = [] ndata = [] for i in range(len(ratios)): r = ratios[i] if i==len(ratios)-1: s2 = pos_row_count s4 = neg_row_count else: s2 = min(s1 + int(round(r*pos_row_count)), pos_row_count) s4 = min(s3 + int(round(r*neg_row_count)), neg_row_count) if s2<=s1: raise Exception('Insufficient positive data for partition, s1={0}, s2={1}'.format(s1,s2)) if s4<=s3: raise Exception('Insufficient negative data for partition, s3={0}, s4={1}'.format(s3,s4)) pdata.append(pos[s1:s2]) ndata.append(neg[s3:s4]) s1 = s2 s3 = s4 return(pdata,ndata)
A study has found that lower zinc levels in your body can be the reason behind high blood pressure levels. Lower-than-normal levels of zinc — a nutrient that helps the immune system fight off invading bacteria and viruses — may contribute to hypertension, finds a new study on mice. The study, from the Wright State University in the US, demonstrated that the way in which the kidneys either excrete sodium into the urine or reabsorb it into the body — specifically through a pathway called the sodium chloride cotransporter (NCC) — also plays a role in controlling high blood pressure. The results, published in the American Journal of Physiology — Renal Physiology, showed that zinc-deficient mice developed high blood pressure and a corresponding decrease in urinary sodium excretion. A small group of the zinc-deficient mice were fed a zinc-rich diet partway. Once the animals’ zinc reached adequate levels, blood pressure began to drop and urinary sodium levels increased. “These significant findings demonstrate that enhanced renal (sodium) re-absorption plays a critical role in (zinc-deficiency)-induced hypertension,” said Clintoria R. Williams, a researcher from the varsity.
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-11-19 19:38 from __future__ import unicode_literals import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('users', '0001_initial'), ('companies', '0001_initial'), ] operations = [ migrations.CreateModel( name='Employee', fields=[ ('admin_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='users.Admin')), ('employer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='employer', to='companies.Company')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, bases=('users.admin',), managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Team', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=250, unique=True)), ], ), migrations.AddField( model_name='employee', name='team', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Team'), ), migrations.AddField( model_name='company', name='editors', field=models.ManyToManyField(related_name='editors', to='users.Admin'), ), migrations.AddField( model_name='company', name='owner', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.Admin'), ), ]
Their living nightmare came to an end when their captor was stopped in a traffic control. He had brought the youngest child with him, and a police officer, who found the shabbily dressed child looking sick, demanded to see the child’s mother. The monster was then forced to take the police to the cabin, and the tragedy was revealed. In this case the policeman’s attitude made the difference. His alertness and interest in the child’s wellbeing led to the rescue of the victims. Sadly there are monsters among us, and there are at any given time numerous captive women and children who are suffering under horrible conditions. Trafficking is a global curse, particularly in poor countries. India, where I spend time, is one such example. Thousands of children and young women disappear every year. While the women may be locked up in brothels, many of the children are out on the street, dressed in filthy clothes, begging at traffic junctions in the big cities, being treated like little slaves. My wife once gave a sweater to a little girl who was begging at a junction in Delhi a cold autumn night. The girl immediately put in on, but when my wife passed through the same junction an hour later, the sweater was gone. Obviously her ‘owners’ had taken it. Some of the street children are living with their parents in abject poverty, and the whole family may have to beg to survive, but others are surely victims of trafficking. There are some NGOs trying to help street children in need, but they face an overwhelming task. What if the police had routinely checked up on the street children’s keepers? I dream of a world where authorities and the police show genuine care for needy children, like the Italian policeman. If so, at least one part of the kidnapping/trafficking curse would be addressed.
import os import IMP import IMP.em import IMP.test import IMP.core class Tests(IMP.test.TestCase): """Class to test EM correlation restraint""" def test_origin_spacing_data_is_kept_in_mrc_format1(self): scene = IMP.em.read_map(self.get_input_file_name("in.mrc"), self.mrw) scene.set_origin(-100, -100, -100) IMP.em.write_map(scene, "test1.mrc", self.mrw) scene2 = IMP.em.read_map("test1.mrc", self.mrw) os.unlink("test1.mrc") origin2 = scene2.get_origin() self.assertEqual(-100, origin2[0]) self.assertEqual(-100, origin2[1]) self.assertEqual(-100, origin2[2]) self.assertEqual(1, scene2.get_spacing()) def test_origin_spacing_data_is_kept_in_mrc_format2(self): mrw = IMP.em.MRCReaderWriter() scene = IMP.em.read_map(self.get_input_file_name("in.mrc"), self.mrw) scene.set_origin(-100, -100, -100) scene.update_voxel_size(10) self.assertEqual(10, scene.get_spacing()) IMP.em.write_map(scene, "test2.mrc", self.mrw) scene2 = IMP.em.read_map("test2.mrc", self.mrw) os.unlink("test2.mrc") origin2 = scene2.get_origin() self.assertEqual(-100, origin2[0]) self.assertEqual(-100, origin2[1]) self.assertEqual(-100, origin2[2]) self.assertEqual(10, scene2.get_spacing()) def test_origin_spacing_data_is_kept_in_mrc_format3(self): mrw = IMP.em.MRCReaderWriter() scene = IMP.em.read_map(self.get_input_file_name("in.mrc"), self.mrw) scene.update_voxel_size(10) scene.set_origin(-100, -100, -100) self.assertEqual(10, scene.get_spacing()) scene.get_header().show() IMP.em.write_map(scene, "test3.mrc", self.mrw) scene2 = IMP.em.read_map("test3.mrc", self.mrw) os.unlink("test3.mrc") origin2 = scene2.get_origin() self.assertEqual(-100, origin2[0]) self.assertEqual(-100, origin2[1]) self.assertEqual(-100, origin2[2]) self.assertEqual(10, scene2.get_spacing()) def test_origin_spacing_data_is_kept_in_mrc_format4(self): mrw = IMP.em.MRCReaderWriter() scene = IMP.em.read_map(self.get_input_file_name("in.mrc"), self.mrw) scene.update_voxel_size(10) self.assertEqual(10, scene.get_spacing()) scene.get_header().show() IMP.em.write_map(scene, "test4.mrc", self.mrw) scene2 = IMP.em.read_map("test4.mrc", self.mrw) os.unlink("test4.mrc") origin2 = scene2.get_origin() self.assertEqual(10, scene2.get_spacing()) def setUp(self): """Build test model and optimizer""" IMP.test.TestCase.setUp(self) self.mrw = IMP.em.MRCReaderWriter() if __name__ == '__main__': IMP.test.main()
ProjectLibre is project management software, an alternative to Microsoft Project. It is also the new You can simply open them on Linux, Mac OS or Windows. Project Management software: alternative to Microsoft Project. and Mac please use ProjectLibre (restaurantegardoki.com,.zip,restaurantegardoki.com versions) Linux. Project Management software: alternative to Microsoft Project. ProjectLibre Cloud. Like Google Docs but replacing MS Project. GET YOUR FREE DAY TRIAL Soon! watch demo try it free. ×. ProjectLibre is compatible with Microsoft Project , and files. You can simply open them on Linux, Mac OS or Windows. ProjectLibre key features. That is why Alexandre Oliva started the GNU Linux-libre project, so that free software advocates can become aware of the problem and use a truly free kernel . The restaurantegardoki.com file is: restaurantegardoki.com ProjectLibre/ You can install ProjectLibre automatically with these commands ( the URL. ProjectLibre is a free and open-source project management software system intended Currently, ProjectLibre is certified to run on Linux, MacOS and MS Windows. It is released under the Common Public Attribution License (CPAL) and. GNU Linux-libre is a project to maintain and publish % Free distributions of Linux, suitable for use in Free System Distributions, removing software that is. It intends to be a complete desktop replacement for Microsoft Project. ProjectLibre runs on the Java Platform, allowing it to run on the Linux.
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2013 Riverbank Computing Limited. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file under the terms of the BSD license as follows: ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ## the names of its contributors may be used to endorse or promote ## products derived from this software without specific prior written ## permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## $QT_END_LICENSE$ ## ############################################################################# from PyQt5.QtCore import (QAbstractTransition, QEasingCurve, QEvent, QParallelAnimationGroup, QPropertyAnimation, qrand, QRect, QSequentialAnimationGroup, qsrand, QState, QStateMachine, Qt, QTime, QTimer) from PyQt5.QtWidgets import (QApplication, QGraphicsScene, QGraphicsView, QGraphicsWidget) class StateSwitchEvent(QEvent): StateSwitchType = QEvent.User + 256 def __init__(self, rand=0): super(StateSwitchEvent, self).__init__(StateSwitchEvent.StateSwitchType) self.m_rand = rand def rand(self): return self.m_rand class QGraphicsRectWidget(QGraphicsWidget): def paint(self, painter, option, widget): painter.fillRect(self.rect(), Qt.blue) class StateSwitchTransition(QAbstractTransition): def __init__(self, rand): super(StateSwitchTransition, self).__init__() self.m_rand = rand def eventTest(self, event): return (event.type() == StateSwitchEvent.StateSwitchType and event.rand() == self.m_rand) def onTransition(self, event): pass class StateSwitcher(QState): def __init__(self, machine): super(StateSwitcher, self).__init__(machine) self.m_stateCount = 0 self.m_lastIndex = 0 def onEntry(self, event): n = qrand() % self.m_stateCount + 1 while n == self.m_lastIndex: n = qrand() % self.m_stateCount + 1 self.m_lastIndex = n self.machine().postEvent(StateSwitchEvent(n)) def onExit(self, event): pass def addState(self, state, animation): self.m_stateCount += 1 trans = StateSwitchTransition(self.m_stateCount) trans.setTargetState(state) self.addTransition(trans) trans.addAnimation(animation) def createGeometryState(w1, rect1, w2, rect2, w3, rect3, w4, rect4, parent): result = QState(parent) result.assignProperty(w1, 'geometry', rect1) result.assignProperty(w1, 'geometry', rect1) result.assignProperty(w2, 'geometry', rect2) result.assignProperty(w3, 'geometry', rect3) result.assignProperty(w4, 'geometry', rect4) return result if __name__ == '__main__': import sys app = QApplication(sys.argv) button1 = QGraphicsRectWidget() button2 = QGraphicsRectWidget() button3 = QGraphicsRectWidget() button4 = QGraphicsRectWidget() button2.setZValue(1) button3.setZValue(2) button4.setZValue(3) scene = QGraphicsScene(0, 0, 300, 300) scene.setBackgroundBrush(Qt.black) scene.addItem(button1) scene.addItem(button2) scene.addItem(button3) scene.addItem(button4) window = QGraphicsView(scene) window.setFrameStyle(0) window.setAlignment(Qt.AlignLeft | Qt.AlignTop) window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) machine = QStateMachine() group = QState() timer = QTimer() timer.setInterval(1250) timer.setSingleShot(True) group.entered.connect(timer.start) state1 = createGeometryState(button1, QRect(100, 0, 50, 50), button2, QRect(150, 0, 50, 50), button3, QRect(200, 0, 50, 50), button4, QRect(250, 0, 50, 50), group) state2 = createGeometryState(button1, QRect(250, 100, 50, 50), button2, QRect(250, 150, 50, 50), button3, QRect(250, 200, 50, 50), button4, QRect(250, 250, 50, 50), group) state3 = createGeometryState(button1, QRect(150, 250, 50, 50), button2, QRect(100, 250, 50, 50), button3, QRect(50, 250, 50, 50), button4, QRect(0, 250, 50, 50), group) state4 = createGeometryState(button1, QRect(0, 150, 50, 50), button2, QRect(0, 100, 50, 50), button3, QRect(0, 50, 50, 50), button4, QRect(0, 0, 50, 50), group) state5 = createGeometryState(button1, QRect(100, 100, 50, 50), button2, QRect(150, 100, 50, 50), button3, QRect(100, 150, 50, 50), button4, QRect(150, 150, 50, 50), group) state6 = createGeometryState(button1, QRect(50, 50, 50, 50), button2, QRect(200, 50, 50, 50), button3, QRect(50, 200, 50, 50), button4, QRect(200, 200, 50, 50), group) state7 = createGeometryState(button1, QRect(0, 0, 50, 50), button2, QRect(250, 0, 50, 50), button3, QRect(0, 250, 50, 50), button4, QRect(250, 250, 50, 50), group) group.setInitialState(state1) animationGroup = QParallelAnimationGroup() anim = QPropertyAnimation(button4, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) animationGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup) subGroup.addPause(100) anim = QPropertyAnimation(button3, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) subGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup) subGroup.addPause(150) anim = QPropertyAnimation(button2, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) subGroup.addAnimation(anim) subGroup = QSequentialAnimationGroup(animationGroup) subGroup.addPause(200) anim = QPropertyAnimation(button1, 'geometry') anim.setDuration(1000) anim.setEasingCurve(QEasingCurve.OutElastic) subGroup.addAnimation(anim) stateSwitcher = StateSwitcher(machine) group.addTransition(timer.timeout, stateSwitcher) stateSwitcher.addState(state1, animationGroup) stateSwitcher.addState(state2, animationGroup) stateSwitcher.addState(state3, animationGroup) stateSwitcher.addState(state4, animationGroup) stateSwitcher.addState(state5, animationGroup) stateSwitcher.addState(state6, animationGroup) stateSwitcher.addState(state7, animationGroup) machine.addState(group) machine.setInitialState(group) machine.start() window.resize(300, 300) window.show() qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime())) sys.exit(app.exec_())
Will the LA Galaxy be able to beat Chicago Fire during Galaxy Throwback Night this Saturday? Will the LA Galaxy finally be able to get a win and beat Chicago Fire this Saturday? This Saturday, the LA Galaxy will host their second Galaxy Throwback Night when they take on Chicago Fire at the Stubhub Center. The night will be complete with retro giveaways, trivia, confetti, videos, playlists, and giving fans insight into the Galaxy’s rich history. Additionally, the first 12,500 lucky fans to enter the stadium will get their very own limited edition Galaxy Throwback shirt. The night will be filled with nostalgia and fun: but will it also include a win for the LA Galaxy? This is the last of the LA Galaxy’s three home games in a row and they have yet to get a win or even make a goal. However, coach Curt Onalfo is making changes to try and rectify that. Last game he added an extra midfielder into the lineup, and although it did not help the Galaxy put the ball in the net, they did dominate possession. The game will take place at 7:30 this Saturday at Stubhub Center. Bastian Schweinsteiger has already scored 2 goals since joining Chicago Fire.
""" Salamander ALM Copyright (c) 2016 Djuro Drljaca This Python module is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This Python module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. """ import connection import json import requests import requests.packages import signal import subprocess import sys import time import unittest class UserManagement(unittest.TestCase): @classmethod def setUpClass(cls): requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning) def setUp(self): self.__admin_user_id = 1 self.__server_instance = subprocess.Popen([sys.executable, "../../server/salamander_alm.py"]) if self.__server_instance is not None: time.sleep(2.0) def tearDown(self): if self.__server_instance is not None: self.__server_instance.send_signal(signal.SIGINT) self.__server_instance.wait(1.0) if self.__server_instance.returncode is None: self.__server_instance.kill() # def create_user_test1(self, conn: connection.Connection) -> Optional[dict]: # """ # Creates a user # :param conn: # :return: # """ # user_id = UserManagementInterface.create_user("test1", # "Test 1", # "test1@test.com", # "basic", # {"password": "test123"}) # return user_id # Tests ---------------------------------------------------------------------------------------- def test_default_administrator_login(self): conn = connection.Connection() success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) def test_default_administrator_login_failure(self): conn = connection.Connection() success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "xyz"}) self.assertFalse(success) def test_default_administrator_logout(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then try to log out success = conn.logout() self.assertTrue(success) def test_default_administrator_logout_failure(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then try to log out success = conn.logout() self.assertTrue(success) def test_default_administrator_read_current_user(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then read the current user success = conn.call_get_method("/usermanagement/user") self.assertTrue(success) user = json.loads(conn.last_response_message.text) self.assertIsNotNone(user) self.assertEqual(user["id"], self.__admin_user_id) self.assertEqual(user["user_name"], "administrator") self.assertEqual(user["display_name"], "Administrator") self.assertEqual(user["email"], "") self.assertEqual(user["active"], True) def test_read_user_by_id(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then read the selected user success = conn.call_get_method("/usermanagement/user", parameters={"user_id": 1}) self.assertTrue(success) user = json.loads(conn.last_response_message.text) self.assertIsNotNone(user) self.assertEqual(user["id"], self.__admin_user_id) self.assertEqual(user["user_name"], "administrator") self.assertEqual(user["display_name"], "Administrator") self.assertEqual(user["email"], "") self.assertEqual(user["active"], True) def test_read_user_by_id_failure(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then try to read a non-existing user success = conn.call_get_method("/usermanagement/user", parameters={"user_id": 2}) self.assertFalse(success) def test_read_user_by_user_name(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then read the selected user success = conn.call_get_method("/usermanagement/user", parameters={"user_name": "administrator"}) self.assertTrue(success) user = json.loads(conn.last_response_message.text) self.assertIsNotNone(user) self.assertEqual(user["id"], self.__admin_user_id) self.assertEqual(user["user_name"], "administrator") self.assertEqual(user["display_name"], "Administrator") self.assertEqual(user["email"], "") self.assertEqual(user["active"], True) def test_read_user_by_user_name_failure(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then try to read a non-existing user success = conn.call_get_method("/usermanagement/user", parameters={"user_name": "xyz"}) self.assertFalse(success) def test_read_user_by_display_name(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then read the selected user success = conn.call_get_method("/usermanagement/user", parameters={"display_name": "Administrator"}) self.assertTrue(success) user = json.loads(conn.last_response_message.text) self.assertIsNotNone(user) self.assertEqual(user["id"], self.__admin_user_id) self.assertEqual(user["user_name"], "administrator") self.assertEqual(user["display_name"], "Administrator") self.assertEqual(user["email"], "") self.assertEqual(user["active"], True) def test_read_user_by_display_name_failure(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "administrator"}) self.assertTrue(success) # And then try to read a non-existing user success = conn.call_get_method("/usermanagement/user", parameters={"display_name": "xyz"}) self.assertFalse(success) if __name__ == '__main__': unittest.main()
Hughie Elbert Stover, former Security Chief at West Virginia’s Upper Big Branch (UBB) Coal Mine was sentenced to 3 years in prison, 2 years of probation, and $20,000 in fines. The Department of Justice mentions that during the April 2010 mine explosion at UBB, where 29 miners died, he was responsible for lying to investigators and getting rid of evidence of safety and health violations. According to charges, mine inspectors had issued citations with violations, but still allowed the mine to operate. In addition, they also issued orders which would lead to either the entire or part of the mine to stop its operations until the violations were corrected. Even though giving an advance notice of an MSHA inspection is against the law, Stover was charged with being responsible on just that from February 2008 to April of 2012. Other supervisors involved have also been charged due to involvement in this tragic event, including Gary May and Thomas Harrah.
# Name: wxlib.py # Purpose: Component plugins for wx.lib classes # Author: Roman Rolinsky <rolinsky@femagsoft.com> # Created: 05.09.2007 # RCS-ID: $Id$ import xh_wxlib from wx.tools.XRCed import component, params from wx.tools.XRCed.globals import TRACE from wx.lib.ticker_xrc import wxTickerXmlHandler TRACE('*** creating wx.lib components') # wx.lib.foldpanelbar.FoldPanelBar c = component.SmartContainer('wx.lib.foldpanelbar.FoldPanelBar', ['book', 'window', 'control'], ['pos', 'size'], implicit_klass='foldpanel', implicit_page='FoldPanel', implicit_attributes=['label', 'collapsed'], implicit_params={'collapsed': params.ParamBool}) c.addStyles('FPB_SINGLE_FOLD', 'FPB_COLLAPSE_TO_BOTTOM', 'FPB_EXCLUSIVE_FOLD', 'FPB_HORIZONTAL', 'FPB_VERTICAL') component.Manager.register(c) component.Manager.addXmlHandler(xh_wxlib.FoldPanelBarXmlHandler) component.Manager.setMenu(c, 'bar', 'fold panel bar', 'FoldPanelBar', 1000) # wx.lib.ticker.Ticker class ParamDirection(params.RadioBox): choices = {'right to left': 'rtl', 'left to right': 'ltr'} default = 'rtl' c = component.Component('wxTicker', ['control'], ['pos', 'size', 'start', 'text', 'ppf', 'fps', 'direction'], params={'ppf': params.ParamInt, 'fps': params.ParamInt, 'direction': ParamDirection}) component.Manager.register(c) component.Manager.addXmlHandler(wxTickerXmlHandler) component.Manager.setMenu(c, 'control', 'ticker', 'Ticker', 1000)
Mangore | Bellucci Guitars - Quarantotto/Sartori, "Time to Say Goodbye" Quarantotto/Sartori, "Time to Say Goodbye" I love "Time to Say Goodbye" wholeheartedly and I have heard it performed by singers throughout Paraguay and it is irresistible to me. I transcribed it and fingered it because I consider it a great addition to my students' repertoire -and mine of course-. It fits the classical guitar beautifully and offers beautiful challenges that you will have no trouble in surpassing. The main challenge as it is usually the case with all songs is to keep the main melody in centerstage. This is achieved controlling the dynamics of each voice and to a degree the tome of each one of the voices. The thumb will work in conjunction with the i-m-a in the long 16th notes sequences in order to achieve a deep round sound. In the recording I omit staffs 3, 4, 5, 9, 10 & 11 because they are meant to be sang as a recitative and the guitar does not serve the sections well enough. Still, I incorporate the staffs in the Masterclass in case you want to accompany a singer or dimply want to give it a shot. Renato Bellucci plays "Time to Say Goodbye" San Bernardino, Paraguay, January 2, 2015, S.D.G.
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='django-oscar-stripe', version='0.1', url='https://github.com/tangentlabs/django-oscar-stripe', author="David Winterbottom", author_email="david.winterbottom@tangentlabs.co.uk", description="Stripe payment module for django-oscar", long_description=open('README.rst').read(), keywords="Payment, Stripe", license='BSD', packages=find_packages(exclude=['sandbox*', 'tests*']), include_package_data=True, install_requires=[ 'django-oscar>=0.4', 'stripe==1.7.9' ], dependency_links=['https://code.stripe.com/stripe/stripe-1.7.9#egg=stripe'], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python'] )
We are excited to launch the first in a series of workout with Joy, The London Physio - HKT's in-house Physiotherapist and wellness wiz. For the next 6 weeks, she will be taking us through a powerful weekly program to get you feeling fit for summer and helping you cleanse the mind to take on the week. Meet us down on the grass at 1pm (just by the podcasting booth), for varied - body weight - high intensity interval training. All abilities welcome and low impact options available. You're in safe hands with this physiology Einstein. Expect to sweat and down forget to bring the towels! Need shower access? Ask at reception to get cleared for entry. Sign up for your spot at this intimate class.
from instal.firstprinciples.TestEngine import InstalSingleShotTestRunner, InstalMultiShotTestRunner, InstalTestCase from instal.instalexceptions import InstalRuntimeError class IncompleteGrounding(InstalTestCase): def test_complete_grounding_solve(self): runner = InstalSingleShotTestRunner(input_files=["incompleteinstitutions/incomplete.ial"], bridge_file=None, domain_files=["incompleteinstitutions/fullgrounding.idc"], fact_files=[]) runner.run_test(query_file="incompleteinstitutions/blank.iaq") def test_no_grounding_solve(self): runner = InstalSingleShotTestRunner(input_files=["incompleteinstitutions/incomplete.ial"], bridge_file=None, domain_files=["incompleteinstitutions/nogrounding.idc"], fact_files=[]) with self.assertRaises(InstalRuntimeError): runner.run_test(query_file="incompleteinstitutions/blank.iaq") def test_partial_grounding_solve(self): runner = InstalSingleShotTestRunner(input_files=["incompleteinstitutions/incomplete.ial"], bridge_file=None, domain_files=["incompleteinstitutions/partialgrounding.idc"], fact_files=[]) with self.assertRaises(InstalRuntimeError): runner.run_test(query_file="incompleteinstitutions/blank.iaq") def test_complete_grounding_query(self): runner = InstalMultiShotTestRunner(input_files=["incompleteinstitutions/incomplete.ial"], bridge_file=None, domain_files=["incompleteinstitutions/fullgrounding.idc"], fact_files=[]) runner.run_test( query_file="incompleteinstitutions/blank.iaq", expected_answersets=1) def test_no_grounding_query(self): runner = InstalMultiShotTestRunner(input_files=["incompleteinstitutions/incomplete.ial"], bridge_file=None, domain_files=["incompleteinstitutions/nogrounding.idc"], fact_files=[]) with self.assertRaises(InstalRuntimeError): runner.run_test(query_file="incompleteinstitutions/blank.iaq") def test_partial_grounding_query(self): runner = InstalMultiShotTestRunner(input_files=["incompleteinstitutions/incomplete.ial"], bridge_file=None, domain_files=["incompleteinstitutions/partialgrounding.idc"], fact_files=[]) with self.assertRaises(InstalRuntimeError): runner.run_test(query_file="incompleteinstitutions/blank.iaq")
Hon. Sara Z. Duterte-Carpio will give the opening remarks during opening exhibits and welcome remarks. While President Rodrigo Roa Duterte will give the keynote speech during the opening ceremonies of the National Science and Technology Week Celebration in Mindanao. Check out DOST Region XI for more information for all the activities in store.
from library.models import Article, Author, Year, Label, Strategies, KeyWord from rest_framework import serializers class AuthorSerializer(serializers.HyperlinkedModelSerializer): papers_on_this_db = serializers.SerializerMethodField() class Meta: model = Author fields = "__all__" def get_papers_on_this_db(self, obj): return obj.article_set.count() class YearSerializer(serializers.HyperlinkedModelSerializer): papers_on_specific_year = serializers.SerializerMethodField() class Meta: model = Year fields = "__all__" def get_papers_on_specific_year(self, obj): return obj.article_set.count() class LabelsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Label fields = ["label"] class KeyWordSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = KeyWord fields = ["key_word"] class StrategiesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Strategies fields = ["strategy_name"] class ArticleSerializer(serializers.HyperlinkedModelSerializer): author = AuthorSerializer(many=True, ) date = YearSerializer() labels = LabelsSerializer(many=True, ) key_word = KeyWordSerializer(many=True, ) list_strategies = StrategiesSerializer(many=True) class Meta: model = Article fields = ('key', 'unique_key', 'title', 'author', 'date', 'abstract', 'pages', 'journal', 'labels', 'read', 'key_word', 'provenance', 'list_strategies') def create(self, validated_data): # Create the new article attributes date = Year.objects.create(year=validated_data['date'].get("year")) # create the article article = Article(date=date, title=validated_data['title'], abstract=validated_data['abstract'], key=validated_data['key'], pages=validated_data['pages'], journal=validated_data['journal'], provenance=validated_data['provenance']) article.save() for author in validated_data['author']: article.author.add(Author.objects.create(name=author['name'])) for label in validated_data['labels']: article.labels.add(Label.objects.create(label=label['label'])) for strategy in validated_data['list_strategies']: article.list_strategies.add(Strategies.objects.create( strategy_name=strategy['strategy_name'])) for keyword in validated_data['key_word']: article.key_word.add(KeyWord.objects.create(key_word=keyword[ 'key_word'])) return article
We all are spending thousands of dollars on internet marketing campaigns with a hope that these would bring in results, to ensure that you get what you want, add some interesting hacks to the PPC campaign. It is a comprehensible fact that PPC is the most effectual internet marketing tool being used and with some tweaks you can ensure that it starts working for you the way you want. The very first thing that you need to do is change the way in which ads are written, go in for a format that is more emotion driven and appears less machine written. This is going to kill that boring element and with this you will start getting the clicks. Another important area on which you need to work upon is the bid multiplier. You need to buy the best clicks for your business as with these only you will reap the benefits. This would work well especially for the local marketer as the results would start arriving in quicker. Another hack that would do you some interesting benefits is optimizing for mobile as this is the place fro where almost half the searches are coming. You can make use of the click to call button as with this chances of people clicking on the ad would increase manifold. Always make sure that you do not call in done with marketing only as you need to remarket again and again as the more actions you take the better would be the results.
class DataGenterator(object): def __init__( self, train_file_path, generate_x, generate_y, predict_file_path=None, batch_size=128 ): self.train_file_path = train_file_path self.predict_file_path = train_file_path if predict_file_path is not None: self.predict_file_path = predict_file_path self.generate_x = generate_x self.generate_y = generate_y self.batch_size = batch_size def array_generator(self, file_path, generating_function, batch_size): with open(file_path, 'r', encoding='utf-8') as array_file: seqs = [] seqs_len = 0 for line in array_file: if seqs_len < batch_size: seqs.append(line.strip().split(' ')) seqs_len += 1 else: array = generating_function(seqs) seqs = [line.strip().split(' ')] seqs_len = 1 yield array array = generating_function(seqs) yield array def __next__(self): while True: for x_array, y_array in zip( self.array_generator( self.train_file_path, self.generate_x, self.batch_size ), self.array_generator( self.predict_file_path, self.generate_y, self.batch_size ) ): #assert (len(x_array) == len(y_array)), \ # 'training data has different length with testing data' return (x_array, y_array)
We have exciting opportunities for a number of temporary Store Fulfilment Assistant to join our fantastic team in Edinburgh, to support over our peak sale period. An exciting and critical role managing our digital product road map reporting directly into the online management team. We are seeking an exceptional Fulfilment Administrator with proven experience in the industry to join our team in Northampton and work the weekend. An exciting opportunity for a copywriter to join our online team.
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class VirtualNetworkPeering(SubResource): """Peerings in a virtual network resource. :param id: Resource ID. :type id: str :param allow_virtual_network_access: Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virtual network space. :type allow_virtual_network_access: bool :param allow_forwarded_traffic: Whether the forwarded traffic from the VMs in the remote virtual network will be allowed/disallowed. :type allow_forwarded_traffic: bool :param allow_gateway_transit: If gateway links can be used in remote virtual networking to link to this virtual network. :type allow_gateway_transit: bool :param use_remote_gateways: If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. :type use_remote_gateways: bool :param remote_virtual_network: The reference of the remote virtual network. :type remote_virtual_network: ~azure.mgmt.network.v2017_08_01.models.SubResource :param peering_state: The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and 'Disconnected'. Possible values include: 'Initiated', 'Connected', 'Disconnected' :type peering_state: str or ~azure.mgmt.network.v2017_08_01.models.VirtualNetworkPeeringState :param provisioning_state: The provisioning state of the resource. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 'type': 'bool'}, 'allow_forwarded_traffic': {'key': 'properties.allowForwardedTraffic', 'type': 'bool'}, 'allow_gateway_transit': {'key': 'properties.allowGatewayTransit', 'type': 'bool'}, 'use_remote_gateways': {'key': 'properties.useRemoteGateways', 'type': 'bool'}, 'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'}, 'peering_state': {'key': 'properties.peeringState', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(VirtualNetworkPeering, self).__init__(**kwargs) self.allow_virtual_network_access = kwargs.get('allow_virtual_network_access', None) self.allow_forwarded_traffic = kwargs.get('allow_forwarded_traffic', None) self.allow_gateway_transit = kwargs.get('allow_gateway_transit', None) self.use_remote_gateways = kwargs.get('use_remote_gateways', None) self.remote_virtual_network = kwargs.get('remote_virtual_network', None) self.peering_state = kwargs.get('peering_state', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None)
Need to add storage capacity to your network quickly and easily? You need an NAS (Network Attached Storage) device. We review three leading contenders and pick a winner. One thing a network will always be short of is storage. As clients' hard disks grow, so do the volumes of data they want to store locally and share on a central server. Yet, for a small or medium-sized business, adding hard disks to a server to keep users happy is a tiresome and often time-consuming business. You need to take the server down -- which in itself is problematic in today's always-on environment -- and probably dismantle bits of the server's internals to find room for the mechanism, along with re-routing cables. It may entail installing new I/O cards and loading new drivers too -- adding time and complexity, not to mention potential instabilities. The bottom line is that it can be very costly. One alternative is to buy another PC-based server. This also gets expensive, not least because it will take time to set up and manage and, because of its complexity, will be less reliable than a dedicated file server. Effectively such a server bought purely for file sharing is wasting its potential. What's more, it has been estimated (by research company Gartner) that lost productivity from server downtime ranges from $200-$2,000 per hour for small businesses, and can be even higher for Web-based businesses. Far easier, then, to buy a network attached storage (NAS) appliance that simply plugs into the network and, after a little setting up, can simply be left alone. In fact, this ease of use combined with the plummeting cost of storage means that NAS has grown to become a very popular hardware category. NAS boxes are designed for file sharing rather than running applications, although they make useful backup devices too, since users can copy the contents of their hard disks whenever it suits them. This is likely to be important where the business or branch has no network manager to enforce backup policies. So the ideal NAS appliance will allow the administrator to manage disk space and set up private areas for users, serve a range of clients, and can be simply plugged into the network and start work with minimal configuration. All three products tested here can do that but some, as we shall see, offer considerably more. With that in mind we asked three NAS vendors -- Evesham Technology, Linksys and SnapAppliance -- to supply a solution they believed was suited to a small or medium-sized business, with a maximum price of around £1,000. We also asked Iomega to participate, but unfortunately, the company was unable to get a product to us in time. Adding storage is easy to do, and all three of these products can handle the requirements of a home office, or small to medium-sized business. They are all easy to fit and work pretty much straight out of the box. Interestingly though, there's a fair difference between them in terms of functionality and price. The Snap Server 1100 is a good-looking device that offers just what it promises -- extra storage, with the additional benefit of portability. It's a professional-looking product, from user interface to box to documentation. However, in spite of its portability, the Snap Server 1100 falls down when it comes to price. Although the version we looked at contained 120GB, the 80GB version still costs £449, while the 80GB Linksys EFG80 costs only £416 and has the capacity to either add another mechanism or upgrade existing drives. So for a simple file storage device, the Linksys product takes top honours for flexibility. However, compared to Evesham's NAS-2108R, the feature sets of the other two products start to look threadbare. This NAS box can do pretty much everything you want from a network gateway at a price below £1,000 -- you don't even need to buy a switch or hub. However, you'd also have to budget for the time it will take to fine-tune the configuration to suit your network's circumstances which, in some cases, may not be trivial. And the usual caveats regarding all-in-one devices apply here -- should you need to upgrade one component, you end up throwing everything away. In summary, for portable NAS, the Snap Server 1100 is the product to go for. For a do-it-all approach, the Evesham NAS-2108R boasts a superb feature set and is hard to beat. But for essential NAS functionality the Linksys EFG80 GigaDrive delivers the goods at an attractive price, and so wins our Editors' Choice.
# coding: utf-8 __author__ = 'tack' class Order(object): def __init__(self, code, num,hold_num, cost_price, market_price, commission, date, cmd): ''' Args: code: stock code cost_price: cost price market_price: market price commission: commission num: num hold_num: hold num date: date cmd: buy|sell ''' self.code = code self.num = num self.hold_num = hold_num self.date = date self.commission = commission self.cost_price = cost_price self.market_price = market_price self.cost = self.cost_price * num + commission self.cmd = cmd if (self.hold_num == 0 and 'sell' == self.cmd): self.profit = (self.market_price - self.cost_price) * num - self.commission else: self.profit = 0 - self.commission def __repr__(self): return 'cmd=%s, code=%s,cost=%f,cost_price=%f, market_price=%f,num=%d, hold_num=%d, commission=%f, profit=%f, date=%s' % (self.cmd, self.code, self.cost, self.cost_price,self.market_price, self.num,self.hold_num, self.commission,self.profit, self.date) class OrderHistory(object): def __init__(self): self._ohs = {} def update(self, order): ''' when the market close, update positions :param order: :return: ''' if order.code in self._ohs: self._ohs[order.code].append(order) else: self._ohs[order.code] = [order] def get_history(self, code): return self._ohs.get(code, None) def get_total_profit(self, code): if code not in self._ohs: return 0. profit = 0. for o in self._ohs[code]: profit += o.profit return profit
Many publisher teams we speak with routinely put ad quality among the top issues. Yet, the nuances and ways to solve for this are not well understood. PubMatic is passionate about improving ad quality for our clients and the programmatic ecosystem. Here we’ll cover the most common misconceptions about ad quality, and some of the best ways to tackle the problem head on. When we talk about ad quality, what do we mean? Quality can cover anything from advertiser category mapping to malicious creatives. We’ll focus on creative quality types (i.e. still banner, gif, in-banner video, auto-audio, etc.) and malicious content rendered through an ad. The most common, and maybe most damaging of myths, is that ad quality management can be solved completely. Much like inventory quality and inventory fraud, as soon as the industry comes out with one solution, the bad actors find a way to circumvent the system. It’s like a game of “whack-a-mole.” The goal is to use all tools available to you to be as close to 100 percent solved as possible. How do you do that? If you’re a tech provider like PubMatic, the best way is through a combination of partners and a build approach. We hold ourselves accountable by partnering with recognized global third-party vendors, like Confiant, to rescan our creatives and block whatever they’ve also flagged. We have also built our own technology to scan creatives that hit our platform, categorize their attributes, and block or allow them through to the publisher’s page, depending on their individual settings. Unlike something like open marketplace RTB protocol, there’s no IAB-standardized, totally clear way to go about solving for ad quality. This means each SSP is left to their own devices to decide for themselves how to solve for this. Some may only partner with a third-party detection vendor, others may only use their own tools, and some, like PubMatic, take a hybrid approach. Ultimately, the best way for a publisher to trust the SSP’s ability to manage ad quality is to understand their solutions and decide for themselves if they’ve taken a deep and comprehensive approach. If your users are extraordinarily sensitive to ad quality and you would prefer to accept potentially lower programmatic revenue rather than risk an ad quality violation, you might conclude that you should hand-pick which advertisers to allow. In other words, you may want to identify a list of trusted brands that cover a majority of your spend, and allow only those brands ads to run. Unfortunately, this won’t get you very far in blocking quality violations. First, a bad actor can attach malicious content to an unsuspecting advertiser. That’s where detection tools have a big impact in ensuring quality. Second, even if the brand itself is safe, the creative type they are using may still not align with what your users are willing to accept (for instance, a creative with auto video playing, not click-to-play). So how do I best protect myself as a publisher? Extra sensitive publishers can partner with a third-party, as an additional verification point, before serving a creative. Though ultimately, protecting yourself against ad quality violations at scale requires choosing SSP partnerships whose solutions you have vetted and trust. PubMatic is fighting the good fight and taking measured steps to further improve ad quality, inventory quality and reduce fraud in the programmatic landscape. If you would like to know more about our solutions, check them out here or let us know how we can partner with you.
""" Created on Dec 12, 2015 @author: justinpalpant Copyright 2015 Justin Palpant This file is part of the Jarvis Lab RNAseq Workflow program. RNAseq Workflow is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RNAseq Workflow is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with RNAseq Workflow. If not, see http://www.gnu.org/licenses/. """ import logging import subprocess import os import fnmatch import re import shutil from abc import ABCMeta, abstractmethod, abstractproperty from cliutils import all_subclasses, firstline from cliutils import ArgFiller class Workflow(object): """ Execute a simple series of steps used to preprocess RNAseq files """ logger = logging.getLogger('rnaseqflow.Workflow') """log4j-style class logger""" def __init__(self): """ Initialize an empty workflow with no stages """ self.items = [] def append(self, item): """Add a WorkflowStage to the workflow :param item: the WorkflowStage to insert :type item: WorkflowStage """ self.items.append(item) def insert(self, idx, item): """Insert a WorkflowStage into the workflow :param idx: list index for insertion :type idx: int :param item: the WorkflowStage to insert :type item: WorkflowStage """ self.items.insert(idx, item) def run(self): """Allows the user to select a directory and processes all files within that directory This function is the primary function of the Workflow class. All other functions are written as support for this function, at the moment """ current_input = None for item in self.items: next_input = item.run(current_input) current_input = next_input class WorkflowStage(object): """Interface for a stage of a Workflow Subclasses must override the run method, which takes and verifies arbitrary input, processes it, and returns some output They must also provide a .spec property which is a short string to be used to select the specific WorkflowStage from many options. These should not overlap, but at the moment no checking is done to see if they do. """ __metaclass__ = ABCMeta logger = logging.getLogger('rnaseqflow.WorkflowStage') """log4j-style class logger""" @abstractmethod def run(self, stage_input): """Attempt to process the provided input according to the rules of the subclass :param stage_input: an arbitrary input to be processed, usually a list of file names or file-like objects. The subclass must typecheck the input as necessary, and define what input it takes :type stage_input: object :returns: the results of the subclass's processing """ pass @abstractproperty def spec(self): """Abstract class property, override with @classmethod Used by the help method to specify available WorkflowItems """ pass @classmethod def shorthelp(cls): """Create a short help text with one line for each subclass of WorkflowStage Subclasses are found using cliutils.all_subclasses """ helpstrings = [] helpstrings.append('The following WorkflowStages are available:\n') for sub in all_subclasses(cls): helpstrings.append( '{0}: {1} - {2}\n'.format( sub.spec, sub.__name__, firstline(sub.__doc__))) helpstrings.append('Use "--help stages" for more details\n') return ''.join(helpstrings) @classmethod def longhelp(cls): """Create a long help text with full docstrings for each subclass of WorkflowStage Subclasses are found using cliutils.all_subclasses """ helpstrings = [] helpstrings.append('The following WorkflowStages are available:\n') for sub in all_subclasses(cls): helpstrings.append( '{0}: {1}\n {2}\n'.format( sub.spec, sub.__name__, sub.__doc__)) return ''.join(helpstrings) class FindFiles(WorkflowStage): """Find files recursively in a folder Input: No input is required for this WorkflowStage Output: A flat set of file path strings Args used: * --root: the folder in which to start the search * --ext: the file extention to search for """ logger = logging.getLogger('rnaseqflow.WorkflowStage.FindFiles') """log4j-style class-logger""" spec = '1' """FindFiles uses '1' as its specifier""" def __init__(self, args): """Prepare the recursive file finder Check that a root directory is provided, or ask for one Make sure the search extension is valid :param args: an object with settable and gettable attributes :type args: Namespace, SimpleNamespace, etc. """ argfiller = ArgFiller(args) argfiller.fill(['root', 'ext']) self.root = args.root self.ext = args.ext def run(self, stage_input): """Run the recursive file finding stage :param stage_input: not used, only for the interface :type stage_input: object, None :returns: A flat set of files found with the correct extension :rtype: set(str) """ self.logger.info('Beginning file find operations') outfiles = set() for root, _, files in os.walk(self.root): for basename in files: if fnmatch.fnmatch(basename, "*" + self.ext): filename = os.path.join(root, basename) outfiles.add(filename) self.logger.info('Found {0} files'.format(len(outfiles))) return outfiles class MergeSplitFiles(WorkflowStage): """Merge files by the identifying sequence and direction Input: An iterable of file names to be grouped and merged Output: A flat set of merged filenames Args used: * --root: the folder where merged files will be placed * --ext: the file extention to be used for the output files * --blocksize: number of kilobytes to use as a copy block size """ logger = logging.getLogger('rnaseqflow.WorkflowStage.MergeSplitFiles') """log4j-style class-logger""" spec = '2' """MergeSplitFiles uses '2' as its specifier""" def __init__(self, args): """Prepare for the merge file stage Check for a root directory and a blocksize :param args: an object with settable and gettable attributes :type args: Namespace, SimpleNamespace, etc. """ argfiller = ArgFiller(args) argfiller.fill(['root', 'ext', 'blocksize']) self.root = args.root self.blocksize = args.blocksize self.ext = args.ext self.outdir = os.path.join(self.root, 'merged') try: os.makedirs(self.outdir) except OSError: if not os.path.isdir(self.outdir): self.logger.error( 'Cannot make directory {0}, ' 'permissions'.format(self.outdir)) raise def run(self, stage_input): """Run the merge files operation Creates a directory merged under the root directory and fills it with files concatenated from individual parts of large RNAseq data files Files are grouped and ordered by searching the file basename for a sequence identifier like AACTAG, a direction like R1, and a part number formatted 001 :param stage_input: file names to be organized and merged :type stage_input: iterable(str) :returns: a set of organized files :rtype: set(str) """ self.logger.info('Beginning file merge operations') organized = self._organize_files(stage_input) merged_files = set() for i, (fileid, files) in enumerate(organized.iteritems()): outfile_name = 'merged_' + \ fileid[0] + '_' + fileid[1] + self.ext outfile_path = os.path.join(self.outdir, outfile_name) self.logger.info( 'Building file {0:d} of {1:d}: {2}'.format( i + 1, len(organized), outfile_path)) with open(outfile_path, 'wb') as outfile: for j, infile in enumerate(files): if j + 1 != self._get_part_num(infile): self.logger.error( '{0} is not file {1} of {2}. Files must be out of' ' order, or there are extra files in the root ' 'folder that the merger cannot process. ' 'Construction of file {2} is ' 'terminated'.format(infile, j+1, outfile_path)) break self.logger.debug( 'Merging file %d of %d: %s', j, len(files), infile) shutil.copyfileobj( open(infile, 'rb'), outfile, 1024 * self.blocksize) merged_files.add(outfile_path) self.logger.info('Created {0} merged files'.format(len(merged_files))) return merged_files def _organize_files(self, files): """Organizes a list of paths by sequence_id, part number, and direction Uses regular expressions to find the six-character sequence ID, the three character integer part number, and the direction (R1 or R2) :param files: filenames to be organized :type files: iterable(str) :returns: organized files in a dictionary mapping the sequence ID and direction to the files that have that ID, sorted in ascending part number :rtype: dict(tuple:list) """ mapping = {} for path in files: sequence_id = self._get_sequence_id(os.path.basename(path)) direction = self._get_direction_id(os.path.basename(path)) if not (sequence_id and direction): self.logger.warning('Discarding file {0} - could not find ' 'sequence ID and direction using ' 'regular expressions'.format( os.path.basename(path))) continue try: mapping[(sequence_id, direction)].append(path) except KeyError: mapping[(sequence_id, direction)] = [path] for key, lst in mapping.iteritems(): mapping[key] = sorted(lst, key=self._get_part_num) return mapping @staticmethod def _get_sequence_id(filename): """Gets the six-letter RNA sequence that identifies the RNAseq file Returns a six character string that is the ID, or an empty string if no identifying sequence is found. :param filename: the base filename to be processed :type filename: str :returns: the file's sequence ID, six characters of ACTG :rtype: string """ p = re.compile('.*[ACTG]{6}') m = p.search(filename) if m is None: return '' else: return m.group() @staticmethod def _get_direction_id(filename): """Gets the direction identifier from an RNAseq filename A direction identifier is either R1 or R2, indicating a forward or a backwards read, respectively. :param filename: the base filename to be processed :type filename: str :returns: the file's direction ID, R1 or R2 :rtype: string """ p = re.compile('R\d{1}') m = p.search(filename) if m is None: return '' else: return m.group() @staticmethod def _get_part_num(filename): """Returns an integer indicating the file part number of the selected RNAseq file RNAseq files, due to their size, are split into many smaller files, each of which is given a three digit file part number (e.g. 001, 010). This method returns that part number as an integer. This requires that there only be one sequence of three digits in the filename :param filename: the base filename to be processed :type filename: str :returns: the file's part number :rtype: int """ p = re.compile('_\d{3}') m = p.search(filename) if m is None: return 0 else: text = m.group() return int(text[1:]) class FastQMCFTrimSolo(WorkflowStage): """Trim adapter sequences from files using fastq-mcf one file at a time Input: A flat set of files to be passed into fastq-mcf file-by-file Output: A flat set of trimmed file names Args used: * --root: the folder where trimmed files will be placed * --adapters: the filepath of the fasta adapters file * --fastq: the location of the fastq-mcf executable * --fastq_args: a string of arguments to pass directly to fastq-mcf * --quiet: silence fastq-mcf's output if given """ logger = logging.getLogger('rnaseqflow.WorkflowStage.FastQMCFTrimSolo') """log4j-style class-logger""" spec = '3.0' """FastQMCFTrimSolo uses '3.0' as its specifier""" def __init__(self, args): """Run all checks needed to create a FastQMCFTrimSolo object Check that fastq-mcf exists in the system Specify the fasta adapter file and any arguments Create the output folder :param args: an object with settable and gettable attributes :type args: Namespace, SimpleNamespace, etc. """ argfiller = ArgFiller(args) argfiller.fill(['root', 'adapters', 'fastq', 'fastq_args', 'quiet']) self.root = args.root self.adapters = args.adapters self.fastq_args = args.fastq_args self.executable = args.fastq self.quiet = args.quiet self.outdir = os.path.join(self.root, 'trimmed') try: os.makedirs(self.outdir) except OSError: if not os.path.isdir(self.outdir): raise try: with open(os.devnull, "w") as fnull: subprocess.call([self.executable], stdout=fnull, stderr=fnull) except OSError: self.logger.error( 'fastq-mcf not found, cannot use FastQMCFTrimSolo') raise else: self.logger.info('fastq-mcf found') def run(self, stage_input): """Trim files one at a time using fastq-mcf :param stage_input: filenames to be processed :type stage_input: iterable(str) :returns: a set of filenames holding the processed files :rtype: set(str) """ self.logger.info('Beginning file trim operation') trimmed_files = set() for i, fname in enumerate(stage_input): outfile_name = 'trimmed_' + os.path.basename(fname) outfile_path = os.path.join(self.outdir, outfile_name) cmd = [self.executable, self.adapters, fname] + \ self.fastq_args.split() + ['-o', outfile_path] self.logger.info( 'Building file {0:d} of {1:d}: {2}'.format( i + 1, len(stage_input), outfile_path)) self.logger.debug('Calling %s', str(cmd)) if self.quiet: with open(os.devnull, 'w') as nullfile: subprocess.call(cmd, stdout=nullfile, stderr=nullfile) else: subprocess.call(cmd) trimmed_files.add(outfile_path) self.logger.info('Trimmed {0} files'.format(len(trimmed_files))) return trimmed_files class FastQMCFTrimPairs(WorkflowStage): """Trim adapter sequences from files using fastq-mcf in paired-end mode Input: A flat set of files to be passed into fastq-mcf in pairs Output: A flat set of trimmed file names Args used: * --root: the folder where trimmed files will be placed * --adapters: the filepath of the fasta adapters file * --fastq: the location of the fastq-mcf executable * --fastq_args: a string of arguments to pass directly to fastq-mcf * --quiet: silence fastq-mcf's output if given """ logger = logging.getLogger('rnaseqflow.WorkflowStage.FastQMCFTrimPairs') """log4j-style class-logger""" spec = '3.1' """FastQMCFTrimPairs uses '3.1' as its specifier""" def __init__(self, args): """Run all checks needed to create a FastQMCFTrimPairs object Check that fastq-mcf exists in the system Specify the fasta adapter file and any arguments Create the output folder :param args: an object with settable and gettable attributes :type args: Namespace, SimpleNamespace, etc. """ argfiller = ArgFiller(args) argfiller.fill(['root', 'adapters', 'fastq', 'fastq_args', 'quiet']) self.root = args.root self.adapters = args.adapters self.fastq_args = args.fastq_args self.executable = args.fastq self.quiet = args.quiet self.outdir = os.path.join(self.root, 'trimmed') try: os.makedirs(self.outdir) except OSError: if not os.path.isdir(self.outdir): raise try: with open(os.devnull, "w") as fnull: subprocess.call([self.executable], stdout=fnull, stderr=fnull) except OSError: self.logger.error( 'fastq-mcf not found, cannot use FastQMCFTrimPairs') raise else: self.logger.info('fastq-mcf found') def run(self, stage_input): """Trim files one at a time using fastq-mcf :param stage_input: filenames to be processed :type stage_input: iterable(str) :returns: a set of filenames holding the processed files :rtype: set(str) """ self.logger.info('Beginning file trim operation') pairs = self._find_file_pairs(stage_input) trimmed_files = set() prog_count = 0 for f1, f2 in pairs: outfile_name_1 = 'trimmed_' + os.path.basename(f1) outfile_path_1 = os.path.join(self.outdir, outfile_name_1) prog_count += 1 if f2: prog_count += 1 outfile_name_2 = 'trimmed_' + os.path.basename(f2) outfile_path_2 = os.path.join(self.outdir, outfile_name_2) cmd = [self.executable, self.adapters, f1, f2] + \ self.fastq_args.split() + \ ['-o', outfile_path_1, '-o', outfile_path_2] self.logger.info( 'Building files {0:d} and {1:d} of {2:d}: {3} and {4}'.format( prog_count - 1, prog_count, len(stage_input), outfile_path_1, outfile_path_2)) self.logger.debug('Calling %s', str(cmd)) trimmed_files.add(outfile_path_1) trimmed_files.add(outfile_path_2) else: cmd = [self.executable, self.adapters, f1] + \ self.fastq_args.split() + ['-o', outfile_path_1] self.logger.info( 'Building file {0:d} of {1:d}: {2}'.format( prog_count, len(stage_input), outfile_path_1)) trimmed_files.add(outfile_path_1) self.logger.debug('Calling %s', str(cmd)) if self.quiet: with open(os.devnull, 'w') as nullfile: subprocess.call(cmd, stdout=nullfile, stderr=nullfile) else: subprocess.call(cmd) self.logger.info('Trimmed {0} files'.format(len(trimmed_files))) return trimmed_files def _find_file_pairs(self, files): """Finds pairs of forward and backward read files :param files: filenames to be paired and trimmed :type files: iterable(str) :returns: pairs (f1, f2) that are paired files, forward and backward If a file f1 does not have a mate, f2 will be None, and the file will be trimmed without a mate :rtype: set(tuple(str, str)) """ pairs = set() for f in files: try: pair = next(f2 for f2 in files if ( self._get_sequence_id(f2) == self._get_sequence_id(f) and f2 != f)) except StopIteration as e: pairs.add((f, None)) else: pairs.add(tuple(fn for fn in sorted([f, pair]))) return pairs @staticmethod def _get_sequence_id(filename): """Gets the six-letter RNA sequence that identifies the RNAseq file Returns a six character string that is the ID, or an empty string if no identifying sequence is found. :param filename: the base filename to be processed :type filename: str :returns: the file's sequence ID, six characters of ACTG :rtype: string """ p = re.compile('.*[ACTG]{6}') m = p.search(filename) if m is None: return '' else: return m.group()
Hugh Blake Bell born July 30, 1927 passed away peacefully with friends and family by his side on October 14,2012 at the Carman Memorial Hospital at the age of 85. Left to mourn Hugh, is his dearly beloved and devoted wife of 52 years Millie, his children, Darlene(Mike) Fardy, Blake (Tamera)Bell, Rob(Janet) Bell; and grandchildren Jamie, Regan(Devon), Matthew, Courtney and Tyler. Also remembered by his sister Ruth and husband Hermann Wold, sister-in-laws Helen Bell, Betty Barthlette, Doreen Hill and brother-in-law Jack(Mary)Hill, numerous nieces and nephews and best friends Lorne and Lorraine Fife. He was predeceased by his parents Peter and Naomi and step-mother Lillian, sisters Alice(Allie)McTavish, Mabel (Sterling) Amos, Edith Bell, brother Robert Bell, Millie's parents Tom and Rose Hill, sister-in-laws Edna Hill, Barbara McCulloch, and brother-in-laws Adelard Barthelette, Bob Hill and Bill Hill. Hugh was born in Roland MB. He grew up on the family farm with his brothers and sisters. When he completed his schooling he chose to follow in his dad's footsteps and farmed with his brother Bob. In 1959, Hugh met his life partner Millie (Hill) and were wed on April 2, 1960. Hugh and Millie continued to farm and raise their family (on the North half- section of the family homestead) until he retired and moved to Carman. Hugh was a social butterfly! He will always be remembered for his big smile. He never missed a sporting event of his children and grandchildren. Hugh will always be deeply loved, sadly missed and always remembered as a devoted husband, father, grandfather and friend. Hugh's funeral service will be held on Friday, October 19, 2012 at 2:00 pm. at the Carman United Church. Lunch will follow immediately at Doyle's Funeral Home. In lieu of flowers, donations may be made to the Carman Memorial Hospital Palliative Care, Box 610, Carman, MB, R0G 0J0.
from flask import render_template, flash, redirect, session, url_for, abort, g from flask.ext.login import login_user, logout_user, current_user, login_required from app import app, db, login_manager, forms from app.models import User, Ticket from common import display_errors @login_manager.user_loader def load_user(userid): return User.query.filter_by(id=int(userid)).first() def administrative(func): def wrapped(*args, **kwargs): if not g.user.admin: flash('Not Authorized to access that page. Not an Admin', 'danger') return redirect(url_for('home')) return func(*args, **kwargs) return wrapped def author(func): def wrapped(*args, **kwargs): if not g.user.author: flash('Not Authorized to access that page. Not an Author', 'danger') return redirect(url_for('home')) return func(*args, **kwargs) return wrapped def reviewer(func): def wrapped(*args, **kwargs): if not g.user.reviewer: flash('Not Authorized to access that page. Not a Reviewer', 'danger') return redirect(url_for('home')) return func(*args, **kwargs) return wrapped @app.route('/login', methods=['GET', 'POST']) def login(): if g.user.is_authenticated(): return redirect(url_for('home')) form = forms.LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is not None and user.check_password(form.password.data): login_user(user) return redirect(url_for('home')) else: user = None if user == None: flash('Invalid Username or Password', 'error') return render_template('login.html', title='Sign In', form=form) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('home')) @app.route('/user/new', methods=['GET', 'POST']) @app.route('/user/<username>', methods=['GET', 'POST']) def user_info(username=None): if g.user.username == username or g.user.admin: user = User.query.filter_by(username=username).first_or_404() tickets = Ticket.query.filter_by(user_id=user.id).all() return render_template('user_info.html', person=user, tickets=tickets, title='%s - Information' % user.username) return redirect(url_for('home'))
A wonderful, immaculate Edgartown home. This spacious home near South Beach is practically in Katama, but also close to the Village, within easy walking distance of a tennis court free for your use. Located convenient to both town and beach, this is a very well priced, nicely appointed home, with a good 12 ft. deck, large eat-in kitchen for 8, a sunny living room with sliders, queen beds, and twins. New Kitchen. A great choice for a family or friends to share. The neighborhood, Island Grove is very sought after, and leafy mature trees grace the streets. This home is in a Cul-de-sac so it is quieter, and nice for children playing or riding their bikes. A true gem!
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import numpy as np import scipy.ndimage as ndimg from scipy.ndimage.morphology import binary_fill_holes as fill_holes from niftynet.layer.base_layer import Layer from niftynet.utilities.util_common import look_up_operations from niftynet.utilities.util_common import otsu_threshold """ This class defines methods to generate a binary image from an input image. The binary image can be used as an automatic foreground selector, so that later processing layers can only operate on the `True` locations within the image. """ SUPPORTED_MASK_TYPES = set(['threshold_plus', 'threshold_minus', 'otsu_plus', 'otsu_minus', 'mean_plus']) SUPPORTED_MULTIMOD_MASK_TYPES = set(['or', 'and', 'multi']) class BinaryMaskingLayer(Layer): def __init__(self, type_str='otsu_plus', multimod_fusion='or', threshold=0.0): super(BinaryMaskingLayer, self).__init__(name='binary_masking') self.type_str = look_up_operations( type_str.lower(), SUPPORTED_MASK_TYPES) self.multimod_fusion = look_up_operations( multimod_fusion.lower(), SUPPORTED_MULTIMOD_MASK_TYPES) self.threshold = threshold def __make_mask_3d(self, image): assert image.ndim == 3 image_shape = image.shape image = image.reshape(-1) mask = np.zeros_like(image, dtype=np.bool) thr = self.threshold if self.type_str == 'threshold_plus': mask[image > thr] = True elif self.type_str == 'threshold_minus': mask[image < thr] = True elif self.type_str == 'otsu_plus': thr = otsu_threshold(image) if np.any(image) else thr mask[image > thr] = True elif self.type_str == 'otsu_minus': thr = otsu_threshold(image) if np.any(image) else thr mask[image < thr] = True elif self.type_str == 'mean_plus': thr = np.mean(image) mask[image > thr] = True mask = mask.reshape(image_shape) mask = ndimg.binary_dilation(mask, iterations=2) mask = fill_holes(mask) # foreground should not be empty assert np.any(mask == True), \ "no foreground based on the specified combination parameters, " \ "please change choose another `mask_type` or double-check all " \ "input images" return mask def layer_op(self, image): if image.ndim == 3: return self.__make_mask_3d(image) if image.ndim == 5: mod_to_mask = [m for m in range(image.shape[4]) if np.any(image[..., :, m])] mask = np.zeros_like(image, dtype=bool) mod_mask = None for mod in mod_to_mask: for t in range(image.shape[3]): mask[..., t, mod] = self.__make_mask_3d(image[..., t, mod]) # combine masks across the modalities dim if self.multimod_fusion == 'or': if mod_mask is None: mod_mask = np.zeros(image.shape[:4], dtype=bool) mod_mask = np.logical_or(mod_mask, mask[..., mod]) elif self.multimod_fusion == 'and': if mod_mask is None: mod_mask = np.ones(image.shape[:4], dtype=bool) mod_mask = np.logical_and(mod_mask, mask[..., mod]) for mod in mod_to_mask: mask[..., mod] = mod_mask return mask else: raise ValueError("unknown input format")
Gary Jaensch contributed more to Oregon Genealogy than anyone I know. He was the one who answered your questions, found your answers, and pushed me to add more to the online pages. He not only answered your questions, he found answers to questions you didn't ask. Genealogy was his passion, didn't seem to matter if it was his own or someone asking for help. Gary spent many hours at the Baker County Library, if you would like to make a donation in Gary's memory, you may do so through Gray West & Co., Baker City, Oregon 97814. All Donations we will be used for the Reading Room of the library.
# -*- coding: utf-8 -*- from flask import Blueprint, redirect, request, url_for from oic.oic.message import AuthorizationResponse, Claims, ClaimsRequest from six.moves.urllib_parse import urlencode from eduid_common.api.decorators import MarshalWith, UnmarshalWith, require_user from eduid_common.api.messages import CommonMsg, redirect_with_msg from eduid_common.api.schemas.csrf import CSRFRequest from eduid_common.api.utils import get_unique_hash, save_and_sync_user from eduid_userdb.logs import OrcidProofing from eduid_userdb.orcid import OidcAuthorization, OidcIdToken, Orcid from eduid_userdb.proofing import OrcidProofingState, ProofingUser from eduid_webapp.orcid.app import current_orcid_app as current_app from eduid_webapp.orcid.helpers import OrcidMsg from eduid_webapp.orcid.schemas import OrcidResponseSchema __author__ = 'lundberg' orcid_views = Blueprint('orcid', __name__, url_prefix='', template_folder='templates') @orcid_views.route('/authorize', methods=['GET']) @require_user def authorize(user): if user.orcid is None: proofing_state = current_app.proofing_statedb.get_state_by_eppn(user.eppn, raise_on_missing=False) if not proofing_state: current_app.logger.debug( 'No proofing state found for user {!s}. Initializing new proofing state.'.format(user) ) proofing_state = OrcidProofingState( id=None, modified_ts=None, eppn=user.eppn, state=get_unique_hash(), nonce=get_unique_hash() ) current_app.proofing_statedb.save(proofing_state) claims_request = ClaimsRequest(userinfo=Claims(id=None)) oidc_args = { 'client_id': current_app.oidc_client.client_id, 'response_type': 'code', 'scope': 'openid', 'claims': claims_request.to_json(), 'redirect_uri': url_for('orcid.authorization_response', _external=True), 'state': proofing_state.state, 'nonce': proofing_state.nonce, } authorization_url = '{}?{}'.format(current_app.oidc_client.authorization_endpoint, urlencode(oidc_args)) current_app.logger.debug('Authorization url: {!s}'.format(authorization_url)) current_app.stats.count(name='authn_request') return redirect(authorization_url) # Orcid already connected to user redirect_url = current_app.conf.orcid_verify_redirect_url return redirect_with_msg(redirect_url, OrcidMsg.already_connected) @orcid_views.route('/authorization-response', methods=['GET']) @require_user def authorization_response(user): # Redirect url for user feedback redirect_url = current_app.conf.orcid_verify_redirect_url current_app.stats.count(name='authn_response') # parse authentication response query_string = request.query_string.decode('utf-8') current_app.logger.debug('query_string: {!s}'.format(query_string)) authn_resp = current_app.oidc_client.parse_response(AuthorizationResponse, info=query_string, sformat='urlencoded') current_app.logger.debug('Authorization response received: {!s}'.format(authn_resp)) if authn_resp.get('error'): current_app.logger.error( 'AuthorizationError from {}: {} - {} ({})'.format( request.host, authn_resp['error'], authn_resp.get('error_message'), authn_resp.get('error_description') ) ) return redirect_with_msg(redirect_url, OrcidMsg.authz_error) user_oidc_state = authn_resp['state'] proofing_state = current_app.proofing_statedb.get_state_by_oidc_state(user_oidc_state, raise_on_missing=False) if not proofing_state: current_app.logger.error('The \'state\' parameter ({!s}) does not match a user state.'.format(user_oidc_state)) return redirect_with_msg(redirect_url, OrcidMsg.no_state) # do token request args = { 'code': authn_resp['code'], 'redirect_uri': url_for('orcid.authorization_response', _external=True), } current_app.logger.debug('Trying to do token request: {!s}'.format(args)) token_resp = current_app.oidc_client.do_access_token_request( scope='openid', state=authn_resp['state'], request_args=args, authn_method='client_secret_basic' ) current_app.logger.debug('token response received: {!s}'.format(token_resp)) id_token = token_resp['id_token'] if id_token['nonce'] != proofing_state.nonce: current_app.logger.error('The \'nonce\' parameter does not match for user') return redirect_with_msg(redirect_url, OrcidMsg.unknown_nonce) current_app.logger.info('ORCID authorized for user') # do userinfo request current_app.logger.debug('Trying to do userinfo request:') userinfo = current_app.oidc_client.do_user_info_request( method=current_app.conf.userinfo_endpoint_method, state=authn_resp['state'] ) current_app.logger.debug('userinfo received: {!s}'.format(userinfo)) if userinfo['sub'] != id_token['sub']: current_app.logger.error( 'The \'sub\' of userinfo does not match \'sub\' of ID Token for user {!s}.'.format(proofing_state.eppn) ) return redirect_with_msg(redirect_url, OrcidMsg.sub_mismatch) # Save orcid and oidc data to user current_app.logger.info('Saving ORCID data for user') proofing_user = ProofingUser.from_user(user, current_app.private_userdb) oidc_id_token = OidcIdToken( iss=id_token['iss'], sub=id_token['sub'], aud=id_token['aud'], exp=id_token['exp'], iat=id_token['iat'], nonce=id_token['nonce'], auth_time=id_token['auth_time'], created_by='orcid', ) oidc_authz = OidcAuthorization( access_token=token_resp['access_token'], token_type=token_resp['token_type'], id_token=oidc_id_token, expires_in=token_resp['expires_in'], refresh_token=token_resp['refresh_token'], created_by='orcid', ) orcid_element = Orcid( id=userinfo['id'], name=userinfo['name'], given_name=userinfo['given_name'], family_name=userinfo['family_name'], is_verified=True, oidc_authz=oidc_authz, created_by='orcid', ) orcid_proofing = OrcidProofing( eppn=proofing_user.eppn, created_by='orcid', orcid=orcid_element.id, issuer=orcid_element.oidc_authz.id_token.iss, audience=orcid_element.oidc_authz.id_token.aud, proofing_method='oidc', proofing_version='2018v1', ) if current_app.proofing_log.save(orcid_proofing): current_app.logger.info('ORCID proofing data saved to log') proofing_user.orcid = orcid_element save_and_sync_user(proofing_user) current_app.logger.info('ORCID proofing data saved to user') message_args = dict(msg=OrcidMsg.authz_success, error=False) else: current_app.logger.info('ORCID proofing data NOT saved, failed to save proofing log') message_args = dict(msg=CommonMsg.temp_problem) # Clean up current_app.logger.info('Removing proofing state') current_app.proofing_statedb.remove_state(proofing_state) return redirect_with_msg(redirect_url, **message_args) @orcid_views.route('/', methods=['GET']) @MarshalWith(OrcidResponseSchema) @require_user def get_orcid(user): return user.to_dict() @orcid_views.route('/remove', methods=['POST']) @UnmarshalWith(CSRFRequest) @MarshalWith(OrcidResponseSchema) @require_user def remove_orcid(user): current_app.logger.info('Removing ORCID data for user') proofing_user = ProofingUser.from_user(user, current_app.private_userdb) proofing_user.orcid = None save_and_sync_user(proofing_user) current_app.logger.info('ORCID data removed for user') return proofing_user.to_dict()
Saturday marks the first annual Austin Nature Day, a day to “celebrate the beauty, vitality, and diversity of natural resources that contribute to our high quality of life.” The number and locations that are taking part is quite large: from McKinney Roughs where you can float down the Colorado River to the Lady Bird Johnson Wildflower Center to the Austin Nature Center, where you can celebrate Earth Day a week early with the American Chemical Society, where you can get infomration on local flora and fauna. There are guided hikes and tours, lectures and other activities. And most all of it is free! What Austin Nature Day is not is this. After all, there it’s nature day every day.
from django.dispatch import receiver from django.db.models.signals import post_save, pre_save from invoicing.models import * from haystack.management.commands import update_index from django.utils import timezone import invoicing.views as invoicing from invoicing import schedules from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ """ Note: if doing a save in post_save ensure signal is disconnected to avoid an infinite loop of saving: e.g.: post_save.disconnect(my_method, sender=sender) instance.save() post_save.connect(my_method, sender=Invoice) """ @receiver(post_save, sender=Invoice) def invoice_post_save(sender, instance, created, **kwargs): """ post save receiver for Invoice model """ save_updated = False post_save.disconnect(invoice_post_save, sender=sender) if created: invoice_id = model_functions.generate_invoice_random_id() # generate random id instance.invoice_number = '{}-{}'.format(invoice_id, instance.id) save_updated = True # recurring invoice stuff if not getattr(instance, 'save_pdf', False): # if save not being called again just to update DB after gen of PDF # set the invoice as start/stop recurring recurring(instance=instance) # dispatch email if client email notifications set to true and the save is being called when saving a new PDF if instance.client.email_notifications and getattr(instance, 'save_pdf', False): if instance.invoice_status == Invoice.INVOICE_STATUS[5][0]: # receipt (paid in full) # send email if not getattr(instance, 'receipt_emailed', False): # if hasn't already been sent invoicing.pdf_gen_or_fetch_or_email(invoice_number=instance.invoice_number, type=invoicing.PDF_TYPES.get('receipt'), email=True, regenerate=False) # mark as sent setattr(instance, 'receipt_emailed', True) save_updated = True elif instance.invoice_status == Invoice.INVOICE_STATUS[1][0]: # invoice (unpaid) # send email if not getattr(instance, 'invoice_emailed', False): # if hasn't already been sent invoicing.pdf_gen_or_fetch_or_email(invoice_number=instance.invoice_number, type=invoicing.PDF_TYPES.get('invoice'), email=True, regenerate=False) # mark as sent setattr(instance, 'invoice_emailed', True) # change status from issued to sent setattr(instance, 'invoice_status', Invoice.INVOICE_STATUS[2][0]) save_updated = True elif instance.invoice_status == Invoice.INVOICE_STATUS[4][0]: # invoice (partially paid) # send email invoicing.pdf_gen_or_fetch_or_email(invoice_number=instance.invoice_number, type=invoicing.PDF_TYPES.get('invoice_update'), email=True) # save the instance if something's been called ... if save_updated: # disable pre_save signal, as not required to be run again for the second save! pre_save.disconnect(invoice_pre_save, sender=Invoice) # save the instance instance.save() # re-enable pre_save signal pre_save.connect(invoice_pre_save, sender=Invoice) # re-enable post_save signal post_save.connect(invoice_post_save, sender=Invoice) @receiver(pre_save, sender=Invoice) def invoice_pre_save(sender, instance, **kwargs): """ Also to populate mark_as_paid field with datetime when a status is changed to 'PAID_IN_FULL' Also populates the "amount_paid" field with total. Also updates the invoice status to partially paid when an amount is paid """ try: # existing invoice to be modified inv = Invoice.objects.get(invoice_number=instance.invoice_number) except Invoice.DoesNotExist: # new invoice inv = Invoice() # generate an empty reference Invoice instance if no existing (i.e. A NEW INVOICE) # IF NOT SAVING PDF (Most stuff goes in here!) if not getattr(instance, 'save_pdf', False): # avoid running this pre_save if 'save_pdf' param added to instance # PRE-SAVE AMENDMENT STUFF instance_dict = invoicing.invoice_instance_to_dict(instance) # get instance as dict + sums # if invoice issued, save the time if getattr(instance, 'invoice_status') in dict(Invoice.INVOICE_STATUS[1:6]) and \ not getattr(inv, 'datetime_issued'): setattr(instance, 'datetime_issued', timezone.now()) # ensure invoice_status is upper case setattr(instance, 'invoice_status', instance.invoice_status.upper()) # # enter marked_as_paid datetime into database if status changed to marked as paid if instance.invoice_status == Invoice.INVOICE_STATUS[5][0]: if not inv.marked_as_paid: # if not originally marked as paid instance.marked_as_paid = timezone.now() # set as marked as paid # set paid_amount to total owed if status is set to paid in full instance.paid_amount = Decimal(instance_dict.get('Total after tax')) # change status if paid_amount is submitted if inv.paid_amount or instance.paid_amount: # if total paid >= total owed, set status to paid in full if inv.paid_amount >= Decimal(instance_dict.get('Total after tax')) or instance.paid_amount >= \ Decimal(instance_dict.get('Total after tax')): instance.invoice_status = Invoice.INVOICE_STATUS[5][0] # enter marked_as_paid datetime into database instance.marked_as_paid = timezone.now() else: # else set status to partially paid instance.invoice_status = Invoice.INVOICE_STATUS[4][0] # check for overdue status todo: move this to an automated django-q later date_due = getattr(instance, 'date_due', None) or getattr(inv, 'date_due') if date_due < timezone.now().date() and \ instance.invoice_status in dict(Invoice.INVOICE_STATUS[:5]): instance.overdue = True # set overdue to True if date_due < now else: instance.overdue = False # ensure set back to False if paid # todo: new feature - if amount paid exceeds amount owed, store client credit note ... @receiver(post_save, sender=Account) def change_uploaded_file_permissions(sender, instance, **kwargs): """ Changes the file permissions of uploaded media files to something sensible """ if getattr(instance, 'logo', False): os.chmod('{}'.format(instance.logo.file.name), 0o664) @receiver(post_save) # don't specify sender, so it is fired on all model saves def update_search_index(sender, instance, created, **kwargs): """ receiver to update the search index whenever a model is saved """ watched_models = [Invoice, Account] # if sender in watched but do NOT trigger when saving the model when saving PDF (no point) if sender in watched_models and not getattr(instance, 'save_pdf', False): update_index.Command().handle(interactive=False) def recurring(instance=None): """ Function to handle the creation of child invoices """ if instance.invoice_number: # ensure child recurring invoice does not produce its own child if int(getattr(instance, 'recurring', False)) not in dict(Invoice.RECURRING[:1]) and getattr(instance, 'parent_invoice', False): raise ValidationError(_('A child invoice cannot itself be recurring')) # ensure invoice is not its own parent try: if getattr(instance, 'invoice_number', False) == getattr(instance, 'parent_invoice', False).invoice_number: raise ValidationError(_('An invoice cannot be it\'s own parent ... stop messing around!')) except AttributeError: pass # thrown if no invoice_number for parent, so can discard as if no parent, no worries! # if status >= ISSUED, call the scheduler to start/stop recurring if getattr(instance, 'invoice_status', False) in dict(Invoice.INVOICE_STATUS[1:]): schedules.recurring_invoice_scheduler(instance=instance) return True return None
Everything you need to know about the Marvin Architectural installation day. This is it! Finally, after picturing it so many times in your head, after watching the plans over and over thinking about ways to bring your ideal home to life, here we are on window installation day. In Marvin Architectural we are deeply committed to bringing you not only the best windows on the market but also a service that meets the high-end quality and design of our products. That’s why we want to share the following steps for you to be aware of how we do this. The first thing you will expect from us is, of course, punctuality. We understand the value of your time and promise to respect it. Your home is your place in the world, and in order to respect your space, we cover your valuables and furniture, protecting your house from any possible damage. As part of Marvin Architectural’s commitment to the environment, we will remove and recycle your old windows as part of the company’s Corporate Social Responsibility (CSR) to the industry and the customer. Once everything is set, it’s time to install your new windows. After more than 25 years of experience and expertise in the window market, our professional installation team will ensure that this experience will exceed your expectations. This is the day that you stamp your personality on your home. Window Installation is completed. What now? After installing, there’s an important step in the process and that’s cleaning everything. The company policy is to leave your site spotless. As the final step, our installation manager will do a full inspection of each unit, ensuring that installation procedure has been followed and performance ratings are accurate and all the technicals aspects of the product have been tested. Your satisfaction is our main concern, and here at Marvin Architectural, we take customer satisfaction very seriously, helping us improve in every way possible the customized service we deliver. Your salesperson will invite you to give us a review of your overall experience with every aspect of the service you have received. Here’s a checklist including every step involved in the window installation process. Does your window company provide all these services?
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """HTTP helpers mock functionality.""" from six.moves import http_client class ResponseMock(dict): """Mock HTTP response""" def __init__(self, vals=None): if vals is None: vals = {} self.update(vals) self.status = int(self.get('status', http_client.OK)) class HttpMock(object): """Mock of HTTP object.""" def __init__(self, headers=None, data=None): """HttpMock constructor. Args: headers: dict, header to return with response """ if headers is None: headers = {'status': http_client.OK} self.data = data self.response_headers = headers self.headers = None self.uri = None self.method = None self.body = None self.headers = None self.requests = 0 def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): self.uri = uri self.method = method self.body = body self.headers = headers self.redirections = redirections self.requests += 1 return ResponseMock(self.response_headers), self.data class HttpMockSequence(object): """Mock of HTTP object with multiple return values. Mocks a sequence of calls to request returning different responses for each call. Create an instance initialized with the desired response headers and content and then use as if an HttpMock instance:: http = HttpMockSequence([ ({'status': '401'}, b''), ({'status': '200'}, b'{"access_token":"1/3w","expires_in":3600}'), ({'status': '200'}, 'echo_request_headers'), ]) resp, content = http.request('http://examples.com') There are special values you can pass in for content to trigger behavours that are helpful in testing. * 'echo_request_headers' means return the request headers in the response body * 'echo_request_body' means return the request body in the response body """ def __init__(self, iterable): """HttpMockSequence constructor. Args: iterable: iterable, a sequence of pairs of (headers, body) """ self._iterable = iterable self.requests = [] def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): resp, content = self._iterable.pop(0) self.requests.append({ 'method': method, 'uri': uri, 'body': body, 'headers': headers, }) # Read any underlying stream before sending the request. body_stream_content = (body.read() if getattr(body, 'read', None) else None) if content == 'echo_request_headers': content = headers elif content == 'echo_request_body': content = (body if body_stream_content is None else body_stream_content) return ResponseMock(resp), content class CacheMock(object): def __init__(self): self.cache = {} def get(self, key, namespace=''): # ignoring namespace for easier testing return self.cache.get(key, None)
Officers investigated after a Pine Drive caller reported Monday at 8:58 a.m. that the neighbors’ pickup truck tires were slashed. Officers arrested John Michael Vauthier of Havre, 41, on a Justice or City court warrant Monday at 11:17 a.m. on Third Street. Officers arrested three people during a motor vehicle stop Monday at 12:25 p.m. on Sixth Avenue. No further information was provided.
""" This demo demonstrates how to train a GPy model using the pymcmc module. Author: Ilias Bilionis Date: 3/20/2014 """ import GPy import pymcmc as pm import numpy as np import matplotlib.pyplot as plt # Construct a GPy Model (anything really..., here we are using a regression # example) model = GPy.examples.regression.olympic_marathon_men(optimize=False, plot=False) # Look at the model before it is trained: print 'Model before training:' print str(model) # Pick a proposal for MCMC (here we pick a Metropolized Langevin Proposal proposal = pm.MALAProposal(dt=1.) # Construct a Metropolis Hastings object mcmc = pm.MetropolisHastings(model, # The model you want to train proposal=proposal, # The proposal you want to use db_filename='demo_1_db.h5')# The HDF5 database to write the results # Look at the model now: We have automatically added uninformative priors # by looking at the constraints of the parameters print 'Model after adding priors:' print str(model) # Now we can sample it: mcmc.sample(100000, # Number of MCMC steps num_thin=100, # Number of steps to skip num_burn=1000, # Number of steps to burn initially verbose=True) # Be verbose or not # Here is the model at the last MCMC step: print 'Model after training:' print str(model) # Let's plot the results: model.plot(plot_limits=(1850, 2050)) a = raw_input('press enter...')
This entry was posted on Saturday, May 30th, 2009 at 10:28 am and is filed under Reader's Recommendations. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. requirements, so I feel I really did my homework and was good to go! people will not go through what we did. documents must be presented in original and copy. in the procedure of entering Mexico. addressed in addition to RABIES – very, very important. I have been looking for info on shipping two puppies to Mexico City. I need to know where to get a health certificate international packet.The puppies will be almost 6 months. The most pet unfriendly city in Mexico has to be San Luie Potosi. We went to a hotel that was listed as being pet friendly (the Maria Delores), asked at the desk when we checked in if it was OK to have our little Bichon, after settling in to our room the manager called to tell us we had to leave as dogs were not allowed. We went up and down the entire hotel strip and could not find a single hotel, even down to the rent by the hour places. Finally a person at the Marriot called around. We ended up at The Westin, very luxurious, they were very gracious about the dog and even offered to provide a bed for her. Only about $100 more than we planned to spend. They offer a very pet friendly budget treks to numerous beaches, mountains and hot springs in their vegetable oil powered beach bus. Just thought I’d let you know that there’s a dog-friendly eco-tourism company that runs bus trips into Baja on their school bus, called Baja Trek. I’ve taken my border collie on board a few times now, to the hot springs and Pacific coast beaches. They are super friendly! Accommodation is mainly camping but sometimes hostels. Dogs are welcome on pretty much any trip except for the Cantina crawl, I believe.
from collections import defaultdict from regparser.citations import Label from regparser.layer.layer import Layer from regparser.tree import struct from regparser.tree.interpretation import text_to_labels class Interpretations(Layer): """Supplement I (interpretations) provides (sometimes very lengthy) extra information about particular paragraphs. This layer provides those interpretations.""" shorthand = 'interpretations' def __init__(self, *args, **kwargs): Layer.__init__(self, *args, **kwargs) self.lookup_table = defaultdict(list) def pre_process(self): """Create a lookup table for each interpretation""" def per_node(node): if (node.node_type != struct.Node.INTERP or node.label[-1] != struct.Node.INTERP_MARK): return # Always add a connection based on the interp's label self.lookup_table[tuple(node.label[:-1])].append(node) # Also add connections based on the title for label in text_to_labels(node.title or '', Label.from_node(node), warn=False): label = tuple(label[:-1]) # Remove Interp marker if node not in self.lookup_table[label]: self.lookup_table[label].append(node) struct.walk(self.tree, per_node) def process(self, node): """Is there an interpretation associated with this node? If yes, return the associated layer information. @TODO: Right now, this only associates if there is a direct match. It should also associate if any parents match""" label = tuple(node.label) if self.lookup_table[label]: # default dict; will always be present interp_labels = [n.label_id() for n in self.lookup_table[label] if not self.empty_interpretation(n)] return [{'reference': l} for l in interp_labels] or None def empty_interpretation(self, interp): """We don't want to include empty (e.g. \n\n) nodes as interpretations unless their children are subparagraphs. We distinguish subparagraphs from structural children by checking the location of the 'Interp' delimiter.""" if interp.text.strip(): return False return all(not child.label or child.label[-1] == struct.Node.INTERP_MARK for child in interp.children)
Incontinence is a source of discomfort and embarrassment to many women, but there are treatments that can help. As leading incontinence specialists in Phoenix, AZ, the team at Southeast Valley Urology are skilled in the diagnosis and treatment of incontinence. Using advanced approaches for patients, our board certified urologists are highly trained in the latest technology and have decades of experience treating female urinary incontinence.
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PySCAP is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging import re from scap.Collector import Collector, ArgumentException logger = logging.getLogger(__name__) class ResolvePathFilenameCollector(Collector): def __init__(self, host, args): super(ResolvePathFilenameCollector, self).__init__(host, args) if 'path' not in args: raise ArgumentException('ResolvePathFilenameCollector requires path argument') if 'filename' not in args: raise ArgumentException('ResolvePathFilenameCollector requires filename argument') for i in ('value_datatypes', 'value_masks', 'value_operations'): if i not in args: raise ArgumentException('ResolvePathFilenameCollector requires ' + i + ' argument') if args['value_datatypes']['path'] != 'string': raise ArgumentException('ResolvePathFilenameCollector requires string path') if args['value_datatypes']['filename'] != 'string': raise ArgumentException('ResolvePathFilenameCollector requires string filename') # NOTE: operation should be already validated by EntityObjectType # TODO the max_depth behavior MUST not be used when a pattern match is used with a path entity # TODO the recurse behavior MUST not be used when a pattern match is used with a path entity # TODO the recurse_direction behavior MUST not be used when a pattern match is used with a path entity # the recurse_file_system behavior MUST not be set to 'defined' when a pattern match is used with a path entity if args['value_operations']['path'] == 'pattern match' and args['behavior_recurse_file_system'] == 'defined': raise ArgumentException('ResolvePathFilenameCollector behavior_recurse_file_system set to defined with path pattern match operation') def collect(self): if self.args['value_operations']['path'] in ['equals', 'case insensitive equals']: # check if path exists col = self.host.load_collector('DirectoryExistsCollector', {'path': self.args['path']}) if not col.collect(): raise FileNotFoundError(self.args['path'] + ' was not found') paths = [self.args['path']] elif self.args['value_operations']['path'] in ['not equal', 'case insensitive not equal']: raise NotImplementedError(self.args['value_operations']['path'] + ' operation not supported for ResolvePathFilenameCollector') elif self.args['value_operations']['path'] == 'pattern match': path = self.args['path'] logger.debug('Matching pattern ' + path) # strip off leading ^ or trailing $ as they are assumed if path.startswith('^'): path = path[1:] if path.endswith('$'): path = path[:-1] paths = [] m = re.match(r'^([a-zA-Z]):\\', path) if m: # C:\ local abs path drive = m.group(1) + ':\\' logger.debug('Absolute path on drive ' + drive) cmd = "Get-PSDrive -PSProvider FileSystem | % { $_.Root }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if drive not in out_lines: # don't have the drive, so path won't match raise FileNotFoundError(self.args['path'] + ' was not found') start = m.group(1) + ':' fp = path.split('\\') fp = fp[1:] for p in fp: logger.debug('Checking if path component ' + p + ' exists') cmd = "Get-Item -LiteralPath '" + start + '\\' + p + "' -ErrorAction Ignore | % { $_.Name }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code == 0 and len(out_lines) == 1: logger.debug(p + ' exists') start = start + '\\' + p else: logger.debug(p + ' does not exist; using ' + start + ' as starting point') break logger.debug('Recursing from ' + start) cmd = "Get-ChildItem -LiteralPath '" + start + "' -Recurse -ErrorAction Ignore | % { $_.FullName }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code != 0 or len(out_lines) < 1: raise FileNotFoundError(self.args['path'] + ' was not found') for l in out_lines: m = re.fullmatch(self.args['path'], l) if m: logger.debug(l + ' matches ' + self.args['path']) paths.append(l) elif path.startswith(r'\\\\\?\\UNC\\'): # \\?\UNC\ extended UNC length path raise NotImplementedError('extended UNC paths are not yet supported') elif path.startswith(r'\\\\\?\\'): # \\?\ extended length path raise NotImplementedError('extended paths are not yet supported') elif path.startswith(r'\\\\\.\\'): # \\.\ device namespace path raise NotImplementedError('device paths are not yet supported') elif path.startswith(r'\\\\'): # \\server\share UNC path m = re.match(r'^\\\\([^\\]+)\\') if not m: raise ArgumentException('Invalid UNC path: ' + path) server = m.group(1) logger.debug('UNC path on server ' + server) start = '\\\\' + server fp = path.split('\\') fp = fp[3:] for p in fp: logger.debug('Checking if path component ' + p + ' exists') cmd = "Get-Item -LiteralPath '" + start + '\\' + p + "' -ErrorAction Ignore | % { $_.Name }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code == 0 and len(out_lines) == 1: logger.debug(p + ' exists') start = start + '\\' + p else: logger.debug(p + ' does not exist; using ' + start + ' as starting point') break logger.debug('Recursing from ' + start) cmd = "Get-ChildItem -LiteralPath '" + start + "' -Recurse -ErrorAction Ignore | % { $_.FullName }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code != 0 or len(out_lines) < 1: raise FileNotFoundError(self.args['path'] + ' was not found') for l in out_lines: m = re.fullmatch(self.args['path'], l) if m: logger.debug(l + ' matches ' + self.args['path']) paths.append(l) elif path.startswith(r'\.\.\\'): # ..\ relative parent path cmd = "(Get-Item -Path '..\\' -Verbose).FullName" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') start = out_lines[0] logger.debug('Recursing from ' + start) cmd = "Get-ChildItem -LiteralPath '" + start + "' -Recurse -ErrorAction Ignore | % { $_.FullName }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code != 0 or len(out_lines) < 1: raise FileNotFoundError(self.args['path'] + ' was not found') for l in out_lines: m = re.fullmatch(self.args['path'], l.replace(start, '..')) if m: logger.debug(l + ' matches ' + self.args['path']) paths.append(l) elif path.startswith(r'\.\\'): # .\ relative current path cmd = "(Get-Item -Path '.\\' -Verbose).FullName" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') start = out_lines[0] logger.debug('Recursing from ' + start) cmd = "Get-ChildItem -LiteralPath '" + start + "' -Recurse -ErrorAction Ignore | % { $_.FullName }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code != 0 or len(out_lines) < 1: raise FileNotFoundError(self.args['path'] + ' was not found') for l in out_lines: m = re.fullmatch(self.args['path'], l.replace(start, '.')) if m: logger.debug(l + ' matches ' + self.args['path']) paths.append(l) else: raise ArgumentException('Invalid path: ' + path) # TODO imp behavior_windows_view filepaths = [] for path in paths: if self.args['behavior_recurse_file_system'] == 'local' and path.startswith('\\\\'): continue if self.args['value_operations']['filename'] in ['equals', 'case insensitive equals']: filepaths.extend(self.search_path_for(path, self.args['filename'], '-eq', self.args['behavior_max_depth'], self.args['behavior_recurse_direction'])) elif self.args['value_operations']['filename'] in ['not equal', 'case insensitive not equal']: raise NotImplementedError(self.args['value_operations']['filename'] + ' operation not supported for ResolvePathFilenameCollector') elif self.args['value_operations']['filename'] == 'pattern match': filepaths.extend(self.search_path_for(path, self.args['filename'], '-match', self.args['behavior_max_depth'], self.args['behavior_recurse_direction'])) else: raise NotImplementedError('Unknown operation not supported for ResolvePathFilenameCollector filename') return filepaths def search_path_for(self, path, filename, operator, remaining_depth, direction): logger.debug('Looking for ' + filename + ' in ' + path) if remaining_depth == 0: return [] if direction == 'up': raise NotImplementedError('Upward recursion is not yet implemented') # TODO implement link traversal validation if remaining_depth == -1: cmd = "Get-ChildItem -Recurse -LiteralPath '" + path.replace("'", "\\'") + "'" else: cmd = "Get-ChildItem -LiteralPath '" + path.replace("'", "\\'") + "'" cmd = cmd + " | % {" cmd = cmd + "$_.FullName + ',' + " cmd = cmd + "($_.Mode[0] -eq 'd') + ',' + " cmd = cmd + "($_.Name " + operator + " '" + filename.replace("'", "\\'") + "')" cmd = cmd + " }" return_code, out_lines, err_lines = self.host.exec_command('powershell -Command "' + cmd.replace('\"', '\\"') + '"') if return_code != 0: raise FileNotFoundError('Error finding ' + filename + ' in ' + path) filepaths = [] for l in out_lines: logger.debug('Got ' + l + ' in ' + path) fullname, is_dir, matches = l.rsplit(',', 3) is_dir = is_dir == 'True' matches = matches == 'True' if is_dir and direction == 'down' and remaining_depth >= 1: filepaths.extend(self.search_path_for(fullname, filename, operator, remaining_depth - 1, direction)) if matches: filepaths.append(fullname) return filepaths
Find top mommies in Cali. Identify the most popular Instagram accounts on Heepsy. Want to discover the 148 mommies we've identified in Cali in 2019?
import traceback from typing import Any, Dict, List, Tuple, Union import urllib3 from dateparser import parse from pytz import utc from requests_ntlm import HttpNtlmAuth import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * urllib3.disable_warnings() SEVERITY_TRANSLATION = { 'Low': 1, 'Medium': 2, 'High': 3 } class Client(BaseClient): def get_suspicious_activity_request(self, suspicious_activity_id: str = '') -> Dict[str, Any]: return self._http_request( method='GET', url_suffix=f'/suspiciousActivities/{suspicious_activity_id}' ) def get_suspicious_activity_details_request(self, suspicious_activity_id: str) -> Dict[str, Any]: return self._http_request( method='GET', url_suffix=f'/suspiciousActivities/{suspicious_activity_id}/details' ) def update_suspicious_activity_status_request(self, suspicious_activity_id: str, suspicious_activity_status: str ) -> Dict[str, Any]: body = { 'Status': suspicious_activity_status } return self._http_request( method='POST', url_suffix=f'/suspiciousActivities/{suspicious_activity_id}', json_data=body, ok_codes=(204,), resp_type='text' ) def delete_suspicious_activity_request(self, suspicious_activity_id: str) -> Dict[str, Any]: body = { 'shouldDeleteSametype': False } params = { 'shouldDeleteSameType': 'false' } return self._http_request( method='DELETE', url_suffix=f'/suspiciousActivities/{suspicious_activity_id}', json_data=body, params=params, ok_codes=(204,), resp_type='text' ) def get_monitoring_alert_request(self) -> Dict[str, Any]: return self._http_request( method='GET', url_suffix='/monitoringAlerts' ) def get_entity_request(self, entity_id: str) -> Dict[str, Any]: return self._http_request( method='GET', url_suffix=f'/uniqueEntities/{entity_id}' ) def get_entity_profile_request(self, entity_id: str) -> Dict[str, Any]: return self._http_request( method='GET', url_suffix=f'/uniqueEntities/{entity_id}/profile' ) def test_module(client: Client) -> str: client.get_monitoring_alert_request() return 'ok' def get_suspicious_activity(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]: suspicious_activity_id = args.get('id', '') suspicious_activity_status = argToList(args.get('status', '')) suspicious_activity_severity = argToList(args.get('severity', '')) suspicious_activity_type = argToList(args.get('type', '')) suspicious_activity_start_time = parse(args.get('start_time', '')) suspicious_activity_end_time = parse(args.get('end_time', '')) limit = int(args.get('limit', '50')) raw_suspicious_activity = client.get_suspicious_activity_request(suspicious_activity_id) suspicious_activity_output = [] if raw_suspicious_activity: suspicious_activities = raw_suspicious_activity if isinstance(raw_suspicious_activity, list) \ else [raw_suspicious_activity] if not suspicious_activity_id and \ any([suspicious_activity_status, suspicious_activity_severity, suspicious_activity_type, suspicious_activity_start_time, suspicious_activity_end_time]): for activity in suspicious_activities: if suspicious_activity_status and activity.get('Status') not in suspicious_activity_status: continue if suspicious_activity_severity and activity.get('Severity') not in suspicious_activity_severity: continue if suspicious_activity_type and activity.get('Type') not in suspicious_activity_type: continue if suspicious_activity_start_time and parse(activity.get('StartTime')).replace(tzinfo=utc) < \ suspicious_activity_start_time.replace(tzinfo=utc): continue if suspicious_activity_end_time and parse(activity.get('EndTime')).replace(tzinfo=utc) > \ suspicious_activity_end_time.replace(tzinfo=utc): continue suspicious_activity_output.append(activity) else: suspicious_activity_output = suspicious_activities suspicious_activity_output = suspicious_activity_output[:limit] if suspicious_activity_output: readable_output = tableToMarkdown( 'Microsoft Advanced Threat Analytics Suspicious Activity', suspicious_activity_output, headers=['Id', 'Type', 'Status', 'Severity', 'StartTime', 'EndTime'], removeNull=True ) if suspicious_activity_id: suspicious_activity_details = client.get_suspicious_activity_details_request(suspicious_activity_id) details_records = suspicious_activity_details.get('DetailsRecords', []) if details_records: suspicious_activity_output[0]['DetailsRecords'] = details_records readable_output += tableToMarkdown( 'Details Records', details_records, removeNull=True ) return CommandResults( readable_output=readable_output, outputs_prefix='MicrosoftATA.SuspiciousActivity', outputs_key_field='Id', outputs=suspicious_activity_output ) else: return 'No results found.' def update_suspicious_activity_status(client: Client, args: Dict[str, str]) -> str: suspicious_activity_id = args.get('id', '') suspicious_activity_status = args.get('status', '') if suspicious_activity_status == 'Delete': client.delete_suspicious_activity_request(suspicious_activity_id) return f'Suspicious activity {suspicious_activity_id} was deleted successfully.' else: client.update_suspicious_activity_status_request(suspicious_activity_id, suspicious_activity_status) return f'Suspicious activity {suspicious_activity_id} status was updated to ' \ f'{suspicious_activity_status} successfully.' def get_monitoring_alert(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]: monitoring_alert_status = argToList(args.get('status', '')) monitoring_alert_severity = argToList(args.get('severity', '')) monitoring_alert_type = argToList(args.get('type', '')) monitoring_alert_start_time = parse(args.get('start_time', '')) monitoring_alert_end_time = parse(args.get('end_time', '')) limit = int(args.get('limit', '50')) raw_monitoring_alert = client.get_monitoring_alert_request() monitoring_alert_output = [] if raw_monitoring_alert: monitoring_alerts = raw_monitoring_alert if isinstance(raw_monitoring_alert, list) else [raw_monitoring_alert] if any([monitoring_alert_status, monitoring_alert_severity, monitoring_alert_type, monitoring_alert_start_time, monitoring_alert_end_time]): for alert in monitoring_alerts: if monitoring_alert_status and alert.get('Status') not in monitoring_alert_status: continue if monitoring_alert_severity and alert.get('Severity') not in monitoring_alert_severity: continue if monitoring_alert_type and alert.get('Type') not in monitoring_alert_type: continue if monitoring_alert_start_time and parse(alert.get('StartTime')).replace(tzinfo=utc) < \ monitoring_alert_start_time.replace(tzinfo=utc): continue if monitoring_alert_end_time and parse(alert.get('EndTime')).replace(tzinfo=utc) > \ monitoring_alert_end_time.replace(tzinfo=utc): continue monitoring_alert_output.append(alert) else: monitoring_alert_output = monitoring_alerts monitoring_alert_output = monitoring_alert_output[:limit] if monitoring_alert_output: readable_output = tableToMarkdown( 'Microsoft Advanced Threat Analytics Monitoring Alert', monitoring_alert_output, headers=['Id', 'Type', 'Status', 'Severity', 'StartTime', 'EndTime'], removeNull=True ) return CommandResults( readable_output=readable_output, outputs_prefix='MicrosoftATA.MonitoringAlert', outputs_key_field='Id', outputs=monitoring_alert_output ) else: return 'No results found.' def get_entity(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]: entity_id = args.get('id', '') entity = client.get_entity_request(entity_id) if entity: readable_output = tableToMarkdown( f'Microsoft Advanced Threat Analytics Entity {entity_id}', entity, headers=['Id', 'SystemDisplayName', 'DistinguishedName', 'UpnName', 'Type', 'CreationTime'], removeNull=True ) entity_profile = client.get_entity_profile_request(entity_id) if entity_profile: entity['Profile'] = entity_profile readable_output += tableToMarkdown( 'Entity Profile', entity_profile, headers=['Type', 'SuspiciousActivitySeverityToCountMapping', 'UpdateTime', 'IsBehaviorChanged'], removeNull=True ) return CommandResults( readable_output=readable_output, outputs_prefix='MicrosoftATA.Entity', outputs_key_field='Id', outputs=entity ) else: return 'No results found.' def fetch_incidents( client: Client, last_run: Dict[str, str], first_fetch_time: str, max_results: int, activity_status_to_fetch: List, min_severity: int, activity_type_to_fetch: List ) -> Tuple[Dict[str, str], List[Dict[str, str]]]: last_fetch = last_run.get('last_fetch', '') if last_run.get('last_fetch') else first_fetch_time last_fetch_dt = parse(last_fetch).replace(tzinfo=utc) latest_start_time = parse(last_fetch).replace(tzinfo=utc) incidents_fetched = 0 incidents: List[Dict[str, Any]] = [] suspicious_activities = client.get_suspicious_activity_request() suspicious_activities_list = suspicious_activities if isinstance(suspicious_activities, list) \ else [suspicious_activities] demisto.debug(suspicious_activities_list) for activity in suspicious_activities_list: if incidents_fetched == max_results: break activity_id = activity.get('Id', '') activity_status = activity.get('Status', '') activity_type = activity.get('Type', '') activity_severity = activity.get('Severity', '') if activity_status_to_fetch and activity_status not in activity_status_to_fetch: demisto.debug(f'Skipping suspicious activity {activity_id} with status {activity_status}') continue if activity_type_to_fetch and activity_type not in activity_type_to_fetch: demisto.debug(f'Skipping suspicious activity {activity_id} with type {activity_type}') continue if SEVERITY_TRANSLATION[activity_severity] < min_severity: demisto.debug(f'Skipping suspicious activity {activity_id} with severity {activity_severity}') continue activity_start_time = activity.get('StartTime', '') activity_start_time_dt = parse(activity_start_time).replace(tzinfo=utc) if activity_start_time_dt > latest_start_time: incidents.append({ 'name': f'{activity_type} - {activity_id}', 'occurred': activity_start_time, 'rawJSON': json.dumps(activity) }) if activity_start_time_dt > last_fetch_dt: last_fetch_dt = activity_start_time_dt last_fetch = activity_start_time incidents_fetched += 1 next_run = {'last_fetch': last_fetch} return next_run, incidents def main() -> None: params = demisto.params() base_url = urljoin(params['url'], '/api/management') username = params['credentials']['identifier'] password = params['credentials']['password'] verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) demisto.debug(f'Command being called is {demisto.command()}') try: client = Client( base_url=base_url, auth=HttpNtlmAuth(username, password), verify=verify_certificate, proxy=proxy ) if demisto.command() == 'test-module': result = test_module(client) return_results(result) elif demisto.command() == 'fetch-incidents': next_run, incidents = fetch_incidents( client=client, last_run=demisto.getLastRun(), first_fetch_time=params.get('first_fetch', '3 days'), max_results=int(params.get('max_fetch', '50')), activity_status_to_fetch=params.get('activity_status', ['Open']), min_severity=SEVERITY_TRANSLATION[params.get('min_severity', 'Low')], activity_type_to_fetch=argToList(params.get('activity_type', '')) ) demisto.setLastRun(next_run) demisto.incidents(incidents) elif demisto.command() == 'ms-ata-suspicious-activities-list': return_results(get_suspicious_activity(client, demisto.args())) elif demisto.command() == 'ms-ata-suspicious-activity-status-set': return_results(update_suspicious_activity_status(client, demisto.args())) elif demisto.command() == 'ms-ata-monitoring-alerts-list': return_results(get_monitoring_alert(client, demisto.args())) elif demisto.command() == 'ms-ata-entity-get': return_results(get_entity(client, demisto.args())) except Exception as e: demisto.error(traceback.format_exc()) return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}') if __name__ in ('__main__', '__builtin__', 'builtins'): main()
I mean I hope somebody out there can hear this right here. You're gonna drive me crazy (don't do that). You're gonna drive me mad (don't do that). I said there's truth in that. Yo, what better things can you hear them sing? Aint this like a celebration? For the boy playing ball on the block. But I came with a plot, plot. I've prolly moved onto my next axis. And if she calling, I don't care about what my ex asks. Why, cause I'm in a lab like Bill Nye the Science Guy. I could jump overtop of the Empire State building, just glide. You see a train, don't be the fool that jumps on the rail. High on the scale, if a nail girl said it. I am well endowed like Harvard and Yale. I'm getting shows booked, I be the noblest. I profit off my topic hits. Periodically, I'm in my element, phosphorus. I'm prosperous, say we loud and too rockerish. Pro, how long are you lockin this? I say until apocalypse, I got this shhh. You're gonna drive me crazy. You're gonna drive me mad. I swear there's truth in that. Youve got an angel on your shoulder. Making hairpins out of glass. 14) Mac Miller - Party On Fifth Ave.
#!/usr/bin/python """LDAP Directory Management, wrapper for python-ldap (http://www.python-ldap.org). This module provides high level control over an LDAP Directory. Some code was originally built on examples available here: http://www.grotan.com/ldap/python-ldap-samples.html Copyright (c) 2014 Derak Berreyesa Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __author__ = "Derak Berreyesa (github.com/derak)" __version__ = "1.0" import sys, json import ldap import ldap.modlist as modlist class Directory(object): def __init__(self): self.result = {} self.l = None def connect(self, url, username, password): try: # Create a new user in Active Directory ldap.set_option(ldap.OPT_REFERRALS, 0) # Allows us to have a secure connection ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, 0) # Open a connection self.l = ldap.initialize(url) # Bind/authenticate with a user with apropriate rights to add objects self.l.simple_bind_s(username, password) except ldap.LDAPError, e: sys.stderr.write('Error connecting to LDAP server: ' + str(e) + '\n') self.result['status'] = 'Error connecting to LDAP server: ' + str(e) + '\n' print json.dumps(self.result) sys.exit(1) def add_user(self, dn, attrs): try: # Convert our dict to nice syntax for the add-function using modlist-module ldif = modlist.addModlist(attrs) # Add user self.l.add_s(dn,ldif) except ldap.LDAPError, e: sys.stderr.write('Error with LDAP add_user: ' + str(e) + '\n') self.result['status'] = 'Error with LDAP add_user: ' + str(e) + '\n' print json.dumps(self.result) sys.exit(1) def add_user_to_groups(self, dn, group_dn_list): try: # Add user to groups as member mod_attrs = [( ldap.MOD_ADD, 'member', dn )] for g in group_dn_list: self.l.modify_s(g, mod_attrs) except ldap.LDAPError, e: sys.stderr.write('Error: adding user to group(s): ' + str(e) + '\n') self.result['status'] = 'Error: adding user to group(s): ' + str(e) + '\n' print json.dumps(self.result) sys.exit(1) def set_password(self, dn, password): # HERE YOU MAKE THE utf-16-le encode password unicode_pass = unicode('\"' + password + '\"', 'iso-8859-1') password_value = unicode_pass.encode('utf-16-le') # change the atribute in the entry you just created add_pass = [(ldap.MOD_REPLACE, 'unicodePwd', [password_value])] try: self.l.modify_s(dn, add_pass) except ldap.LDAPError, error_message: self.result['status'] = 'Error: could not change password: ' + str(error_message) + '\n' print json.dumps(self.result) sys.exit(1) else: self.result['status'] = 'Successfully changed password \n' def modify_user(self, dn, flag): """Modify user, flag is userAccountControl property""" # 512 will set user account to enabled # change the user to enabled mod_acct = [(ldap.MOD_REPLACE, 'userAccountControl', str(flag))] try: self.l.modify_s(dn, mod_acct) except ldap.LDAPError, error_message: self.result['status'] = 'Error: could not modify user: ' + str(error_message) + '\n' print json.dumps(self.result) sys.exit(1) else: self.result['status'] = 'Successfully modified user \n' def print_users(self, base_dn, attrs): filter = '(objectclass=person)' users = self.l.search_s(base_dn, ldap.SCOPE_SUBTREE, filter, attrs) for row in users: print row def disconnect(self): self.l.unbind_s() def get_result(self): return self.result if __name__ == '__main__': print 'This is directory.py'
A WW2 Spitfire that crashed just miles from its hero pilot's home has been dug up after 77 years. Sgt Emrys Ivor Lewis was killed after losing control of his Mark 1 during the Battle Of Britain on 4 July 1940. On Friday his family watched as the remains of the famous fighter plane was unearthed in a field in South Owersby, Lincs. Tragically, Sgt Lewis was just 11 miles from his base at RAF Kirton in Lindsey, Gainsborough, Lincs., when he crashed. He was buried with full military honours in his hometown of Llannerchymedd, Angelsey, North Wales, on July 11, 1940, but the plane's wreckage was left at the scene. It was buried under 20ft of earth which was painstakingly removed by archaeologists over two before the wreckage — including the famous Rolls Royce Merlin engine — was exhumed. Military records show Sgt Lewis' Spitfire had been used in the Dunkirk evacuation before defending Britain from the Nazi's aerial onslaught. Sgt Lewis' niece Beryl Wilson, 82, and her two daughters Karen and Janet made an emotional pilgrimage to witness the recovery of the plane. Gareth Jones, whose team of archaeologists led the excavation along with a team from Winchester University, said: "It was both emotional and exciting - a truly memorable moment for everyone involved." A minute's silence was held in memory of Sgt Lewis along with a Spitfire flypast from RAF Duxford. The excavation was also filmed as part of a documentary which is expected to be shown next year. A military report into the fatal crash at the time said: "On 4th July 1940 the pilot of this aircraft was undertaking a gunnery training flight and when he was flying in cloud he lost control, the aircraft dived into the ground near Withernsea. "Sadly he was killed in the resulting crash but the exact location is not yet known."
from base64 import b64decode import json import logging from dateutil import parser from redash.query_runner import * from redash.utils import JSONEncoder logger = logging.getLogger(__name__) try: import gspread from oauth2client.client import SignedJwtAssertionCredentials enabled = True except ImportError: enabled = False def _load_key(filename): with open(filename, "rb") as f: return json.loads(f.read()) def _guess_type(value): if value == '': return TYPE_STRING try: val = int(value) return TYPE_INTEGER except ValueError: pass try: val = float(value) return TYPE_FLOAT except ValueError: pass if unicode(value).lower() in ('true', 'false'): return TYPE_BOOLEAN try: val = parser.parse(value) return TYPE_DATETIME except ValueError: pass return TYPE_STRING def _value_eval_list(value): value_list = [] for member in value: if member == '' or member is None: val = None value_list.append(val) continue try: val = int(member) value_list.append(val) continue except ValueError: pass try: val = float(member) value_list.append(val) continue except ValueError: pass if unicode(member).lower() in ('true', 'false'): if unicode(member).lower() == 'true': value_list.append(True) else: value_list.append(False) continue try: val = parser.parse(member) value_list.append(val) continue except ValueError: pass value_list.append(member) return value_list HEADER_INDEX = 0 class WorksheetNotFoundError(Exception): def __init__(self, worksheet_num, worksheet_count): message = "Worksheet number {} not found. Spreadsheet has {} worksheets. Note that the worksheet count is zero based.".format(worksheet_num, worksheet_count) super(WorksheetNotFoundError, self).__init__(message) def parse_worksheet(worksheet): if not worksheet: return {'columns': [], 'rows': []} column_names = [] columns = [] duplicate_counter = 1 for j, column_name in enumerate(worksheet[HEADER_INDEX]): if column_name in column_names: column_name = u"{}{}".format(column_name, duplicate_counter) duplicate_counter += 1 column_names.append(column_name) columns.append({ 'name': column_name, 'friendly_name': column_name, 'type': TYPE_STRING }) if len(worksheet) > 1: for j, value in enumerate(worksheet[HEADER_INDEX+1]): columns[j]['type'] = _guess_type(value) rows = [dict(zip(column_names, _value_eval_list(row))) for row in worksheet[HEADER_INDEX + 1:]] data = {'columns': columns, 'rows': rows} return data def parse_spreadsheet(spreadsheet, worksheet_num): worksheets = spreadsheet.worksheets() worksheet_count = len(worksheets) if worksheet_num >= worksheet_count: raise WorksheetNotFoundError(worksheet_num, worksheet_count) worksheet = worksheets[worksheet_num].get_all_values() return parse_worksheet(worksheet) class GoogleSpreadsheet(BaseQueryRunner): @classmethod def annotate_query(cls): return False @classmethod def type(cls): return "google_spreadsheets" @classmethod def enabled(cls): return enabled @classmethod def configuration_schema(cls): return { 'type': 'object', 'properties': { 'jsonKeyFile': { "type": "string", 'title': 'JSON Key File' } }, 'required': ['jsonKeyFile'], 'secret': ['jsonKeyFile'] } def __init__(self, configuration): super(GoogleSpreadsheet, self).__init__(configuration) def _get_spreadsheet_service(self): scope = [ 'https://spreadsheets.google.com/feeds', ] key = json.loads(b64decode(self.configuration['jsonKeyFile'])) credentials = SignedJwtAssertionCredentials(key['client_email'], key["private_key"], scope=scope) spreadsheetservice = gspread.authorize(credentials) return spreadsheetservice def test_connection(self): self._get_spreadsheet_service() def run_query(self, query, user): logger.debug("Spreadsheet is about to execute query: %s", query) values = query.split("|") key = values[0] #key of the spreadsheet worksheet_num = 0 if len(values) != 2 else int(values[1])# if spreadsheet contains more than one worksheet - this is the number of it try: spreadsheet_service = self._get_spreadsheet_service() spreadsheet = spreadsheet_service.open_by_key(key) data = parse_spreadsheet(spreadsheet, worksheet_num) json_data = json.dumps(data, cls=JSONEncoder) error = None except gspread.SpreadsheetNotFound: error = "Spreadsheet ({}) not found. Make sure you used correct id.".format(key) json_data = None return json_data, error register(GoogleSpreadsheet)
The place is located at a distance of about 82 km from Gorakhpur and can be accessed from Gorakhpur by NH-29A up to Eksarwa & then 15 km distance from here. The place is said to be the place of Buddha’s maternal grandfather. The mound is spread over an area of 82.5 acres. The site is protected by the Archaeological Department of U.P. and is yet to be explored extensively.
# -*- coding: utf-8 -*- """ Discord API Wrapper ~~~~~~~~~~~~~~~~~~~ A basic wrapper for the Discord API. :copyright: (c) 2015-2019 Rapptz :license: MIT, see LICENSE for more details. """ __title__ = 'discord' __author__ = 'Rapptz' __license__ = 'MIT' __copyright__ = 'Copyright 2015-2019 Rapptz' __version__ = '1.3.0a' from collections import namedtuple import logging from .client import Client from .appinfo import AppInfo from .user import User, ClientUser, Profile from .emoji import Emoji from .partial_emoji import PartialEmoji from .activity import * from .channel import * from .guild import Guild, SystemChannelFlags from .relationship import Relationship from .member import Member, VoiceState from .message import Message, Attachment from .asset import Asset from .errors import * from .calls import CallMessage, GroupCall from .permissions import Permissions, PermissionOverwrite from .role import Role from .file import File from .colour import Color, Colour from .invite import Invite, PartialInviteChannel, PartialInviteGuild from .widget import Widget, WidgetMember, WidgetChannel from .object import Object from .reaction import Reaction from . import utils, opus, abc, rtp from .enums import * from .embeds import Embed from .shard import AutoShardedClient from .player import * from .reader import * from .webhook import * from .voice_client import VoiceClient from .audit_logs import AuditLogChanges, AuditLogEntry, AuditLogDiff from .raw_models import * from .team import * from .speakingstate import SpeakingState VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial') version_info = VersionInfo(major=1, minor=3, micro=0, releaselevel='alpha', serial=0) try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler()) import warnings warnings.simplefilter('once', category=RuntimeWarning) warnings.warn("""This is a development branch. DO NOT: - Expect anything to work. - Expect anything broken to be fixed in a timely manner. - Expect docs. - Expect it to be done anytime soon. - Expect this code to be up to date with the main repo. - Expect help with this fork from randos in the discord.py help channels. - Bother people in the help server for assistance anyways. - Mention the words "machine learning" or "AI" without being able to produce a university email or degree. - Try to use this fork without some degree of python competence. If I see you struggling with basic stuff I will ignore your problem and tell you to learn python. If you have questions ping Imayhaveborkedit somewhere in the help server and ask directly. For other matters such as comments and concerns relating more to the api design post it here instead: https://github.com/Rapptz/discord.py/issues/1094 """, RuntimeWarning, stacklevel=1000) warnings.simplefilter('default', category=RuntimeWarning) del warnings
"My flash cable and sockets are wet - what am I doing wrong?" Make sure that your plug connections are dry when you unplug them. Water can otherwise reach the socket or the plug. Clean your plugs and sockets with alcohol and dry them afterwards. The best thing is to blow-dry them with compressed air. Treat them now and again with a drop of contact oil - corrosion is thus reduced, the contact security and lifetime are enhanced substantially. Only dry contacts guarantee a flawless TTL control.
#!/usr/bin/python import sys, os, time, urllib, datetime, socket, sched, threading basepath = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] sys.path.append(basepath + '/libs/Adafruit_Python_CharLCD') import Adafruit_CharLCD as LCD sys.path.append(basepath + '/libs/requests') sys.path.append(basepath + '/libs/python-forecast.io') sys.path.append(basepath + '/libs/io-client-python') import requests from requests.packages import urllib3 urllib3.disable_warnings() import forecastio import Adafruit_IO import tempControl UI = ( ("time",), ("indoor temp", ('offset up', 'offset down')), ("outdoor temp",), ("diagnostics", ('IP', 'reboot')), ('auxiliaries', ( ("fan", ('on', 'off')), ("patio melter", ('on', 'off')), ("outside light", ('on', 'off')), ("garden hose", ('on', 'off')) )) ) threads = [] topUIidx = 0 def log(message): with file(sys.argv[0]+".log", 'a') as logFile: logFile.write("%s: %s\n" % (datetime.datetime.now(), message)) def getOutdoor(lcd): global topUIidx temp = tempControl.getOutdoor() if topUIidx == 3: lcd.clear() lcd.message("Outside temp\n%i deg F" % temp) update = threading.Timer(300, getOutdoor, (lcd,)) update.start() def getIndoor(lcd): global topUIidx temp, humidity = tempControl.getIndoor() target = tempControl.getTarget() if topUIidx == 2: lcd.clear() lcd.message("Inside temp: %iF\nSet to: %iF" % (int(round(temp,0)), target)) update = threading.Timer(300, getIndoor, (lcd,)) update.start() def getIp(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8",80)) return s.getsockname()[0] except: return "unknown" def getTime(lcd): d = datetime.datetime.now() if topUIidx == 1: lcd.clear() lcd.message(d.strftime("%m/%d %I:%M %p\n%A")) update = threading.Timer(60, getTime, (lcd,)) update.start() def setTopMessage(lcd, on=True): global topUIidx global threads lcd.clear() if topUIidx == 1: t = threading.Thread(name="time", target=getTime, args=(lcd,)) t.start() elif topUIidx == 2: lcd.message("Inside temp:\nSet to:") t = threading.Thread(name="insideTemp", target=getIndoor, args=(lcd,)) threads.append(t) t.start() elif topUIidx == 3: lcd.message("Outside temp\n...") t = threading.Thread(name="outsideTemp", target=getOutdoor, args=(lcd,)) threads.append(t) t.start() elif topUIidx == 4: lcd.message('Press up/down to\nuse Aux. systems') elif topUIidx == 5: lcd.message('Welcome to\nRPi Thermostat') def setAuxMessage(idx, lcd, on): lcd.clear() if idx == 0: if not on: lcd.message('Press select to\nturn fan on') else: lcd.message('Press select to\nturn fan off') elif idx == 1: if not on: lcd.message('Press select to\nturn melter on') else: lcd.message('Press select to\nturn melter off') elif idx == 2: if not on: lcd.message('Press select to\nturn light on') else: lcd.message('Press select to\nturn light off') elif idx == 3: if not on: lcd.message('Press select to\nturn hose on') else: lcd.message('Press select to\nturn hose off') else: lcd.message('Aux menu level\nerror: choice=%i' % idx) def setDiagMessage(idx, lcd): lcd.clear() if idx == 0: lcd.message("IP address\n%s" % (getIp())) elif idx == 1: lcd.message("Press select\nto reboot") else: lcd.message('Menu Error\ndiag level choice=%i' % idx) def setFurnace(): temp, humidity = tempControl.getIndoor() target = tempControl.getTarget() if target > temp: On = True else: On = False callRelay(3, On) def callRelay(idx, On): url = r'http://192.168.42.44/relay%i%s' % (idx, {True:'On', False:"Off"}[On]) log(url) try: result = urllib.urlopen(url).read() except IOError: result = "Remote control unit not responding" log(result) def restart(): command = "/usr/bin/sudo /sbin/shutdown -r now" import subprocess process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) output = process.communicate()[0] log( output ) def main(): global topUIidx global threads scheduler = sched.scheduler(time.time, time.sleep) nextEventTime = time.mktime(tempControl.getNextEventTime()) nextEvent = scheduler.enterabs(nextEventTime, 1, setFurnace, None) # Start a thread to run the events t = threading.Thread(target=scheduler.run) t.start() lcd = LCD.Adafruit_CharLCDPlate() lcd.set_color(1,1,1) secUIidx = 0 auxDevices = [False, False, False, False] setTopMessage(lcd) while True: if lcd.is_pressed(LCD.LEFT): secUIidx = 0 topUIidx -= 1 if topUIidx < 1: topUIidx = len(UI) setTopMessage(lcd) if lcd.is_pressed(LCD.RIGHT): secUIidx = 0 topUIidx += 1 if topUIidx > len(UI): topUIidx = 1 setTopMessage(lcd) if lcd.is_pressed(LCD.UP): if UI[topUIidx][0] == 'indoor temp': tempControl.offset += 1 setTopMessage(lcd) t = threading.Thread(name="furnaceUp", target=setFurnace) threads.append(t) t.start() if UI[topUIidx][0] == 'auxiliaries': secUIidx += 1 if secUIidx > len(UI[topUIidx][0][1]): secUIidx = 0 setAuxMessage(secUIidx, lcd, auxDevices[secUIidx]) if UI[topUIidx][0] == "diagnostics": secUIidx += 1 if secUIidx > len(UI[topUIidx][0][1]): secUIidx = 0 setDiagMessage(secUIidx, lcd) if lcd.is_pressed(LCD.DOWN): if UI[topUIidx][0] == 'indoor temp': tempControl.offset -= 1 setTopMessage(lcd) t = threading.Thread(name="furnaceDown", target=setFurnace) threads.append(t) t.start() if UI[topUIidx][0] == 'auxiliaries': secUIidx -= 1 if secUIidx < 0: secUIidx = len(UI[topUIidx][0][1]) setAuxMessage(secUIidx, lcd, auxDevices[secUIidx]) if UI[topUIidx][0] == "diagnostics": secUIidx -= 1 if secUIidx < 0: secUIidx = len(UI[topUIidx][0][1]) setDiagMessage(secUIidx, lcd) if lcd.is_pressed(LCD.SELECT): if UI[topUIidx][0] == "diagnostics" and UI[topUIidx][secUIidx] == 'reboot': lcd.clear() lcd.message("\nrebooting...") restart() if UI[topUIidx][0] == 'auxiliaries': t = threading.Thread(name="callRelayAux", target=callRelay, args =(secUIidx+1, auxDevices[secUIidx])) threads.append(t) t.start() auxDevices[secUIidx] = not auxDevices[secUIidx] setAuxMessage(secUIidx, lcd, auxDevices[secUIidx]) if __name__ == '__main__': ## check internet connection ## ## check for relay module main()
bzip2 is a freely available, patent free, high-quality data compressor for Linux. It typically compresses files to within 10% to 15% of the best available techniques. ArchView is an extension of Firefox, which can open archive file online without downloading the whole archive. PeaZip is a file and archive manager for Linux and other systems. It Features volume spanning, compression, authenticated encryption.Supports almost all file formats. File Roller is an archive manager for the GNOME desktop environment. File Roller is only a graphical interface to archiving software utilities such as tar and zip. Ark is a program for managing various archive formats within the KDE environment. Archives can be viewed, extracted, created and modified from within Ark. p7zip is a quick port of 7z.exe and 7za.exe (command line version of 7zip, see www.7-zip.org) for Linux and Unix systems. Q7Z is a P7Zip or 7-Zip GUI, which attempts to simplify data compression and backup. GNU Gzip is a popular data compression software originally written by Jean-loup Gailly for the GNU project. Mark Adler wrote the decompression part. Xarchiver is a GTK+2 only frontend to 7z,zip,rar,tar,bzip2, gzip,arj, lha, rpm and deb. Xarchiver allows you to create,add, extract and delete files in the above formats. WinRAR is a powerful archive manager for Linux. It can backup your data and reduce the size of email attachments, decompress RAR, ZIP and other files. LRZIP (Long Range ZIP) is a Linux compression software optimised for large files. The larger the file and the more memory you have, the better the compression advantage. Lzip is a lossless data compressor based on the LZMA algorithm, with very safe integrity checking and a user interface similar to the one of gzip or bzip2.
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from collections import defaultdict from datetime import datetime import pymongo from pylons import tmpl_context as c, app_globals as g from pylons import request from ming import schema as S from ming.orm import state, session from ming.orm import FieldProperty, ForeignIdProperty, RelationProperty from ming.orm.declarative import MappedClass from ming.utils import LazyProperty from webhelpers import feedgenerator as FG from allura.lib import helpers as h from allura.lib import security from .session import main_orm_session from .session import project_orm_session from .session import artifact_orm_session from .index import ArtifactReference from .types import ACL, MarkdownCache from .project import AppConfig from .notification import MailFooter from filesystem import File log = logging.getLogger(__name__) class Artifact(MappedClass): """ Base class for anything you want to keep track of. - Automatically indexed into Solr (see index() method) - Has a discussion thread that can have files attached to it :var mod_date: last-modified :class:`datetime` :var acl: dict of permission name => [roles] :var labels: list of plain old strings """ class __mongometa__: session = artifact_orm_session name = 'artifact' indexes = [ ('app_config_id', 'labels'), ] def before_save(data): _session = artifact_orm_session._get() skip_mod_date = getattr(_session, 'skip_mod_date', False) skip_last_updated = getattr(_session, 'skip_last_updated', False) if not skip_mod_date: data['mod_date'] = datetime.utcnow() else: log.debug('Not updating mod_date') if c.project and not skip_last_updated: c.project.last_updated = datetime.utcnow() type_s = 'Generic Artifact' # Artifact base schema _id = FieldProperty(S.ObjectId) mod_date = FieldProperty(datetime, if_missing=datetime.utcnow) app_config_id = ForeignIdProperty( 'AppConfig', if_missing=lambda: c.app.config._id) plugin_verson = FieldProperty(S.Deprecated) tool_version = FieldProperty(S.Deprecated) acl = FieldProperty(ACL) tags = FieldProperty(S.Deprecated) labels = FieldProperty([str]) references = FieldProperty(S.Deprecated) backreferences = FieldProperty(S.Deprecated) app_config = RelationProperty('AppConfig') # Not null if artifact originated from external import. The import ID is # implementation specific, but should probably be an object indicating # the source, original ID, and any other info needed to identify where # the artifact came from. But if you only have one source, a str might do. import_id = FieldProperty(None, if_missing=None) deleted = FieldProperty(bool, if_missing=False) def __json__(self): """Return a JSON-encodable :class:`dict` representation of this Artifact. """ return dict( _id=str(self._id), mod_date=self.mod_date, labels=list(self.labels), related_artifacts=[a.url() for a in self.related_artifacts()], discussion_thread=self.discussion_thread.__json__(), discussion_thread_url=h.absurl('/rest%s' % self.discussion_thread.url()), ) def parent_security_context(self): """Return the :class:`allura.model.project.AppConfig` instance for this Artifact. ACL processing for this Artifact continues at the AppConfig object. This lets AppConfigs provide a 'default' ACL for all artifacts in the tool. """ return self.app_config @classmethod def attachment_class(cls): raise NotImplementedError, 'attachment_class' @classmethod def translate_query(cls, q, fields): """Return a translated Solr query (``q``), where generic field identifiers are replaced by the 'strongly typed' versions defined in ``fields``. """ for f in fields: if '_' in f: base, typ = f.rsplit('_', 1) q = q.replace(base + ':', f + ':') return q @LazyProperty def ref(self): """Return :class:`allura.model.index.ArtifactReference` for this Artifact. """ return ArtifactReference.from_artifact(self) @LazyProperty def refs(self): """Artifacts referenced by this one. :return: list of :class:`allura.model.index.ArtifactReference` """ return self.ref.references @LazyProperty def backrefs(self): """Artifacts that reference this one. :return: list of :attr:`allura.model.index.ArtifactReference._id`'s """ q = ArtifactReference.query.find(dict(references=self.index_id())) return [aref._id for aref in q] def related_artifacts(self): """Return all Artifacts that are related to this one. """ related_artifacts = [] for ref_id in self.refs + self.backrefs: ref = ArtifactReference.query.get(_id=ref_id) if ref is None: continue artifact = ref.artifact if artifact is None: continue artifact = artifact.primary() if artifact is None: continue # don't link to artifacts in deleted tools if hasattr(artifact, 'app_config') and artifact.app_config is None: continue # TODO: This should be refactored. We shouldn't be checking # artifact type strings in platform code. if artifact.type_s == 'Commit' and not artifact.repo: ac = AppConfig.query.get( _id=ref.artifact_reference['app_config_id']) app = ac.project.app_instance(ac) if ac else None if app: artifact.set_context(app.repo) if artifact not in related_artifacts and (getattr(artifact, 'deleted', False) == False): related_artifacts.append(artifact) return sorted(related_artifacts, key=lambda a: a.url()) def subscribe(self, user=None, topic=None, type='direct', n=1, unit='day'): """Subscribe ``user`` to the :class:`allura.model.notification.Mailbox` for this Artifact. :param user: :class:`allura.model.auth.User` If ``user`` is None, ``c.user`` will be subscribed. """ from allura.model import Mailbox if user is None: user = c.user Mailbox.subscribe( user_id=user._id, project_id=self.app_config.project_id, app_config_id=self.app_config._id, artifact=self, topic=topic, type=type, n=n, unit=unit) def unsubscribe(self, user=None): """Unsubscribe ``user`` from the :class:`allura.model.notification.Mailbox` for this Artifact. :param user: :class:`allura.model.auth.User` If ``user`` is None, ``c.user`` will be unsubscribed. """ from allura.model import Mailbox if user is None: user = c.user Mailbox.unsubscribe( user_id=user._id, project_id=self.app_config.project_id, app_config_id=self.app_config._id, artifact_index_id=self.index_id()) def primary(self): """If an artifact is a "secondary" artifact (discussion of a ticket, for instance), return the artifact that is the "primary". """ return self @classmethod def artifacts_labeled_with(cls, label, app_config): """Return all artifacts of type ``cls`` that have the label ``label`` and are in the tool denoted by ``app_config``. :param label: str :param app_config: :class:`allura.model.project.AppConfig` instance """ return cls.query.find({'labels': label, 'app_config_id': app_config._id}) def email_link(self, subject='artifact'): """Return a 'mailto' URL for this Artifact, with optional subject. """ if subject: return 'mailto:%s?subject=[%s:%s:%s] Re: %s' % ( self.email_address, self.app_config.project.shortname, self.app_config.options.mount_point, self.shorthand_id(), subject) else: return 'mailto:%s' % self.email_address @property def project(self): """Return the :class:`allura.model.project.Project` instance to which this Artifact belongs. """ return getattr(self.app_config, 'project', None) @property def project_id(self): """Return the ``_id`` of the :class:`allura.model.project.Project` instance to which this Artifact belongs. """ return self.app_config.project_id @LazyProperty def app(self): """Return the :class:`allura.model.app.Application` instance to which this Artifact belongs. """ if not self.app_config: return None if getattr(c, 'app', None) and c.app.config._id == self.app_config._id: return c.app else: return self.app_config.load()(self.project, self.app_config) def index_id(self): """Return a globally unique artifact identifier. Used for SOLR ID, shortlinks, and possibly elsewhere. """ id = '%s.%s#%s' % ( self.__class__.__module__, self.__class__.__name__, self._id) return id.replace('.', '/') def index(self): """Return a :class:`dict` representation of this Artifact suitable for search indexing. Subclasses should override this, providing a dictionary of solr_field => value. These fields & values will be stored by Solr. Subclasses should call the super() index() and then extend it with more fields. You probably want to override at least title and text to have meaningful search results and email senders. You can take advantage of Solr's dynamic field typing by adding a type suffix to your field names, e.g.: _s (string) (not analyzed) _t (text) (analyzed) _b (bool) _i (int) """ project = self.project return dict( id=self.index_id(), mod_date_dt=self.mod_date, title='Artifact %s' % self._id, project_id_s=str(project._id), project_name_t=project.name, project_shortname_t=project.shortname, tool_name_s=self.app_config.tool_name, mount_point_s=self.app_config.options.mount_point, is_history_b=False, url_s=self.url(), type_s=self.type_s, labels_t=' '.join(l for l in self.labels), snippet_s='', deleted_b=self.deleted) def url(self): """Return the URL for this Artifact. Subclasses must implement this. """ raise NotImplementedError, 'url' # pragma no cover def shorthand_id(self): """How to refer to this artifact within the app instance context. For a wiki page, it might be the title. For a ticket, it might be the ticket number. For a discussion, it might be the message ID. Generally this should have a strong correlation to the URL. """ return str(self._id) # pragma no cover def link_text(self): """Return the link text to use when a shortlink to this artifact is expanded into an <a></a> tag. By default this method returns :attr:`type_s` + :meth:`shorthand_id`. Subclasses should override this method to provide more descriptive link text. """ return self.shorthand_id() def get_discussion_thread(self, data=None): """Return the discussion thread and parent_id for this artifact. :return: (:class:`allura.model.discuss.Thread`, parent_thread_id (int)) """ from .discuss import Thread t = Thread.query.get(ref_id=self.index_id()) if t is None: idx = self.index() t = Thread.new( app_config_id=self.app_config_id, discussion_id=self.app_config.discussion_id, ref_id=idx['id'], subject='%s discussion' % h.get_first(idx, 'title')) parent_id = None if data: in_reply_to = data.get('in_reply_to', []) if in_reply_to: parent_id = in_reply_to[0] return t, parent_id @LazyProperty def discussion_thread(self): """Return the :class:`discussion thread <allura.model.discuss.Thread>` for this Artifact. """ return self.get_discussion_thread()[0] def add_multiple_attachments(self, file_info): if not isinstance(file_info, list): file_info = [file_info] for attach in file_info: if hasattr(attach, 'file'): self.attach(attach.filename, attach.file, content_type=attach.type) def attach(self, filename, fp, **kw): """Attach a file to this Artifact. :param filename: file name :param fp: a file-like object (implements ``read()``) :param \*\*kw: passed through to Attachment class constructor """ att = self.attachment_class().save_attachment( filename=filename, fp=fp, artifact_id=self._id, **kw) return att @LazyProperty def attachments(self): return self.attachment_class().query.find(dict( app_config_id=self.app_config_id, artifact_id=self._id, type='attachment')).all() def delete(self): """Delete this Artifact. """ ArtifactReference.query.remove(dict(_id=self.index_id())) super(Artifact, self).delete() def get_mail_footer(self, notification, toaddr): return MailFooter.standard(notification) def message_id(self): '''Persistent, email-friendly (Message-ID header) id of this artifact''' return h.gen_message_id(self._id) class Snapshot(Artifact): """A snapshot of an :class:`Artifact <allura.model.artifact.Artifact>`, used in :class:`VersionedArtifact <allura.model.artifact.VersionedArtifact>`""" class __mongometa__: session = artifact_orm_session name = 'artifact_snapshot' unique_indexes = [('artifact_class', 'artifact_id', 'version')] indexes = [('artifact_id', 'version')] _id = FieldProperty(S.ObjectId) artifact_id = FieldProperty(S.ObjectId) artifact_class = FieldProperty(str) version = FieldProperty(S.Int, if_missing=0) author = FieldProperty(dict( id=S.ObjectId, username=str, display_name=str, logged_ip=str)) timestamp = FieldProperty(datetime) data = FieldProperty(None) def index(self): result = Artifact.index(self) original = self.original() if original: original_index = original.index() result.update(original_index) result['title'] = '%s (version %d)' % ( h.get_first(original_index, 'title'), self.version) result.update( id=self.index_id(), version_i=self.version, author_username_t=self.author.username, author_display_name_t=self.author.display_name, timestamp_dt=self.timestamp, is_history_b=True) return result def original(self): raise NotImplemented, 'original' # pragma no cover def shorthand_id(self): return '%s#%s' % (self.original().shorthand_id(), self.version) @property def attachments(self): orig = self.original() if not orig: return None return orig.attachments def __getattr__(self, name): return getattr(self.data, name) class VersionedArtifact(Artifact): """ An :class:`Artifact <allura.model.artifact.Artifact>` that has versions. Associated data like attachments and discussion thread are not versioned. """ class __mongometa__: session = artifact_orm_session name = 'versioned_artifact' history_class = Snapshot version = FieldProperty(S.Int, if_missing=0) def commit(self, update_stats=True): '''Save off a snapshot of the artifact and increment the version #''' self.version += 1 try: ip_address = request.headers.get( 'X_FORWARDED_FOR', request.remote_addr) ip_address = ip_address.split(',')[0].strip() except: ip_address = '0.0.0.0' data = dict( artifact_id=self._id, artifact_class='%s.%s' % ( self.__class__.__module__, self.__class__.__name__), version=self.version, author=dict( id=c.user._id, username=c.user.username, display_name=c.user.get_pref('display_name'), logged_ip=ip_address), timestamp=datetime.utcnow(), data=state(self).clone()) ss = self.__mongometa__.history_class(**data) session(ss).insert_now(ss, state(ss)) log.info('Snapshot version %s of %s', self.version, self.__class__) if update_stats: if self.version > 1: g.statsUpdater.modifiedArtifact( self.type_s, self.mod_date, self.project, c.user) else: g.statsUpdater.newArtifact( self.type_s, self.mod_date, self.project, c.user) return ss def get_version(self, n): if n < 0: n = self.version + n + 1 ss = self.__mongometa__.history_class.query.get( artifact_id=self._id, artifact_class='%s.%s' % ( self.__class__.__module__, self.__class__.__name__), version=n) if ss is None: raise IndexError, n return ss def revert(self, version): ss = self.get_version(version) old_version = self.version for k, v in ss.data.iteritems(): setattr(self, k, v) self.version = old_version def history(self): HC = self.__mongometa__.history_class q = HC.query.find(dict(artifact_id=self._id)).sort( 'version', pymongo.DESCENDING) return q @property def last_updated(self): history = self.history() if history.count(): return self.history().first().timestamp else: return self.mod_date def delete(self): # remove history so that the snapshots aren't left orphaned super(VersionedArtifact, self).delete() HC = self.__mongometa__.history_class HC.query.remove(dict(artifact_id=self._id)) class Message(Artifact): """ A message :var _id: an email friendly (e.g. message-id) string id :var slug: slash-delimeted random identifier. Slashes useful for threaded searching and ordering :var full_slug: string of slash-delimited "timestamp:slug" components. Useful for sorting by timstamp """ class __mongometa__: session = artifact_orm_session name = 'message' type_s = 'Generic Message' _id = FieldProperty(str, if_missing=h.gen_message_id) slug = FieldProperty(str, if_missing=h.nonce) full_slug = FieldProperty(str, if_missing=None) parent_id = FieldProperty(str) app_id = FieldProperty(S.ObjectId, if_missing=lambda: c.app.config._id) timestamp = FieldProperty(datetime, if_missing=datetime.utcnow) author_id = FieldProperty(S.ObjectId, if_missing=lambda: c.user._id) text = FieldProperty(str, if_missing='') @classmethod def make_slugs(cls, parent=None, timestamp=None): part = h.nonce() if timestamp is None: timestamp = datetime.utcnow() dt = timestamp.strftime('%Y%m%d%H%M%S') slug = part full_slug = dt + ':' + part if parent: return (parent.slug + '/' + slug, parent.full_slug + '/' + full_slug) else: return slug, full_slug def author(self): from .auth import User return User.query.get(_id=self.author_id) or User.anonymous() def index(self): result = Artifact.index(self) author = self.author() result.update( author_user_name_t=author.username, author_display_name_t=author.get_pref('display_name'), timestamp_dt=self.timestamp, text=self.text) return result def shorthand_id(self): return self.slug class AwardFile(File): class __mongometa__: session = main_orm_session name = 'award_file' award_id = FieldProperty(S.ObjectId) class Award(Artifact): class __mongometa__: session = main_orm_session name = 'award' indexes = ['short'] type_s = 'Generic Award' from .project import Neighborhood _id = FieldProperty(S.ObjectId) created_by_neighborhood_id = ForeignIdProperty( Neighborhood, if_missing=None) created_by_neighborhood = RelationProperty( Neighborhood, via='created_by_neighborhood_id') short = FieldProperty(str, if_missing=h.nonce) timestamp = FieldProperty(datetime, if_missing=datetime.utcnow) full = FieldProperty(str, if_missing='') def index(self): result = Artifact.index(self) result.update( _id_s=self._id, short_s=self.short, timestamp_dt=self.timestamp, full_s=self.full) if self.created_by: result['created_by_s'] = self.created_by.name return result @property def icon(self): return AwardFile.query.get(award_id=self._id) def url(self): return str(self._id) def longurl(self): return self.created_by_neighborhood.url_prefix + "_admin/awards/" + self.url() def shorthand_id(self): return self.short class AwardGrant(Artifact): "An :class:`Award <allura.model.artifact.Award>` can be bestowed upon a project by a neighborhood" class __mongometa__: session = main_orm_session name = 'grant' indexes = ['short'] type_s = 'Generic Award Grant' _id = FieldProperty(S.ObjectId) award_id = ForeignIdProperty(Award, if_missing=None) award = RelationProperty(Award, via='award_id') granted_by_neighborhood_id = ForeignIdProperty( 'Neighborhood', if_missing=None) granted_by_neighborhood = RelationProperty( 'Neighborhood', via='granted_by_neighborhood_id') granted_to_project_id = ForeignIdProperty('Project', if_missing=None) granted_to_project = RelationProperty( 'Project', via='granted_to_project_id') timestamp = FieldProperty(datetime, if_missing=datetime.utcnow) def index(self): result = Artifact.index(self) result.update( _id_s=self._id, short_s=self.short, timestamp_dt=self.timestamp, full_s=self.full) if self.award: result['award_s'] = self.award.short return result @property def icon(self): return AwardFile.query.get(award_id=self.award_id) def url(self): slug = str(self.granted_to_project.shortname).replace('/', '_') return h.urlquote(slug) def longurl(self): slug = str(self.granted_to_project.shortname).replace('/', '_') slug = self.award.longurl() + '/' + slug return h.urlquote(slug) def shorthand_id(self): if self.award: return self.award.short else: return None class Feed(MappedClass): """ Used to generate rss/atom feeds. This does not need to be extended; all feed items go into the same collection """ class __mongometa__: session = project_orm_session name = 'artifact_feed' indexes = [ 'pubdate', ('artifact_ref.project_id', 'artifact_ref.mount_point'), (('ref_id', pymongo.ASCENDING), ('pubdate', pymongo.DESCENDING)), (('project_id', pymongo.ASCENDING), ('app_config_id', pymongo.ASCENDING), ('pubdate', pymongo.DESCENDING)), # used in ext/user_profile/user_main.py for user feeds 'author_link', # used in project feed (('project_id', pymongo.ASCENDING), ('pubdate', pymongo.DESCENDING)), ] _id = FieldProperty(S.ObjectId) ref_id = ForeignIdProperty('ArtifactReference') neighborhood_id = ForeignIdProperty('Neighborhood') project_id = ForeignIdProperty('Project') app_config_id = ForeignIdProperty('AppConfig') tool_name = FieldProperty(str) title = FieldProperty(str) link = FieldProperty(str) pubdate = FieldProperty(datetime, if_missing=datetime.utcnow) description = FieldProperty(str) description_cache = FieldProperty(MarkdownCache) unique_id = FieldProperty(str, if_missing=lambda: h.nonce(40)) author_name = FieldProperty(str, if_missing=lambda: c.user.get_pref( 'display_name') if hasattr(c, 'user') else None) author_link = FieldProperty( str, if_missing=lambda: c.user.url() if hasattr(c, 'user') else None) artifact_reference = FieldProperty(S.Deprecated) @classmethod def post(cls, artifact, title=None, description=None, author=None, author_link=None, author_name=None, pubdate=None, link=None, **kw): """ Create a Feed item. Returns the item. But if anon doesn't have read access, create does not happen and None is returned """ # TODO: fix security system so we can do this correctly and fast from allura import model as M anon = M.User.anonymous() if not security.has_access(artifact, 'read', user=anon): return if not security.has_access(c.project, 'read', user=anon): return idx = artifact.index() if author is None: author = c.user if author_name is None: author_name = author.get_pref('display_name') if title is None: title = '%s modified by %s' % ( h.get_first(idx, 'title'), author_name) if description is None: description = title if pubdate is None: pubdate = datetime.utcnow() if link is None: link = artifact.url() item = cls( ref_id=artifact.index_id(), neighborhood_id=artifact.app_config.project.neighborhood_id, project_id=artifact.app_config.project_id, app_config_id=artifact.app_config_id, tool_name=artifact.app_config.tool_name, title=title, description=g.markdown.convert(description), link=link, pubdate=pubdate, author_name=author_name, author_link=author_link or author.url()) unique_id = kw.pop('unique_id', None) if unique_id: item.unique_id = unique_id return item @classmethod def feed(cls, q, feed_type, title, link, description, since=None, until=None, offset=None, limit=None): "Produces webhelper.feedgenerator Feed" d = dict(title=title, link=h.absurl(link), description=description, language=u'en') if feed_type == 'atom': feed = FG.Atom1Feed(**d) elif feed_type == 'rss': feed = FG.Rss201rev2Feed(**d) query = defaultdict(dict) query.update(q) if since is not None: query['pubdate']['$gte'] = since if until is not None: query['pubdate']['$lte'] = until cur = cls.query.find(query) cur = cur.sort('pubdate', pymongo.DESCENDING) if limit is None: limit = 10 query = cur.limit(limit) if offset is not None: query = cur.offset(offset) for r in cur: feed.add_item(title=r.title, link=h.absurl(r.link.encode('utf-8')), pubdate=r.pubdate, description=r.description, unique_id=h.absurl(r.unique_id), author_name=r.author_name, author_link=h.absurl(r.author_link)) return feed class VotableArtifact(MappedClass): """Voting support for the Artifact. Use as a mixin.""" class __mongometa__: session = main_orm_session name = 'vote' votes = FieldProperty(int, if_missing=0) votes_up = FieldProperty(int, if_missing=0) votes_down = FieldProperty(int, if_missing=0) votes_up_users = FieldProperty([str], if_missing=list()) votes_down_users = FieldProperty([str], if_missing=list()) def vote_up(self, user): voted = self.user_voted(user) if voted == 1: # Already voted up - unvote self.votes_up_users.remove(user.username) self.votes_up -= 1 elif voted == -1: # Change vote to negative self.votes_down_users.remove(user.username) self.votes_down -= 1 self.votes_up_users.append(user.username) self.votes_up += 1 else: self.votes_up_users.append(user.username) self.votes_up += 1 self.votes = self.votes_up - self.votes_down def vote_down(self, user): voted = self.user_voted(user) if voted == -1: # Already voted down - unvote self.votes_down_users.remove(user.username) self.votes_down -= 1 elif voted == 1: # Change vote to positive self.votes_up_users.remove(user.username) self.votes_up -= 1 self.votes_down_users.append(user.username) self.votes_down += 1 else: self.votes_down_users.append(user.username) self.votes_down += 1 self.votes = self.votes_up - self.votes_down def user_voted(self, user): """Check that user voted for this artifact. Return: 1 if user voted up -1 if user voted down 0 if user doesn't vote """ if user.username in self.votes_up_users: return 1 if user.username in self.votes_down_users: return -1 return 0 @property def votes_up_percent(self): votes_count = self.votes_up + self.votes_down if votes_count == 0: return 0 return int(float(self.votes_up) / votes_count * 100) def __json__(self): return { 'votes_up': self.votes_up, 'votes_down': self.votes_down, } class MovedArtifact(Artifact): class __mongometa__: session = artifact_orm_session name = 'moved_artifact' _id = FieldProperty(S.ObjectId) app_config_id = ForeignIdProperty( 'AppConfig', if_missing=lambda: c.app.config._id) app_config = RelationProperty('AppConfig') moved_to_url = FieldProperty(str, required=True, allow_none=False)
Be the first to know about job openings at Pix4D. Do you know someone at Pix4D ? Connect to find out! Pix4D is a developer of cutting edge software that converts images taken by hand, by drone, or by plane into survey-grade accurate and georeferenced 2D mosaics, 3D surface models and point clouds. Founded in 2011, Pix4D is rapidly expanding from its headquarters in Lausanne, Switzerland, to offices in Shanghai and San Francisco.Pix4D technology truly enables lightweight civilian drones to become the mapping and surveying tool of the future: empowering individuals to instantly capture their own 3D map of any changing environment. It forms the base of many cloud-processing solutions and is used by thousands of professionals worldwide on Windows, iOS and Linux platforms.
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=too-many-branches from __future__ import (absolute_import, division, print_function) import os import tempfile import itertools from collections import namedtuple from contextlib import contextmanager import numpy as np from mantid import config as mantid_config from mantid.api import (DataProcessorAlgorithm, AlgorithmFactory, FileProperty, WorkspaceProperty, FileAction, PropertyMode, mtd, AnalysisDataService, Progress) from mantid.simpleapi import (DeleteWorkspace, LoadEventNexus, SetGoniometer, SetUB, ModeratorTzeroLinear, SaveNexus, ConvertToMD, LoadMask, MaskDetectors, LoadNexus, MDNormSCDPreprocessIncoherent, MDNormSCD, MultiplyMD, CreateSingleValuedWorkspace, ConvertUnits, CropWorkspace, DivideMD, MinusMD, RenameWorkspace, ConvertToMDMinMaxGlobal, ClearMaskFlag) from mantid.kernel import (Direction, EnabledWhenProperty, PropertyCriterion, IntArrayProperty, FloatArrayProperty, FloatArrayLengthValidator) DEPRECATION_NOTICE = """BASISDiffraction is deprecated (on 2018-08-27). Instead, use BASISCrystalDiffraction or BASISPowderReduction.""" _SOLID_ANGLE_WS_ = '/tmp/solid_angle_diff.nxs' _FLUX_WS_ = '/tmp/int_flux.nxs' @contextmanager def pyexec_setup(new_options): """ Backup keys of mantid.config and clean up temporary files and workspaces upon algorithm completion or exception raised. :param new_options: dictionary of mantid configuration options to be modified. """ # Hold in this tuple all temporary objects to be removed after completion temp_objects = namedtuple('temp_objects', 'files workspaces') temps = temp_objects(list(), list()) previous_config = dict() for key, value in new_options.items(): previous_config[key] = mantid_config[key] mantid_config[key] = value try: yield temps finally: # reinstate the mantid options for key, value in previous_config.items(): mantid_config[key] = value # delete temporary files for file_name in temps.files: os.remove(file_name) # remove any workspace added to temps.workspaces or whose name begins # with "_t_" to_be_removed = set() for name in AnalysisDataService.getObjectNames(): if '_t_' == name[0:3]: to_be_removed.add(name) for workspace in temps.workspaces: if isinstance(workspace, str): to_be_removed.add(workspace) else: to_be_removed.add(workspace.name()) for name in to_be_removed: DeleteWorkspace(name) class BASISDiffraction(DataProcessorAlgorithm): _mask_file = '/SNS/BSS/shared/autoreduce/new_masks_08_12_2015/'\ 'BASIS_Mask_default_diff.xml' _solid_angle_ws_ = '/SNS/BSS/shared/autoreduce/solid_angle_diff.nxs' _flux_ws_ = '/SNS/BSS/shared/autoreduce/int_flux.nxs' def __init__(self): DataProcessorAlgorithm.__init__(self) self._lambda_range = [5.86, 6.75] # units of inverse Angstroms self._short_inst = "BSS" self._long_inst = "BASIS" self._run_list = None self._temps = None self._bkg = None self._bkg_scale = None self._vanadium_files = None self._momentum_range = None self._t_mask = None self._n_bins = None @classmethod def category(self): return "Diffraction\\Reduction" @classmethod def version(self): return 1 @classmethod def summary(self): return DEPRECATION_NOTICE def seeAlso(self): return [ "AlignDetectors","DiffractionFocussing","SNSPowderReduction" ] def PyInit(self): # Input validators array_length_three = FloatArrayLengthValidator(3) # Properties self.declareProperty('RunNumbers', '', 'Sample run numbers') self.declareProperty(FileProperty(name='MaskFile', defaultValue=self._mask_file, action=FileAction.OptionalLoad, extensions=['.xml']), doc='See documentation for latest mask files.') self.declareProperty(FloatArrayProperty('LambdaRange', self._lambda_range, direction=Direction.Input), doc='Incoming neutron wavelength range') self.declareProperty(WorkspaceProperty('OutputWorkspace', '', optional=PropertyMode.Mandatory, direction=Direction.Output), doc='Output Workspace. If background is '+ 'subtracted, _data and _background '+ 'workspaces will also be generated') # # Background for the sample runs # background_title = 'Background runs' self.declareProperty('BackgroundRuns', '', 'Background run numbers') self.setPropertyGroup('BackgroundRuns', background_title) self.declareProperty("BackgroundScale", 1.0, doc='The background will be scaled by this '+ 'number before being subtracted.') self.setPropertyGroup('BackgroundScale', background_title) # # Vanadium # vanadium_title = 'Vanadium runs' self.declareProperty('VanadiumRuns', '', 'Vanadium run numbers') self.setPropertyGroup('VanadiumRuns', vanadium_title) # # Single Crystal Diffraction # crystal_diffraction_title = 'Single Crystal Diffraction' self.declareProperty('SingleCrystalDiffraction', False, direction=Direction.Input, doc='Calculate diffraction pattern?') crystal_diffraction_enabled =\ EnabledWhenProperty('SingleCrystalDiffraction', PropertyCriterion.IsNotDefault) self.declareProperty('PsiAngleLog', 'SE50Rot', direction=Direction.Input, doc='log entry storing rotation of the sample' 'around the vertical axis') self.declareProperty('PsiOffset', 0.0, direction=Direction.Input, doc='Add this quantity to PsiAngleLog') self.declareProperty(FloatArrayProperty('LatticeSizes', [0,0,0], array_length_three, direction=Direction.Input), doc='three item comma-separated list "a, b, c"') self.declareProperty(FloatArrayProperty('LatticeAngles', [90.0, 90.0, 90.0], array_length_three, direction=Direction.Input), doc='three item comma-separated ' + 'list "alpha, beta, gamma"') # Reciprocal vector to be aligned with incoming beam self.declareProperty(FloatArrayProperty('VectorU', [1, 0, 0], array_length_three, direction=Direction.Input), doc='three item, comma-separated, HKL indexes' 'of the diffracting plane') # Reciprocal vector orthogonal to VectorU and in-plane with # incoming beam self.declareProperty(FloatArrayProperty('VectorV', [0, 1, 0], array_length_three, direction=Direction.Input), doc='three item, comma-separated, HKL indexes' 'of the direction perpendicular to VectorV' 'and the vertical axis') # Abscissa view self.declareProperty(FloatArrayProperty('Uproj', [1, 0, 0], array_length_three, direction=Direction.Input), doc='three item comma-separated Abscissa view' 'of the diffraction pattern') # Ordinate view self.declareProperty(FloatArrayProperty('Vproj', [0, 1, 0], array_length_three, direction=Direction.Input), doc='three item comma-separated Ordinate view' 'of the diffraction pattern') # Hidden axis self.declareProperty(FloatArrayProperty('Wproj', [0, 0, 1], array_length_three, direction=Direction.Input), doc='Hidden axis view') # Binnin in reciprocal slice self.declareProperty('NBins', 400, direction=Direction.Input, doc='number of bins in the HKL slice') self.setPropertyGroup('SingleCrystalDiffraction', crystal_diffraction_title) for a_property in ('PsiAngleLog', 'PsiOffset', 'LatticeSizes', 'LatticeAngles', 'VectorU', 'VectorV', 'Uproj', 'Vproj', 'Wproj', 'NBins'): self.setPropertyGroup(a_property, crystal_diffraction_title) self.setPropertySettings(a_property, crystal_diffraction_enabled) def PyExec(self): # Exit with deprecation notice self.log().error(DEPRECATION_NOTICE) # Facility and database configuration config_new_options = {'default.facility': 'SNS', 'default.instrument': 'BASIS', 'datasearch.searcharchive': 'On'} # Find valid incoming momentum range self._lambda_range = np.array(self.getProperty('LambdaRange').value) self._momentum_range = np.sort(2 * np.pi / self._lambda_range) # implement with ContextDecorator after python2 is deprecated) with pyexec_setup(config_new_options) as self._temps: # Load the mask to a workspace self._t_mask = LoadMask(Instrument='BASIS', InputFile=self.getProperty('MaskFile'). value, OutputWorkspace='_t_mask') # Pre-process the background runs if self.getProperty('BackgroundRuns').value: bkg_run_numbers = self._getRuns( self.getProperty('BackgroundRuns').value, doIndiv=True) bkg_run_numbers = \ list(itertools.chain.from_iterable(bkg_run_numbers)) background_reporter = Progress(self, start=0.0, end=1.0, nreports=len(bkg_run_numbers)) for i, run in enumerate(bkg_run_numbers): if self._bkg is None: self._bkg = self._mask_t0_crop(run, '_bkg') self._temps.workspaces.append('_bkg') else: _ws = self._mask_t0_crop(run, '_ws') self._bkg += _ws if '_ws' not in self._temps.workspaces: self._temps.workspaces.append('_ws') message = 'Pre-processing background: {} of {}'.\ format(i+1, len(bkg_run_numbers)) background_reporter.report(message) SetGoniometer(self._bkg, Axis0='0,0,1,0,1') self._bkg_scale = self.getProperty('BackgroundScale').value background_reporter.report(len(bkg_run_numbers), 'Done') # Pre-process the vanadium run(s) if self.getProperty('VanadiumRuns').value: run_numbers = self._getRuns( self.getProperty('VanadiumRuns').value, doIndiv=True) run_numbers = list(itertools.chain.from_iterable(run_numbers)) vanadium_reporter = Progress(self, start=0.0, end=1.0, nreports=len(run_numbers)) self._vanadium_files = list() for i, run in enumerate(run_numbers): self._vanadium_files.append(self._save_t0(run)) message = 'Pre-processing vanadium: {} of {}'. \ format(i+1, len(run_numbers)) vanadium_reporter.report(message) vanadium_reporter.report(len(run_numbers), 'Done') # Determination of single crystal diffraction if self.getProperty('SingleCrystalDiffraction').value: self._determine_single_crystal_diffraction() def _determine_single_crystal_diffraction(self): """ All work related to the determination of the diffraction pattern """ a, b, c = self.getProperty('LatticeSizes').value alpha, beta, gamma = self.getProperty('LatticeAngles').value u = self.getProperty('VectorU').value v = self.getProperty('VectorV').value uproj = self.getProperty('Uproj').value vproj = self.getProperty('Vproj').value wproj = self.getProperty('Wproj').value n_bins = self.getProperty('NBins').value self._n_bins = (n_bins, n_bins, 1) axis0 = '{},0,1,0,1'.format(self.getProperty('PsiAngleLog').value) axis1 = '{},0,1,0,1'.format(self.getProperty('PsiOffset').value) # Options for SetUB independent of run ub_args = dict(a=a, b=b, c=c, alpha=alpha, beta=beta, gamma=gamma, u=u, v=v) min_values = None # Options for algorithm ConvertToMD independent of run cmd_args = dict(QDimensions='Q3D', dEAnalysisMode='Elastic', Q3DFrames='HKL', QConversionScales='HKL', Uproj=uproj, Vproj=vproj, Wproj=wproj) mdn_args = None # Options for algorithm MDNormSCD # Find solid angle and flux if self._vanadium_files: kwargs = dict(Filename='+'.join(self._vanadium_files), MaskFile=self.getProperty("MaskFile").value, MomentumMin=self._momentum_range[0], MomentumMax=self._momentum_range[1]) _t_solid_angle, _t_int_flux = \ MDNormSCDPreprocessIncoherent(**kwargs) else: _t_solid_angle = self.nominal_solid_angle('_t_solid_angle') _t_int_flux = self.nominal_integrated_flux('_t_int_flux') # Process a sample at a time run_numbers = self._getRuns(self.getProperty("RunNumbers").value, doIndiv=True) run_numbers = list(itertools.chain.from_iterable(run_numbers)) diffraction_reporter = Progress(self, start=0.0, end=1.0, nreports=len(run_numbers)) for i_run, run in enumerate(run_numbers): _t_sample = self._mask_t0_crop(run, '_t_sample') # Set Goniometer and UB matrix SetGoniometer(_t_sample, Axis0=axis0, Axis1=axis1) SetUB(_t_sample, **ub_args) if self._bkg: self._bkg.run().getGoniometer().\ setR(_t_sample.run().getGoniometer().getR()) SetUB(self._bkg, **ub_args) # Determine limits for momentum transfer in HKL space. Needs to be # done only once. We use the first run. if min_values is None: kwargs = dict(QDimensions='Q3D', dEAnalysisMode='Elastic', Q3DFrames='HKL') min_values, max_values = ConvertToMDMinMaxGlobal(_t_sample, **kwargs) cmd_args.update({'MinValues': min_values, 'MaxValues': max_values}) # Convert to MD _t_md = ConvertToMD(_t_sample, OutputWorkspace='_t_md', **cmd_args) if self._bkg: _t_bkg_md = ConvertToMD(self._bkg, OutputWorkspace='_t_bkg_md', **cmd_args) # Determine aligned dimensions. Need to be done only once if mdn_args is None: aligned = list() for i_dim in range(3): kwargs = {'name': _t_md.getDimension(i_dim).name, 'min': min_values[i_dim], 'max': max_values[i_dim], 'n_bins': self._n_bins[i_dim]} aligned.append( '{name},{min},{max},{n_bins}'.format(**kwargs)) mdn_args = dict(AlignedDim0=aligned[0], AlignedDim1=aligned[1], AlignedDim2=aligned[2], FluxWorkspace=_t_int_flux, SolidAngleWorkspace=_t_solid_angle, SkipSafetyCheck=True) # Normalize sample by solid angle and integrated flux; # Accumulate runs into the temporary workspaces MDNormSCD(_t_md, OutputWorkspace='_t_data', OutputNormalizationWorkspace='_t_norm', TemporaryDataWorkspace='_t_data' if mtd.doesExist('_t_data') else None, TemporaryNormalizationWorkspace='_t_norm' if mtd.doesExist('_t_norm') else None, **mdn_args) if self._bkg: MDNormSCD(_t_bkg_md, OutputWorkspace='_t_bkg_data', OutputNormalizationWorkspace='_t_bkg_norm', TemporaryDataWorkspace='_t_bkg_data' if mtd.doesExist('_t_bkg_data') else None, TemporaryNormalizationWorkspace='_t_bkg_norm' if mtd.doesExist('_t_bkg_norm') else None, **mdn_args) message = 'Processing sample {} of {}'.\ format(i_run+1, len(run_numbers)) diffraction_reporter.report(message) self._temps.workspaces.append('PreprocessedDetectorsWS') # to remove # Iteration over the sample runs is done. # Division by vanadium, subtract background, and rename workspaces name = self.getPropertyValue("OutputWorkspace") _t_data = DivideMD(LHSWorkspace='_t_data', RHSWorkspace='_t_norm') if self._bkg: _t_bkg_data = DivideMD(LHSWorkspace='_t_bkg_data', RHSWorkspace='_t_bkg_norm') _t_scale = CreateSingleValuedWorkspace(DataValue=self._bkg_scale) _t_bkg_data = MultiplyMD(_t_bkg_data, _t_scale) ws = MinusMD(_t_data, _t_bkg_data) RenameWorkspace(_t_data, OutputWorkspace=name + '_dat') RenameWorkspace(_t_bkg_data, OutputWorkspace=name + '_bkg') else: ws = _t_data RenameWorkspace(ws, OutputWorkspace=name) self.setProperty("OutputWorkspace", ws) diffraction_reporter.report(len(run_numbers), 'Done') def _save_t0(self, run_number, name='_t_ws'): """ Create temporary events file with delayed emission time from moderator removed :param run: run number :param name: name for the output workspace :return: file name of event file with events treated with algorithm ModeratorTzeroLinear. """ ws = LoadEventNexus(Filename=self._makeRunFile(run_number), NXentryName='entry-diff', OutputWorkspace=name) ws = ModeratorTzeroLinear(InputWorkspace=ws.name(), OutputWorkspace=ws.name()) file_name = self._spawn_tempnexus() SaveNexus(ws, file_name) return file_name def _mask_t0_crop(self, run_number, name): """ Load a run into a workspace with: 1. Masked detectors 2. Delayed emission time from moderator removed 3. Conversion of units to momentum 4. Remove events outside the valid momentum range :param run_number: BASIS run number :param name: name for the output workspace :return: workspace object """ ws = LoadEventNexus(Filename=self._makeRunFile(run_number), NXentryName='entry-diff', SingleBankPixelsOnly=False, OutputWorkspace=name) MaskDetectors(ws, MaskedWorkspace=self._t_mask) ws = ModeratorTzeroLinear(InputWorkspace=ws.name(), OutputWorkspace=ws.name()) ws = ConvertUnits(ws, Target='Momentum', OutputWorkspace=ws.name()) ws = CropWorkspace(ws, OutputWorkspace=ws.name(), XMin=self._momentum_range[0], XMax=self._momentum_range[1]) return ws def _getRuns(self, rlist, doIndiv=True): """ Create sets of run numbers for analysis. A semicolon indicates a separate group of runs to be processed together. :param rlist: string containing all the run numbers to be reduced. :return: if doIndiv is False, return a list of IntArrayProperty objects. Each item is a pseudolist containing a set of runs to be reduced together. if doIndiv is True, return a list of strings, each string is a run number. """ run_list = [] # ";" separates the runs into substrings. Each substring represents a set of runs rlvals = rlist.split(';') for rlval in rlvals: iap = IntArrayProperty('', rlval) # split the substring if doIndiv: run_list.extend([[x] for x in iap.value]) else: run_list.append(iap.value) return run_list def _makeRunFile(self, run): """ Make name like BSS_24234_event.nxs """ return "{0}_{1}_event.nxs".format(self._short_inst, str(run)) def _spawn_tempnexus(self): """ Create a temporary file and flag for removal upon algorithm completion. :return: (str) absolute path to the temporary file. """ f = tempfile.NamedTemporaryFile(prefix='BASISDiffraction_', suffix='.nxs', dir=mantid_config['defaultsave.directory'], delete=False) file_name = f.name f.close() self._temps.files.append(file_name) # flag for removal return file_name def nominal_solid_angle(self, name): """ Generate an isotropic solid angle :param name: Name of the output workspace :return: reference to solid angle workspace """ ws = LoadNexus(Filename=self._solid_angle_ws_, OutputWorkspace=name) ClearMaskFlag(ws) MaskDetectors(ws, MaskedWorkspace=self._t_mask) for i in range(ws.getNumberHistograms()): ws.dataY(i)[0] = 0.0 if ws.getDetector(i).isMasked() else 1.0 ws.setX(i, self._momentum_range) return ws def nominal_integrated_flux(self, name): """ Generate a flux independent of momentum :param name: Name of the output workspace :return: reference to flux workspace """ ws = LoadNexus(Filename=self._flux_ws_, OutputWorkspace=name) ClearMaskFlag(ws) MaskDetectors(ws, MaskedWorkspace=self._t_mask) return ws # Register algorithm with Mantid. AlgorithmFactory.subscribe(BASISDiffraction)
It seems in our world today, gift-giving is a battle of creativity. How else are you going to surprise someone who has seen them all online, is content with they have, or gives no hints about what they want? Indeed, gift-giving has become a challenge wrapped in an odd sort of puzzle, figuring out what to give them in a way they would not expect. But if there is one thing we have to learn about those creative surprises online, nothing beats simplicity. So if a family member, a friend, or a significant other has a celebration coming up, you want to start their morning right by waking them up with simple and sincere gifts. Well, why not try flowers? In Australia, they already have a flower deliver service in Melbourne that lets you pick out flowers online and have them delivered on a specific time. If you have some delivered right at the door of the people you love, then you have just made their whole day a lot better. Here we will tell how you can choose the right kinds of flowers online and how you can actually save more from doing it. Contrary to what people think, flowers are not exactly cheap. Some types come with a sizeable price tag. So think of it as if you are shopping online for other items you usually buy, you need to set yourself a budget. Always keep that budget in mind when you are browsing through the library of flowers being offered by an online florist. The key to budgeting is to set a few notches higher than the cheapest bouquet you can get. In this way, there is room for adjustment. Or some people would save up for the most expensive bunch there is, and if they do not meet their deadline, they can just pick out flowers that their saved up money can afford; this is a good technique, too. If you are still on the fence about which kinds of flowers you are going to give them, opt for flowers that are already in season. They are usually cheap because they are delivered to stores in bulk, freshly cut and available for purchase. But that does not mean you should not get their favourite flowers. If those are not in season, you can just mix it along with those that are and create a beautiful arrangement. Before finalising your decision, always scout for other online florists so you can compare quality and price. Remember that expensive services are not always good, and cheaper ones are bound to be sketchy. So be careful when you are browsing through florists who have stores within your area. The best way to do this is to Google search the most popular ones and reduce it to your top three choices. Once you have your top florists, you can now proceed with looking up reviews of their stores and services online, Find out if they can be trusted, if the quality of their flowers and arrangement are excellent, and if their service is worth the time and money spent on them. Ensure that you are not just walking away with a good florist and a bargain deal; the person you are giving those flowers to should be made to feel special once they are delivered. Just like with online shopping, buying flowers on the Internet is not as difficult as it sounds. When it comes to getting quality flowers, keep these tips in mind and you will be sure the person receiving them will definitely remember it forever.
# This module handles input and output of PDB files. # # Written by Konrad Hinsen <hinsen@cnrs-orleans.fr> # Last revision: 2001-6-13 # """This module provides classes that represent PDB (Protein Data Bank) files and configurations contained in PDB files. It provides access to PDB files on two levels: low-level (line by line) and high-level (chains, residues, and atoms). Caution: The PDB file format has been heavily abused, and it is probably impossible to write code that can deal with all variants correctly. This modules tries to read the widest possible range of PDB files, but gives priority to a correct interpretation of the PDB format as defined by the Brookhaven National Laboratory. A special problem are atom names. The PDB file format specifies that the first two letters contain the right-justified chemical element name. A later modification allowed the initial space in hydrogen names to be replaced by a digit. Many programs ignore all this and treat the name as an arbitrary left-justified four-character name. This makes it difficult to extract the chemical element accurately; most programs write the '"CA"' for C_alpha in such a way that it actually stands for a calcium atom! For this reason a special element field has been added later, but only few files use it. The low-level routines in this module do not try to deal with the atom name problem; they return and expect four-character atom names including spaces in the correct positions. The high-level routines use atom names without leading or trailing spaces, but provide and use the element field whenever possible. For output, they use the element field to place the atom name correctly, and for input, they construct the element field content from the atom name if no explicit element field is found in the file. Except where indicated, numerical values use the same units and conventions as specified in the PDB format description. Example: >>>conf = Structure('example.pdb') >>>print conf >>>for residue in conf.residues: >>> for atom in residue: >>> print atom """ from Scientific.IO.TextFile import TextFile from Scientific.IO.FortranFormat import FortranFormat, FortranLine from Scientific.Geometry import Vector, Tensor from PDBExportFilters import export_filters import copy, string # # Fortran formats for PDB entries # atom_format = FortranFormat('A6,I5,1X,A4,A1,A4,A1,I4,A1,3X,3F8.3,2F6.2,' + '6X,A4,2A2') anisou_format = FortranFormat('A6,I5,1X,A4,A1,A4,A1,I4,A1,1X,6I7,2X,A4,2A2') conect_format = FortranFormat('A6,11I5') ter_format = FortranFormat('A6,I5,6X,A4,A1,I4,A1') model_format = FortranFormat('A6,4X,I4') header_format = FortranFormat('A6,4X,A40,A9,3X,A4') generic_format = FortranFormat('A6,A74') # # Amino acid and nucleic acid residues # amino_acids = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'CYX', 'GLN', 'GLU', 'GLY', 'HIS', 'HID', 'HIE', 'HIP', 'HSD', 'HSE', 'HSP', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', 'ACE', 'NME'] nucleic_acids = [ 'A', 'C', 'G', 'I', 'T', 'U', '+A', '+C', '+G', '+I', '+T', '+U', 'RA', 'RC', 'RG', 'RU', 'DA', 'DC', 'DG', 'DT', 'RA5', 'RC5', 'RG5', 'RU5', 'DA5', 'DC5', 'DG5', 'DT5', 'RA3', 'RC3', 'RG3', 'RU3', 'DA3', 'DC3', 'DG3', 'DT3', 'RAN', 'RCN', 'RGN', 'RUN', 'DAN', 'DCN', 'DGN', 'DTN', ] def defineAminoAcidResidue(symbol): amino_acids.append(string.upper(symbol)) def defineNucleicAcidResidue(symbol): nucleic_acids.append(string.upper(symbol)) # # Low-level file object. It represents line contents as Python dictionaries. # For output, there are additional methods that generate sequence numbers # for everything. # class PDBFile: """PDB file with access at the record level Constructor: PDBFile(|filename|, |mode|='"r"'), where |filename| is the file name and |mode| is '"r"' for reading and '"w"' for writing, The low-level file access is handled by the module Scientific.IO.TextFile, therefore compressed files and URLs (for reading) can be used as well. """ def __init__(self, filename, mode = 'r', subformat = None): self.file = TextFile(filename, mode) self.output = string.lower(mode[0]) == 'w' self.export_filter = None if subformat is not None: export = export_filters.get(subformat, None) if export is not None: self.export_filter = export() self.open = 1 if self.output: self.data = {'serial_number': 0, 'residue_number': 0, 'chain_id': '', 'segment_id': ''} self.het_flag = 0 self.chain_number = -1 def readLine(self): """Returns the contents of the next non-blank line (= record). The return value is a tuple whose first element (a string) contains the record type. For supported record types (HEADER, ATOM, HETATM, ANISOU, TERM, MODEL, CONECT), the items from the remaining fields are put into a dictionary which is returned as the second tuple element. Most dictionary elements are strings or numbers; atom positions are returned as a vector, and anisotropic temperature factors are returned as a rank-2 tensor, already multiplied by 1.e-4. White space is stripped from all strings except for atom names, whose correct interpretation can depend on an initial space. For unsupported record types, the second tuple element is a string containing the remaining part of the record. """ while 1: line = self.file.readline() if not line: return ('END','') if line[-1] == '\n': line = line[:-1] line = string.strip(line) if line: break line = string.ljust(line, 80) type = string.strip(line[:6]) if type == 'ATOM' or type == 'HETATM': line = FortranLine(line, atom_format) data = {'serial_number': line[1], 'name': line[2], 'alternate': string.strip(line[3]), 'residue_name': string.strip(line[4]), 'chain_id': string.strip(line[5]), 'residue_number': line[6], 'insertion_code': string.strip(line[7]), 'position': Vector(line[8:11]), 'occupancy': line[11], 'temperature_factor': line[12], 'segment_id': string.strip(line[13]), 'element': string.strip(line[14]), 'charge': string.strip(line[15])} return type, data elif type == 'ANISOU': line = FortranLine(line, anisou_format) data = {'serial_number': line[1], 'name': line[2], 'alternate': string.strip(line[3]), 'residue_name': string.strip(line[4]), 'chain_id': string.strip(line[5]), 'residue_number': line[6], 'insertion_code': string.strip(line[7]), 'u': 1.e-4*Tensor([[line[8], line[11], line[12]], [line[11], line[9] , line[13]], [line[12], line[13], line[10]]]), 'segment_id': string.strip(line[14]), 'element': string.strip(line[15]), 'charge': string.strip(line[16])} return type, data elif type == 'TER': line = FortranLine(line, ter_format) data = {'serial_number': line[1], 'residue_name': string.strip(line[2]), 'chain_id': string.strip(line[3]), 'residue_number': line[4], 'insertion_code': string.strip(line[5])} return type, data elif type == 'CONECT': line = FortranLine(line, conect_format) data = {'serial_number': line[1], 'bonded': filter(lambda i: i > 0, line[2:6]), 'hydrogen_bonded': filter(lambda i: i > 0, line[6:10]), 'salt_bridged': filter(lambda i: i > 0, line[10:12])} return type, data elif type == 'MODEL': line = FortranLine(line, model_format) data = {'serial_number': line[1]} return type, data elif type == 'HEADER': line = FortranLine(line, header_format) data = {'compound': line[1], 'date': line[2], 'pdb_code': line[3]} return type, data else: return type, line[6:] def writeLine(self, type, data): """Writes a line using record type and data dictionary in the same format as returned by readLine(). Default values are provided for non-essential information, so the data dictionary need not contain all entries. """ if self.export_filter is not None: type, data = self.export_filter.processLine(type, data) if type is None: return line = [type] if type == 'ATOM' or type == 'HETATM': format = atom_format position = data['position'] line = line + [data.get('serial_number', 1), data.get('name'), data.get('alternate', ''), string.rjust(data.get('residue_name', ''), 3), data.get('chain_id', ''), data.get('residue_number', 1), data.get('insertion_code', ''), position[0], position[1], position[2], data.get('occupancy', 0.), data.get('temperature_factor', 0.), data.get('segment_id', ''), string.rjust(data.get('element', ''), 2), data.get('charge', '')] elif type == 'ANISOU': format = anisou_format u = 1.e4*data['u'] u = [int(u[0,0]), int(u[1,1]), int(u[2,2]), int(u[0,1]), int(u[0,2]), int(u[1,2])] line = line + [data.get('serial_number', 1), data.get('name'), data.get('alternate', ''), string.rjust(data.get('residue_name'), 3), data.get('chain_id', ''), data.get('residue_number', 1), data.get('insertion_code', '')] \ + u \ + [data.get('segment_id', ''), string.rjust(data.get('element', ''), 2), data.get('charge', '')] elif type == 'TER': format = ter_format line = line + [data.get('serial_number', 1), string.rjust(data.get('residue_name'), 3), data.get('chain_id', ''), data.get('residue_number', 1), data.get('insertion_code', '')] elif type == 'CONECT': format = conect_format line = line + [data.get('serial_number')] line = line + (data.get('bonded', [])+4*[None])[:4] line = line + (data.get('hydrogen_bonded', [])+4*[None])[:4] line = line + (data.get('salt_bridged', [])+2*[None])[:2] elif type == 'MODEL': format = model_format line = line + [data.get('serial_number')] elif type == 'HEADER': format = header_format line = line + [data.get('compound', ''), data.get('date', ''), data.get('pdb_code')] else: format = generic_format line = line + [data] self.file.write(str(FortranLine(line, format)) + '\n') def writeComment(self, text): """Writes |text| into one or several comment lines. Each line of the text is prefixed with 'REMARK' and written to the file. """ while text: eol = string.find(text,'\n') if eol == -1: eol = len(text) self.file.write('REMARK %s \n' % text[:eol]) text = text[eol+1:] def writeAtom(self, name, position, occupancy=0.0, temperature_factor=0.0, element=''): """Writes an ATOM or HETATM record using the |name|, |occupancy|, |temperature| and |element| information supplied. The residue and chain information is taken from the last calls to the methods nextResidue() and nextChain(). """ if self.het_flag: type = 'HETATM' else: type = 'ATOM' name = string.upper(name) if element != '' and len(element) == 1 and name and name[0] == element: name = ' ' + name self.data['name'] = name self.data['position'] = position self.data['serial_number'] = (self.data['serial_number'] + 1) % 100000 self.data['occupancy'] = occupancy self.data['temperature_factor'] = temperature_factor self.data['element'] = element self.writeLine(type, self.data) def nextResidue(self, name, number = None, terminus = None): """Signals the beginning of a new residue, starting with the next call to writeAtom(). The residue name is |name|, and a |number| can be supplied optionally; by default residues in a chain will be numbered sequentially starting from 1. The value of |terminus| can be 'None', '"C"', or '"N"'; it is passed to export filters that can use this information in order to use different atom or residue names in terminal residues. """ name = string.upper(name) if self.export_filter is not None: name, number = self.export_filter.processResidue(name, number, terminus) self.het_flag = not (name in amino_acids or name in nucleic_acids) self.data['residue_name'] = name self.data['residue_number'] = (self.data['residue_number'] + 1) % 10000 self.data['insertion_code'] = '' if number is not None: if type(number) is type(0): self.data['residue_number'] = number % 10000 else: self.data['residue_number'] = number.number % 10000 self.data['insertion_code'] = number.insertion_code def nextChain(self, chain_id = None, segment_id = ''): """Signals the beginning of a new chain. A chain identifier (string of length one) can be supplied as |chain_id|, by default consecutive letters from the alphabet are used. The equally optional |segment_id| defaults to an empty string. """ if chain_id is None: self.chain_number = (self.chain_number + 1) % len(self._chain_ids) chain_id = self._chain_ids[self.chain_number] if self.export_filter is not None: chain_id, segment_id = \ self.export_filter.processChain(chain_id, segment_id) self.data['chain_id'] = (chain_id+' ')[:1] self.data['segment_id'] = (segment_id+' ')[:4] self.data['residue_number'] = 0 _chain_ids = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def terminateChain(self): "Signals the end of a chain." if self.export_filter is not None: self.export_filter.terminateChain() self.data['serial_number'] = (self.data['serial_number'] + 1) % 100000 self.writeLine('TER', self.data) self.data['chain_id'] = '' self.data['segment_id'] = '' def close(self): """Closes the file. This method *must* be called for write mode because otherwise the file will be incomplete. """ if self.open: if self.output: self.file.write('END\n') self.file.close() self.open = 0 def __del__(self): self.close() # # High-level object representation of PDB file contents. # # # Representation of objects. # class Atom: """Atom in a PDB structure Constructor: Atom(|name|, |position|, |**properties|), where |name| is the PDB atom name (a string), |position| is a atom position (a vector), and |properties| can include any of the other items that can be stored in an atom record. The properties can be obtained or modified using indexing, as for Python dictionaries. """ def __init__(self, name, position, **properties): self.position = position self.properties = properties if self.properties.get('element', '') == '': if name[0] == ' ' or name[0] in string.digits: self.properties['element'] = name[1] elif name[1] in string.digits: self.properties['element'] = name[0] self.name = string.strip(name) def __getitem__(self, item): try: return self.properties[item] except KeyError: if item == 'name': return self.name elif item == 'position': return self.position else: raise KeyError, "Undefined atom property: " + repr(item) def __setitem__(self, item, value): self.properties[item] = value def __str__(self): return self.__class__.__name__ + ' ' + self.name + \ ' at ' + str(self.position) __repr__ = __str__ def type(self): "Returns the six-letter record type, ATOM or HETATM." return 'ATOM ' def writeToFile(self, file): """Writes an atom record to |file| (a PDBFile object or a string containing a file name).""" close = 0 if type(file) == type(''): file = PDBFile(file, 'w') close = 1 file.writeAtom(self.name, self.position, self.properties.get('occupancy', 0.), self.properties.get('temperature_factor', 0.), self.properties.get('element', '')) if close: file.close() class HetAtom(Atom): """HetAtom in a PDB structure A subclass of Atom, which differs only in the return value of the method type(). Constructor: HetAtom(|name|, |position|, |**properties|). """ def type(self): return 'HETATM' class Group: """Atom group (residue or molecule) in a PDB file This is an abstract base class. Instances can be created using one of the subclasses (Molecule, AminoAcidResidue, NucleotideResidue). Group objects permit iteration over atoms with for-loops, as well as extraction of atoms by indexing with the atom name. """ def __init__(self, name, atoms = None, number = None): self.name = name self.number = number self.atom_list = [] self.atoms = {} if atoms: self.atom_list = atoms for a in atoms: self.atoms[a.name] = a def __len__(self): return len(self.atom_list) def __getitem__(self, item): if type(item) == type(0): return self.atom_list[item] else: return self.atoms[item] def __str__(self): s = self.__class__.__name__ + ' ' + self.name + ':\n' for atom in self.atom_list: s = s + ' ' + `atom` + '\n' return s __repr__ = __str__ def isCompatible(self, residue_data): return residue_data['residue_name'] == self.name \ and residue_data['residue_number'] == self.number def addAtom(self, atom): "Adds |atom| (an Atom object) to the group." self.atom_list.append(atom) self.atoms[atom.name] = atom def deleteAtom(self, atom): """Removes |atom| (an Atom object) from the group. An exception will be raised if |atom| is not part of the group. """ self.atom_list.remove(atom) del self.atoms[atom.name] def deleteHydrogens(self): "Removes all hydrogen atoms." delete = [] for a in self.atom_list: if a.name[0] == 'H' or (a.name[0] in string.digits and a.name[1] == 'H'): delete.append(a) for a in delete: self.deleteAtom(a) def changeName(self, name): "Sets the PDB residue name to |name|." self.name = name def writeToFile(self, file): """Writes the group to |file| (a PDBFile object or a string containing a file name). """ close = 0 if type(file) == type(''): file = PDBFile(file, 'w') close = 1 file.nextResidue(self.name, self.number, None) for a in self.atom_list: a.writeToFile(file) if close: file.close() class Molecule(Group): """Molecule in a PDB file A subclass of Group. Constructor: Molecule(|name|, |atoms|='None', |number|=None), where |name| is the PDB residue name. An optional list of |atoms| can be specified, otherwise the molecule is initially empty. The optional |number| is the PDB residue number. Note: In PDB files, non-chain molecules are treated as residues, there is no separate molecule definition. This modules defines every residue as a molecule that is not an amino acid residue or a nucleotide residue. """ pass class Residue(Group): pass class AminoAcidResidue(Residue): """Amino acid residue in a PDB file A subclass of Group. Constructor: AminoAcidResidue(|name|, |atoms|='None', |number|=None), where |name| is the PDB residue name. An optional list of |atoms| can be specified, otherwise the residue is initially empty. The optional |number| is the PDB residue number. """ is_amino_acid = 1 def isCTerminus(self): """Returns 1 if the residue is in C-terminal configuration, i.e. if it has a second oxygen bound to the carbon atom of the peptide group. """ return self.atoms.has_key('OXT') or self.atoms.has_key('OT2') def isNTerminus(self): """Returns 1 if the residue is in N-terminal configuration, i.e. if it contains more than one hydrogen bound to be nitrogen atom of the peptide group. """ return self.atoms.has_key('1HT') or self.atoms.has_key('2HT') \ or self.atoms.has_key('3HT') def writeToFile(self, file): close = 0 if type(file) == type(''): file = PDBFile(file, 'w') close = 1 terminus = None if self.isCTerminus(): terminus = 'C' if self.isNTerminus(): terminus = 'N' file.nextResidue(self.name, self.number, terminus) for a in self.atom_list: a.writeToFile(file) if close: file.close() class NucleotideResidue(Residue): """Nucleotide residue in a PDB file A subclass of Group. Constructor: NucleotideResidue(|name|, |atoms|='None', |number|=None), where |name| is the PDB residue name. An optional list of |atoms| can be specified, otherwise the residue is initially empty. The optional |number| is the PDB residue number. """ is_nucleotide = 1 def __init__(self, name, atoms = None, number = None): self.pdbname = name name = string.strip(name) if name[0] != 'D' and name[0] != 'R': name = 'D' + name Residue.__init__(self, name, atoms, number) for a in atoms: if a.name == 'O2*' or a.name == "O2'": # Ribose self.name = 'R' + self.name[1:] def isCompatible(self, residue_data): return (residue_data['residue_name'] == self.name or residue_data['residue_name'] == self.pdbname) \ and residue_data['residue_number'] == self.number def addAtom(self, atom): Residue.addAtom(self, atom) if atom.name == 'O2*' or atom.name == "O2'": # Ribose self.name = 'R' + self.name[1:] def hasRibose(self): "Returns 1 if the residue has an atom named O2*." return self.atoms.has_key('O2*') or self.atoms.has_key("O2'") def hasDesoxyribose(self): "Returns 1 if the residue has no atom named O2*." return not self.hasRibose() def hasPhosphate(self): "Returns 1 if the residue has a phosphate group." return self.atoms.has_key('P') def hasTerminalH(self): "Returns 1 if the residue has a 3-terminal H atom." return self.atoms.has_key('H3T') def writeToFile(self, file): close = 0 if type(file) == type(''): file = PDBFile(file, 'w') close = 1 terminus = None if not self.hasPhosphate(): terminus = '5' file.nextResidue(self.name[1:], self.number, terminus) for a in self.atom_list: a.writeToFile(file) if close: file.close() class Chain: """Chain of PDB residues This is an abstract base class. Instances can be created using one of the subclasses (PeptideChain, NucleotideChain). Chain objects respond to len() and return their residues by indexing with integers. """ def __init__(self, residues = None, chain_id = None, segment_id = None): if residues is None: self.residues = [] else: self.residues = residues self.chain_id = chain_id self.segment_id = segment_id def __len__(self): return len(self.residues) def sequence(self): "Returns the list of residue names." return map(lambda r: r.name, self.residues) def __getitem__(self, index): return self.residues[index] def addResidue(self, residue): "Add |residue| at the end of the chain." self.residues.append(residue) def removeResidues(self, first, last): """Remove residues starting from |first| up to (but not including) |last|. If |last| is 'None', remove everything starting from |first|. """ if last is None: del self.residues[first:] else: del self.residues[first:last] def deleteHydrogens(self): "Removes all hydrogen atoms." for r in self.residues: r.deleteHydrogens() def writeToFile(self, file): """Writes the chain to |file| (a PDBFile object or a string containing a file name). """ close = 0 if type(file) == type(''): file = PDBFile(file, 'w') close = 1 file.nextChain(self.chain_id, self.segment_id) for r in self.residues: r.writeToFile(file) file.terminateChain() if close: file.close() class PeptideChain(Chain): """Peptide chain in a PDB file A subclass of Chain. Constructor: PeptideChain(|residues|='None', |chain_id|='None', |segment_id|='None'), where |chain_id| is a one-letter chain identifier and |segment_id| is a multi-character chain identifier, both are optional. A list of AminoAcidResidue objects can be passed as |residues|; by default a peptide chain is initially empty. """ def __getslice__(self, i1, i2): return self.__class__(self.residues[i1:i2]) def isTerminated(self): "Returns 1 if the last residue is in C-terminal configuration." return self.residues and self.residues[-1].isCTerminus() def isCompatible(self, chain_data, residue_data): return chain_data['chain_id'] == self.chain_id and \ chain_data['segment_id'] == self.segment_id and \ residue_data['residue_name'] in amino_acids class NucleotideChain(Chain): """Nucleotide chain in a PDB file A subclass of Chain. Constructor: NucleotideChain(|residues|='None', |chain_id|='None', |segment_id|='None'), where |chain_id| is a one-letter chain identifier and |segment_id| is a multi-character chain identifier, both are optional. A list of NucleotideResidue objects can be passed as |residues|; by default a nucleotide chain is initially empty. """ def __getslice__(self, i1, i2): return self.__class__(self.residues[i1:i2]) def isTerminated(self): # impossible to detect for standard PDB files, but we can still # do something useful for certain non-standard files return self.residues and \ (self.residues[-1].name[-1] == '3' or self.residues[-1].hasTerminalH()) def isCompatible(self, chain_data, residue_data): return chain_data['chain_id'] == self.chain_id and \ chain_data['segment_id'] == self.segment_id and \ residue_data['residue_name'] in nucleic_acids class DummyChain(Chain): def __init__(self, structure, chain_id, segment_id): self.structure = structure self.chain_id = chain_id self.segment_id = segment_id def isTerminated(self): return 0 def addResidue(self, residue): self.structure.addMolecule(residue) def isCompatible(self, chain_data, residue_data): return chain_data['chain_id'] == self.chain_id and \ chain_data['segment_id'] == self.segment_id and \ residue_data['residue_name'] not in amino_acids and \ residue_data['residue_name'] not in nucleic_acids # # Residue number class for dealing with insertion codes # class ResidueNumber: """PDB residue number Most PDB residue numbers are simple integers, but when insertion codes are used a number can consist of an integer plus a letter. Such compound residue numbers are represented by this class. Constructor: ResidueNumber(|number|, |insertion_code|) """ def __init__(self, number, insertion_code): self.number = number self.insertion_code = insertion_code def __cmp__(self, other): if type(other) == type(0): if self.number == other: return 1 else: return cmp(self.number, other) if self.number == other.number: return cmp(self.insertion_code, other.insertion_code) else: return cmp(self.number, other.number) def __str__(self): return str(self.number) + self.insertion_code __repr__ = __str__ # # The configuration class. # class Structure: """A high-level representation of the contents of a PDB file Constructor: Structure(|filename|, |model|='0', |alternate_code|='"A"'), where |filename| is the name of the PDB file. Compressed files and URLs are accepted, as for class PDBFile. The two optional arguments specify which data should be read in case of a multiple-model file or in case of a file that contains alternative positions for some atoms. The components of a system can be accessed in several ways ('s' is an instance of this class): - 's.residues' is a list of all PDB residues, in the order in which they occurred in the file. - 's.peptide_chains' is a list of PeptideChain objects, containing all peptide chains in the file in their original order. - 's.nucleotide_chains' is a list of NucleotideChain objects, containing all nucleotide chains in the file in their original order. - 's.molecules' is a list of all PDB residues that are neither amino acid residues nor nucleotide residues, in their original order. - 's.objects' is a list of all high-level objects (peptide chains, nucleotide chains, and molecules) in their original order. An iteration over a Structure instance by a for-loop is equivalent to an iteration over the residue list. """ def __init__(self, filename, model = 0, alternate_code = 'A'): self.filename = filename self.model = model self.alternate = alternate_code self.pdb_code = '' self.residues = [] self.objects = [] self.peptide_chains = [] self.nucleotide_chains = [] self.molecules = {} self.parseFile(PDBFile(filename)) peptide_chain_constructor = PeptideChain nucleotide_chain_constructor = NucleotideChain molecule_constructor = Molecule def __len__(self): return len(self.residues) def __getitem__(self, item): return self.residues[item] def deleteHydrogens(self): "Removes all hydrogen atoms." for r in self.residues: r.deleteHydrogens() def splitPeptideChain(self, number, position): """Splits the peptide chain indicated by |number| (0 being the first peptide chain in the PDB file) after the residue indicated by |position| (0 being the first residue of the chain). The two chain fragments remain adjacent in the peptide chain list, i.e. the numbers of all following nucleotide chains increase by one. """ self._splitChain(self.peptide_chain_constructor, self.peptide_chains, number, position) def splitNucleotideChain(self, number, position): """Splits the nucleotide chain indicated by |number| (0 being the first nucleotide chain in the PDB file) after the residue indicated by |position| (0 being the first residue of the chain). The two chain fragments remain adjacent in the nucleotide chain list, i.e. the numbers of all following nucleotide chains increase by one. """ self._splitChain(self.nucleotide_chain_constructor, self.nucleotide_chains, number, position) def _splitChain(self, constructor, chain_list, number, position): chain = chain_list[number] part1 = constructor(chain.residues[:position], chain.chain_id, chain.segment_id) part2 = constructor(chain.residues[position:]) chain_list[number:number+1] = [part1, part2] index = self.objects.index(chain) self.objects[index:index+1] = [part1, part2] def joinPeptideChains(self, first, second): """Join the two peptide chains indicated by |first| and |second| into one peptide chain. The new chain occupies the position |first|; the chain at |second| is removed from the peptide chain list. """ self._joinChains(self.peptide_chain_constructor, self.peptide_chains, first, second) def joinNucleotideChains(self, first, second): """Join the two nucleotide chains indicated by |first| and |second| into one nucleotide chain. The new chain occupies the position |first|; the chain at |second| is removed from the nucleotide chain list. """ self._joinChains(self.nucleotide_chain_constructor, self.nucleotide_chains, first, second) def _joinChains(self, constructor, chain_list, first, second): chain1 = chain_list[first] chain2 = chain_list[second] total = constructor(chain1.residues+chain2.residues, chain1.chain_id, chain1.segment_id) chain_list[first] = total del chain_list[second] index = self.objects.index(chain1) self.objects[index] = total index = self.objects.index(chain2) del self.objects[index] def addMolecule(self, molecule): try: molecule_list = self.molecules[molecule.name] except KeyError: molecule_list = [] self.molecules[molecule.name] = molecule_list molecule_list.append(molecule) self.objects.append(molecule) def extractData(self, data): atom_data = {} for name in ['serial_number', 'name', 'position', 'occupancy', 'temperature_factor']: atom_data[name] = data[name] for name in ['alternate', 'charge']: value = data[name] if value: atom_data[name] = value element = data['element'] if element != '': try: string.atoi(element) except ValueError: atom_data['element'] = element residue_data = {'residue_name': data['residue_name']} number = data['residue_number'] insertion = data['insertion_code'] if insertion == '': residue_data['residue_number'] = number else: residue_data['residue_number'] = ResidueNumber(number, insertion) chain_data = {} for name in ['chain_id', 'segment_id']: chain_data[name] = data[name] if chain_data['segment_id'] == self.pdb_code: chain_data['segment_id'] = '' return atom_data, residue_data, chain_data def newResidue(self, residue_data): name = residue_data['residue_name'] residue_number = residue_data['residue_number'] if name in amino_acids: residue = AminoAcidResidue(name, [], residue_number) elif name in nucleic_acids: residue = NucleotideResidue(name, [], residue_number) else: residue = self.molecule_constructor(name, [], residue_number) self.residues.append(residue) return residue def newChain(self, residue, chain_data): if hasattr(residue, 'is_amino_acid'): chain = self.peptide_chain_constructor([], chain_data['chain_id'], chain_data['segment_id']) self.peptide_chains.append(chain) self.objects.append(chain) elif hasattr(residue, 'is_nucleotide'): chain = self.nucleotide_chain_constructor([], chain_data['chain_id'], chain_data['segment_id']) self.nucleotide_chains.append(chain) self.objects.append(chain) else: chain = DummyChain(self, chain_data['chain_id'], chain_data['segment_id']) return chain def parseFile(self, file): atom = None residue = None chain = None read = self.model == 0 while 1: type, data = file.readLine() if type == 'END': break elif type == 'HEADER': self.pdb_code = data['pdb_code'] elif type == 'MODEL': read = data['serial_number'] == self.model if self.model == 0 and len(self.residues) == 0: read = 1 elif type == 'ENDMDL': read = 0 elif read: if type == 'ATOM' or type == 'HETATM': alt = data['alternate'] if alt == '' or alt == self.alternate: atom_data, residue_data, chain_data = \ self.extractData(data) if type == 'ATOM': atom = apply(Atom, (), atom_data) else: atom = apply(HetAtom, (), atom_data) new_chain = chain is None or \ not chain.isCompatible(chain_data, residue_data) new_residue = new_chain or residue is None \ or not residue.isCompatible(residue_data) if new_residue and chain is not None and \ chain.isTerminated(): new_chain = 1 if new_residue: residue = self.newResidue(residue_data) if new_chain: chain = self.newChain(residue, chain_data) chain.addResidue(residue) residue.addAtom(atom) elif type == 'ANISOU': alt = data['alternate'] if alt == '' or alt == self.alternate: if atom is None: raise ValueError, "ANISOU record before " + \ "ATOM record" atom['u'] = data['u'] elif type == 'TERM': if chain is None: raise ValueError, "TERM record before chain" chain = None def renumberAtoms(self): "Renumber all atoms sequentially starting with 1." n = 0 for residue in self.residues: for atom in residue: atom['serial_number'] = n n = n + 1 def __repr__(self): s = self.__class__.__name__ + "(" + repr(self.filename) if self.model != 0: s = s + ", model=" + repr(self.model) if self.alternate != 'A': s = s + ", alternate_code = " + repr(self.alternate_code) s = s + "):\n" for name, list in [("Peptide", self.peptide_chains), ("Nucleotide", self.nucleotide_chains)]: for c in list: s = s + " " + name + " chain " if c.segment_id: s = s + c.segment_id + " " elif c.chain_id: s = s + c.chain_id + " " s = s + "of length " + repr(len(c)) + "\n" for name, list in self.molecules.items(): s = s + " " + repr(len(list)) + " " + name + " molecule" if len(list) == 1: s = s + "\n" else: s = s + "s\n" return s def writeToFile(self, file): """Writes all objects to |file| (a PDBFile object or a string containing a file name). """ close = 0 if type(file) == type(''): file = PDBFile(file, 'w') close = 1 for o in self.objects: o.writeToFile(file) if close: file.close() if __name__ == '__main__': if 0: file = PDBFile('~/3lzt.pdb') copy = PDBFile('test.pdb', 'w', 'xplor') while 1: type, data = file.readLine() if type == 'END': break copy.writeLine(type, data) copy.close() if 1: s = Structure('~/detached/okb.pdb') #s = Structure('./3lzt.pdb') #s = Structure('~/1tka.pdb') print s
Apartment 2 * Small Seestraße * - With a floor space of 22 m², the apartment can accommodate 2 persons Facilities: • Combined living / sleeping area with double bed • Furthermore offers the apartment a sofa, a flat-screen TV and plenty of storage space • The separate.. kitchen with small dining area feature. 2 plate induction cooker, refrigerator, microwave and various kitchen utensils • the bathroom has a shower / WC and hair dryer • the apartment has a small möbelierte terrace • your car can be parked on the property.. . • for you have brought sports equipment is a lockable storage room. Apartments * * Seestraße located on the property of the landlord on the ground floor. The holiday homes are centrally located but quiet in the town Sassnitz. Within walking distance to the city harbor, public transport is very close. Sassnitz is a "state-approved recreation" and therefore kurabgabepflichtig. New building holiday house super modern everything including linen etc.
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'UserSubscriptionFolders', fields ['user'] db.create_unique('reader_usersubscriptionfolders', ['user_id']) # Changing field 'UserSubscription.needs_unread_recalc' db.alter_column('reader_usersubscription', 'needs_unread_recalc', self.gf('django.db.models.fields.BooleanField')(blank=True)) # Changing field 'UserSubscription.is_trained' db.alter_column('reader_usersubscription', 'is_trained', self.gf('django.db.models.fields.BooleanField')(blank=True)) # Changing field 'UserSubscription.active' db.alter_column('reader_usersubscription', 'active', self.gf('django.db.models.fields.BooleanField')(blank=True)) def backwards(self, orm): # Removing unique constraint on 'UserSubscriptionFolders', fields ['user'] db.delete_unique('reader_usersubscriptionfolders', ['user_id']) # Changing field 'UserSubscription.needs_unread_recalc' db.alter_column('reader_usersubscription', 'needs_unread_recalc', self.gf('django.db.models.fields.BooleanField')()) # Changing field 'UserSubscription.is_trained' db.alter_column('reader_usersubscription', 'is_trained', self.gf('django.db.models.fields.BooleanField')()) # Changing field 'UserSubscription.active' db.alter_column('reader_usersubscription', 'active', self.gf('django.db.models.fields.BooleanField')()) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'reader.feature': { 'Meta': {'object_name': 'Feature'}, 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'description': ('django.db.models.fields.TextField', [], {'default': "''"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'reader.userstory': { 'Meta': {'unique_together': "(('user', 'feed', 'story'),)", 'object_name': 'UserStory'}, 'feed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rss_feeds.Feed']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'opinion': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'read_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'story': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rss_feeds.Story']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'reader.usersubscription': { 'Meta': {'unique_together': "(('user', 'feed'),)", 'object_name': 'UserSubscription'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'feed': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subscribers'", 'to': "orm['rss_feeds.Feed']"}), 'feed_opens': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_trained': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_read_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2010, 10, 22, 2, 45, 34, 980447)'}), 'mark_read_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2010, 10, 22, 2, 45, 34, 980447)'}), 'needs_unread_recalc': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'unread_count_negative': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'unread_count_neutral': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'unread_count_positive': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'unread_count_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subscriptions'", 'to': "orm['auth.User']"}) }, 'reader.usersubscriptionfolders': { 'Meta': {'object_name': 'UserSubscriptionFolders'}, 'folders': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'rss_feeds.feed': { 'Meta': {'object_name': 'Feed', 'db_table': "'feeds'"}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'active_subscribers': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'average_stories_per_month': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'creation': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'days_to_trim': ('django.db.models.fields.IntegerField', [], {'default': '90'}), 'etag': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'exception_code': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'feed_address': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '255'}), 'feed_link': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '1000', 'null': 'True', 'blank': 'True'}), 'feed_tagline': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'null': 'True', 'blank': 'True'}), 'feed_title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'fetched_once': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'has_feed_exception': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}), 'has_page_exception': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_load_time': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'last_modified': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'last_update': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}), 'min_to_decay': ('django.db.models.fields.IntegerField', [], {'default': '15'}), 'next_scheduled_update': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}), 'num_subscribers': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'popular_authors': ('django.db.models.fields.CharField', [], {'max_length': '2048', 'null': 'True', 'blank': 'True'}), 'popular_tags': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}), 'premium_subscribers': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'queued_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}), 'stories_last_month': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'story_count_history': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'rss_feeds.story': { 'Meta': {'unique_together': "(('story_feed', 'story_guid_hash'),)", 'object_name': 'Story', 'db_table': "'stories'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'story_author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rss_feeds.StoryAuthor']"}), 'story_author_name': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'story_content': ('utils.compressed_textfield.StoryField', [], {'null': 'True', 'blank': 'True'}), 'story_content_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'story_date': ('django.db.models.fields.DateTimeField', [], {}), 'story_feed': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stories'", 'to': "orm['rss_feeds.Feed']"}), 'story_guid': ('django.db.models.fields.CharField', [], {'max_length': '1000'}), 'story_guid_hash': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'story_original_content': ('utils.compressed_textfield.StoryField', [], {'null': 'True', 'blank': 'True'}), 'story_past_trim_date': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'story_permalink': ('django.db.models.fields.CharField', [], {'max_length': '1000'}), 'story_tags': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}), 'story_title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'rss_feeds.storyauthor': { 'Meta': {'object_name': 'StoryAuthor'}, 'author_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'feed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rss_feeds.Feed']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['reader']
SC, 24 x 32 cm., 2nd Ed. Winner of the Price of the best young photobook 2007 in Arles. We love it!
from django.db.utils import OperationalError from django.contrib.contenttypes.models import ContentType PLUGIN_NAME = 'Current Issue' DESCRIPTION = 'This is a homepage element that renders featured current issues.' AUTHOR = 'Martin Paul Eve' def install(): import core.models as core_models import journal.models as journal_models import press.models as press_models # check whether this homepage element has already been installed for all journals journals = journal_models.Journal.objects.all() for journal in journals: content_type = ContentType.objects.get_for_model(journal) element, created = core_models.HomepageElement.objects.get_or_create( name=PLUGIN_NAME, configure_url='current_issue_setup', template_path='journal/homepage_elements/issue_block.html', content_type=content_type, object_id=journal.pk, has_config=True) element.save() presses = press_models.Press.objects.all() for press in presses: content_type = ContentType.objects.get_for_model(press) element, created = core_models.HomepageElement.objects.get_or_create( name=PLUGIN_NAME, configure_url='current_issue_setup', template_path='journal/homepage_elements/issue_block.html', content_type=content_type, object_id=press.pk, has_config=True) element.save() def hook_registry(): try: install() return { 'yield_homepage_element_context': { 'module': 'core.homepage_elements.issue.hooks', 'function': 'yield_homepage_element_context', 'name': PLUGIN_NAME, } } except OperationalError: # if we get here the database hasn't yet been created return {} except BaseException: return {}
Exchange Autodiscover is deceptively simple. Until it doesn’t work. Then, repairing autodiscover can be surprisingly challenging. Microsoft does provide the Microsoft Connectivity Analyzer which can (among other things) give you detailed information about your autodiscover situation. However, it works “from the outside to the inside”. This PowerShell allows you to work “from the inside to the outside”. The script below allows you to test autodiscover to a specific server. If it succeeds, but your overall autodiscover fails, then you have a far reduced set of things to investigate, in order to repair your autodiscover deployment. This script will allow you to test internally or externally (given that your firewall/router has the appropriate NAT forwarding/translation rules and DNS is properly configured). If an internal test succeeds, but an external test fails – this points you to load-balancer/firewall/router. If the internal test fails – then you may have several items to check. Read the source of the script below for the most common issues. I am developing a script that works “the same way” as Outlook is documented to work for autodiscover – with more insight to the various steps. While I have it working today, it’s not a pretty script. 🙂 I will post it when it is more clean. ### your real autodiscover host, the responses will be the same. ### of the Microsoft provided tools give you that flexibility. ### all three of username, password, and emailAddress. ### of the script. Look below. ### This is not a list of all possible issues. ### will attempt to figure out what is going on. However - no promises. throw "You must provide a hostname" $str = Read-Host "Enter username for request" throw "You must provide a username" $str = Read-Host -AsSecureString "Enter password for $username" throw "You must provide a password" $str = Read-Host "Enter email address for $username" throw "You must provide an emailaddress" $autoDiscoverRequest = $autoDiscoverRequest.Replace( "`t", '' ) ### remove tab characters from the autodiscoverrequest. Exchange doesn't like those tabs. ### the computer is on a LAN or connected via a VPN or connected via DirectAccess). ### separated by a colon. That's all. Never use except with SSL! ### autodiscover has knowledge about user-agents. i found that surprising. write-error "Webpage response is empty." Previous PostPrevious PowerShell Quick Script: Would You Like to Play a Game?
# /usr/bin/env python """ This module has utility functions for gathering up the static content that is defined by XModules and XModuleDescriptors (javascript and css) """ import logging import hashlib import os import errno import sys from collections import defaultdict from docopt import docopt from path import path from xmodule.x_module import XModuleDescriptor LOG = logging.getLogger(__name__) def write_module_styles(output_root): """Write all registered XModule css, sass, and scss files to output root.""" return _write_styles('.xmodule_display', output_root, _list_modules()) def write_module_js(output_root): """Write all registered XModule js and coffee files to output root.""" return _write_js(output_root, _list_modules()) def write_descriptor_styles(output_root): """Write all registered XModuleDescriptor css, sass, and scss files to output root.""" return _write_styles('.xmodule_edit', output_root, _list_descriptors()) def write_descriptor_js(output_root): """Write all registered XModuleDescriptor js and coffee files to output root.""" return _write_js(output_root, _list_descriptors()) def _list_descriptors(): """Return a list of all registered XModuleDescriptor classes.""" return [ desc for desc in [ desc for (_, desc) in XModuleDescriptor.load_classes() ] ] def _list_modules(): """Return a list of all registered XModule classes.""" return [ desc.module_class for desc in _list_descriptors() ] def _ensure_dir(directory): """Ensure that `directory` exists.""" try: os.makedirs(directory) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise def _write_styles(selector, output_root, classes): """ Write the css fragments from all XModules in `classes` into `output_root` as individual files, hashed by the contents to remove duplicates """ contents = {} css_fragments = defaultdict(set) for class_ in classes: class_css = class_.get_css() for filetype in ('sass', 'scss', 'css'): for idx, fragment in enumerate(class_css.get(filetype, [])): css_fragments[idx, filetype, fragment].add(class_.__name__) css_imports = defaultdict(set) for (idx, filetype, fragment), classes in sorted(css_fragments.items()): fragment_name = "{idx:0=3d}-{hash}.{type}".format( idx=idx, hash=hashlib.md5(fragment).hexdigest(), type=filetype) # Prepend _ so that sass just includes the files into a single file filename = '_' + fragment_name contents[filename] = fragment for class_ in classes: css_imports[class_].add(fragment_name) module_styles_lines = [] module_styles_lines.append("@import 'bourbon/bourbon';") module_styles_lines.append("@import 'bourbon/addons/button';") module_styles_lines.append("@import 'assets/anims';") for class_, fragment_names in css_imports.items(): module_styles_lines.append("""{selector}.xmodule_{class_} {{""".format( class_=class_, selector=selector )) module_styles_lines.extend(' @import "{0}";'.format(name) for name in fragment_names) module_styles_lines.append('}') contents['_module-styles.scss'] = '\n'.join(module_styles_lines) _write_files(output_root, contents) def _write_js(output_root, classes): """ Write the javascript fragments from all XModules in `classes` into `output_root` as individual files, hashed by the contents to remove duplicates """ contents = {} js_fragments = set() for class_ in classes: module_js = class_.get_javascript() # It will enforce 000 prefix for xmodule.js. js_fragments.add((0, 'js', module_js.get('xmodule_js'))) for filetype in ('coffee', 'js'): for idx, fragment in enumerate(module_js.get(filetype, [])): js_fragments.add((idx + 1, filetype, fragment)) for idx, filetype, fragment in sorted(js_fragments): filename = "{idx:0=3d}-{hash}.{type}".format( idx=idx, hash=hashlib.md5(fragment).hexdigest(), type=filetype) contents[filename] = fragment _write_files(output_root, contents, {'.coffee': '.js'}) return [output_root / filename for filename in contents.keys()] def _write_files(output_root, contents, generated_suffix_map=None): """ Write file contents to output root. Any files not listed in contents that exists in output_root will be deleted, unless it matches one of the patterns in `generated_suffix_map`. output_root (path): The root directory to write the file contents in contents (dict): A map from filenames to file contents to be written to the output_root generated_suffix_map (dict): Optional. Maps file suffix to generated file suffix. For any file in contents, if the suffix matches a key in `generated_suffix_map`, then the same filename with the suffix replaced by the value from `generated_suffix_map` will be ignored """ _ensure_dir(output_root) to_delete = set(file.basename() for file in output_root.files()) - set(contents.keys()) if generated_suffix_map: for output_file in contents.keys(): for suffix, generated_suffix in generated_suffix_map.items(): if output_file.endswith(suffix): to_delete.discard(output_file.replace(suffix, generated_suffix)) for extra_file in to_delete: (output_root / extra_file).remove_p() for filename, file_content in contents.iteritems(): output_file = output_root / filename not_file = not output_file.isfile() # not_file is included to short-circuit this check, because # read_md5 depends on the file already existing write_file = not_file or output_file.read_md5() != hashlib.md5(file_content).digest() # pylint: disable=too-many-function-args if write_file: LOG.debug("Writing %s", output_file) output_file.write_bytes(file_content) else: LOG.debug("%s unchanged, skipping", output_file) def main(): """ Generate Usage: static_content.py <output_root> """ args = docopt(main.__doc__) root = path(args['<output_root>']) write_descriptor_js(root / 'descriptors/js') write_descriptor_styles(root / 'descriptors/css') write_module_js(root / 'modules/js') write_module_styles(root / 'modules/css') if __name__ == '__main__': sys.exit(main())
On 15 November 2018, Brian Silvia and Andrew Cummins of BRI Ferrier were appointed as Voluntary Administrators to the Strongbuild Group of Companies consisting of Strongbuild Pty Limited, Strongbuild Manufacturing Pty Limited and Strongbuild Commercial Pty Limited. Strongbuild commenced in 2000 and is a Home, Multi-Residential, Commercial and Retirement Village Builder operating in Sydney and the Illawarra, Southern Highlands and South Coast regions. In recent years Strongbuild has invested significant capital to develop a world's best practice manufacturing division specialising in the offsite production of environmentally friendly modules, significantly reducing the building times for residential and commercial/multi-site projects. The Voluntary Administration appointment was precipitated by the Group's weakened financial position as a result of the recent termination of a $45m construction contract. The Group employs 150 staff and currently has approximately 50 projects on foot. The Administrators are currently reviewing the Group's financial position and assessing the viability to continue to trade and complete the projects. Employees may be stood down for a brief period whilst we undertake our review. The Administrators intend to undertake a sale of business for either the whole of the business or each of its divisions. The Administrators are confident that there will be strong interest from prospective purchasers. Further information will be made available on the current matters page of the BRI Ferrier website as the administration proceeds.
from miasm2.ir.symbexec import SymbolicExecutionEngine, StateEngine from miasm2.expression.simplifications import expr_simp from miasm2.expression.expression import ExprId, ExprInt, ExprSlice,\ ExprMem, ExprCond, ExprCompose, ExprOp from miasm2.core import asmblock TOPSTR = "TOP" def exprid_top(expr): """Return a TOP expression (ExprId("TOP") of size @expr.size @expr: expression to replace with TOP """ return ExprId(TOPSTR, expr.size) class SymbolicStateTop(StateEngine): def __init__(self, dct, regstop): self._symbols = frozenset(dct.items()) self._regstop = frozenset(regstop) def __hash__(self): return hash((self.__class__, self._symbols, self._regstop)) def __str__(self): out = [] for dst, src in sorted(self._symbols): out.append("%s = %s" % (dst, src)) for dst in self._regstop: out.append('TOP %s' %dst) return "\n".join(out) def __eq__(self, other): if self is other: return True if self.__class__ != other.__class__: return False return (self.symbols == other.symbols and self.regstop == other.regstop) def __iter__(self): for dst, src in self._symbols: yield dst, src def merge(self, other): """Merge two symbolic states Only equal expressions are kept in both states @other: second symbolic state """ symb_a = self.symbols symb_b = other.symbols intersection = set(symb_a.keys()).intersection(symb_b.keys()) diff = set(symb_a.keys()).union(symb_b.keys()).difference(intersection) symbols = {} regstop = set() for dst in diff: if dst.is_id(): regstop.add(dst) for dst in intersection: if symb_a[dst] == symb_b[dst]: symbols[dst] = symb_a[dst] else: regstop.add(dst) return self.__class__(symbols, regstop) @property def symbols(self): """Return the dictionnary of known symbols""" return dict(self._symbols) @property def regstop(self): """Return the set of expression with TOP values""" return self._regstop class SymbExecTopNoMem(SymbolicExecutionEngine): """ Symbolic execution, include TOP value. ExprMem are not propagated. Any computation involving a TOP will generate TOP. """ StateEngine = SymbolicStateTop def __init__(self, ir_arch, state, regstop, func_read=None, func_write=None, sb_expr_simp=expr_simp): known_symbols = dict(state) super(SymbExecTopNoMem, self).__init__(ir_arch, known_symbols, func_read, func_write, sb_expr_simp) self.regstop = set(regstop) def get_state(self): """Return the current state of the SymbolicEngine""" return self.StateEngine(self.symbols, self.regstop) def eval_expr(self, expr, eval_cache=None): if expr in self.regstop: return exprid_top(expr) ret = self.apply_expr_on_state(expr, eval_cache) return ret def manage_mem(self, expr, state, cache, level): ptr = self.apply_expr_on_state_visit_cache(expr.arg, state, cache, level+1) ret = ExprMem(ptr, expr.size) ret = self.get_mem_state(ret) if ret.is_mem() and not ret.arg.is_int() and ret.arg == ptr: ret = exprid_top(expr) assert expr.size == ret.size return ret def apply_expr_on_state_visit_cache(self, expr, state, cache, level=0): """ Deep First evaluate nodes: 1. evaluate node's sons 2. simplify """ if expr in cache: ret = cache[expr] elif expr in state: return state[expr] elif expr.is_int(): ret = expr elif expr.is_id(): if isinstance(expr.name, asmblock.asm_label) and expr.name.offset is not None: ret = ExprInt(expr.name.offset, expr.size) elif expr in self.regstop: ret = exprid_top(expr) else: ret = state.get(expr, expr) elif expr.is_mem(): ret = self.manage_mem(expr, state, cache, level) elif expr.is_cond(): cond = self.apply_expr_on_state_visit_cache(expr.cond, state, cache, level+1) src1 = self.apply_expr_on_state_visit_cache(expr.src1, state, cache, level+1) src2 = self.apply_expr_on_state_visit_cache(expr.src2, state, cache, level+1) if cond.is_id(TOPSTR) or src1.is_id(TOPSTR) or src2.is_id(TOPSTR): ret = exprid_top(expr) else: ret = ExprCond(cond, src1, src2) elif expr.is_slice(): arg = self.apply_expr_on_state_visit_cache(expr.arg, state, cache, level+1) if arg.is_id(TOPSTR): ret = exprid_top(expr) else: ret = ExprSlice(arg, expr.start, expr.stop) elif expr.is_op(): args = [] for oarg in expr.args: arg = self.apply_expr_on_state_visit_cache(oarg, state, cache, level+1) assert oarg.size == arg.size if arg.is_id(TOPSTR): return exprid_top(expr) args.append(arg) ret = ExprOp(expr.op, *args) elif expr.is_compose(): args = [] for arg in expr.args: arg = self.apply_expr_on_state_visit_cache(arg, state, cache, level+1) if arg.is_id(TOPSTR): return exprid_top(expr) args.append(arg) ret = ExprCompose(*args) else: raise TypeError("Unknown expr type") ret = self.expr_simp(ret) assert expr.size == ret.size cache[expr] = ret return ret def apply_change(self, dst, src): eval_cache = {} if dst.is_mem(): # If Write to TOP, forget all memory information ret = self.eval_expr(dst.arg, eval_cache) if ret.is_id(TOPSTR): to_del = set() for dst_tmp in self.symbols: if dst_tmp.is_mem(): to_del.add(dst_tmp) for dst_to_del in to_del: del self.symbols[dst_to_del] return src_o = self.expr_simp(src) # Force update. Ex: # EBX += 1 (state: EBX = EBX+1) # EBX -= 1 (state: EBX = EBX, must be updated) if dst in self.regstop: self.regstop.discard(dst) self.symbols[dst] = src_o if dst == src_o: # Avoid useless X = X information del self.symbols[dst] if src_o.is_id(TOPSTR): if dst in self.symbols: del self.symbols[dst] self.regstop.add(dst) class SymbExecTop(SymbExecTopNoMem): """ Symbolic execution, include TOP value. ExprMem are propagated. Any computation involving a TOP will generate TOP. WARNING: avoid memory aliases here! """ def manage_mem(self, expr, state, cache, level): ptr = self.apply_expr_on_state_visit_cache(expr.arg, state, cache, level+1) ret = ExprMem(ptr, expr.size) ret = self.get_mem_state(ret) assert expr.size == ret.size return ret
The achievements Dior is based on element around the inventiveness of owner, Orlando Dior. Several consumers would like to make use of a great-superior replica, nevertheless, you surely must not pay developer price ranges for at wholesale prices carriers that are almost certainly not real. Bag closures like Velcro, zips and over unity magnetic flap can verify essential to avoid the chance of your stuff receding. Checking out significant societal web-sites and having great inspired solutions in Malaga can be quite straightforward to do, even within a strict budget. Remarkably, it isn't just women that give thought to details in terms of picking a difficult-wearing, functional and classy bags. These totes advise me of those who had been preferred as i what food was in twelfth grade. Unexpected influx of income from state taxation has lessened the requirement of some instant slashes from the Co spending budget, but an agent for said tough deliver the results remains to be to shut the budget difference. A lot of career most women also believe that it is beneficial specially in their daily expert pursuits. Cd save buying is definitely an outing. The decision and number of replica designer handbags has boomed to epic proportions into numerous layouts, patterns, colors and fabrics, each and every having a various function and a sense celebration. Every one of these internet sites have devoted portions for general purses and general scarves as well as other goods and within minutes it will be easy to view during the entire assortment. I received my favorite essence coloration billfold plus the easy and vibrant buckskin appear would make me this way pockets much. Wide range of replicate replicas of cab accessories is available in the market. There are several available that happen to be just stunning. Platinum firmness is hardware. You possibly can provide the info on exactly where it absolutely was dropped making sure that quite a few through the law enforcement to uncover your pockets. BLUEDG present laides handbags,sneakers,vogue,jewellery,et cetera. The heat and luxury standing of sleeping-bags are assessed in the seasons based on their excessive and luxury temperature. His bubble skirts and strange, elegant, yet extra-modern day patterns ended up trademarks of your home. In 1914 Burberry adapted its officer's layer for the trench circumstances of your First Planet War. Soft to the touch, Sundance functions natural-side engineering, give-credit scoring particulars Replica Designer Handbags and supplies vibrant, household leather homes. There are plenty of merchants online giving the items and you can get great reductions on there. You know it should be true should you never have viewed like great buy or purchase ahead of identified at this moment for your sale made or great buy, such as leaving business enterprise for example. Progressive services and products aren't without the need of submission, procedure, or stability problems. It ought to be really worth your dollars when you purchase a synthetic leather purse. Coach's principal developer was Bonnie Cashin and he or she caused a revolution in the custom tote sector. This is when money might be held. There's a compartment exclusively newspaper money using provisions for safe-keeping of greeting cards. I used to be for the purpose of larger elements. Bodhi carriers convey a Far Eastern school of thought and provide with regards to a zen like excellent and appeal to the wearer. Crucial paperwork and view training books can certainly be safely put within it. This LV tote features by itself with a prominent rare metal name plate with InLouis Vuitton" in piece of software versus its dark brown material outside. I blushed to begin. These handbags provide stylish personal DB now its decorative, Replica Louis Vuitton Handbags fancyful Bumblebee style and design. Proceed stitching additional base corner. It no easy factor .you may must shell out a lot, time or dollars. Thus, chest muscles depth and larger around waistline girls ought to decide an oblong travelling bag though chiseled chest muscles, narrow body shape women should choose the inside on the thickness with the pie case so as to enable the a little bit podgy all over.
#!/usr/bin/python import sys import urllib2 RAINX_STAT_KEYS = [ ("rainx.reqpersec", "total_reqpersec"), ("rainx.reqputpersec", "put_reqpersec"), ("rainx.reqgetpersec", "get_reqpersec"), ("rainx.avreqtime", "total_avreqtime"), ("rainx.avputreqtime", "put_avreqtime"), ("rainx.avgetreqtime", "get_avreqtime"), ] def parse_info(stream): data = {} for line in stream.readlines(): parts = line.split() if len(parts) > 1: # try to cast value to int or float try: value = int(parts[1]) except ValueError: try: value = float(parts[1]) except ValueError: value = parts[1] data[parts[0]] = value else: data[parts[0]] = None return data def get_stat_lines(url, stat_keys): stream = urllib2.urlopen(url) data = parse_info(stream) stream.close() stats = [("stat.%s = %s" % (k[1], str(data[k[0]]))) for k in stat_keys if k[0] in data] return stats def main(args): ip_port = args[1].split("|")[2] stats_url = "http://%s/stat" % ip_port for stat in get_stat_lines(stats_url, RAINX_STAT_KEYS): print stat if __name__ == "__main__": main(sys.argv)
*** BOTH designs shown included. This is an SVG, PNG , DXF and EPS in zipped folder. PNG is 300 DPI with glitter and transparent background.
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.rnn.python.ops.fused_rnn_cell.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.rnn.python.ops import fused_rnn_cell from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import init_ops from tensorflow.python.ops import rnn from tensorflow.python.ops import rnn_cell from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test class FusedRnnCellTest(test.TestCase): def testBasicRNNFusedWrapper(self): """This test checks that using a wrapper for BasicRNN works as expected.""" with self.cached_session() as sess: initializer = init_ops.random_uniform_initializer( -0.01, 0.01, seed=19890212) cell = rnn_cell.BasicRNNCell(10) batch_size = 5 input_size = 20 timelen = 15 inputs = constant_op.constant( np.random.randn(timelen, batch_size, input_size)) with variable_scope.variable_scope("basic", initializer=initializer): unpacked_inputs = array_ops.unstack(inputs) outputs, state = rnn.static_rnn( cell, unpacked_inputs, dtype=dtypes.float64) packed_outputs = array_ops.stack(outputs) basic_vars = [ v for v in variables.trainable_variables() if v.name.startswith("basic/") ] sess.run([variables.global_variables_initializer()]) basic_outputs, basic_state = sess.run([packed_outputs, state]) basic_grads = sess.run(gradients_impl.gradients(packed_outputs, inputs)) basic_wgrads = sess.run( gradients_impl.gradients(packed_outputs, basic_vars)) with variable_scope.variable_scope( "fused_static", initializer=initializer): fused_cell = fused_rnn_cell.FusedRNNCellAdaptor( rnn_cell.BasicRNNCell(10)) outputs, state = fused_cell(inputs, dtype=dtypes.float64) fused_static_vars = [ v for v in variables.trainable_variables() if v.name.startswith("fused_static/") ] sess.run([variables.global_variables_initializer()]) fused_static_outputs, fused_static_state = sess.run([outputs, state]) fused_static_grads = sess.run(gradients_impl.gradients(outputs, inputs)) fused_static_wgrads = sess.run( gradients_impl.gradients(outputs, fused_static_vars)) self.assertAllClose(basic_outputs, fused_static_outputs) self.assertAllClose(basic_state, fused_static_state) self.assertAllClose(basic_grads, fused_static_grads) for basic, fused in zip(basic_wgrads, fused_static_wgrads): self.assertAllClose(basic, fused, rtol=1e-2, atol=1e-2) with variable_scope.variable_scope( "fused_dynamic", initializer=initializer): fused_cell = fused_rnn_cell.FusedRNNCellAdaptor( rnn_cell.BasicRNNCell(10), use_dynamic_rnn=True) outputs, state = fused_cell(inputs, dtype=dtypes.float64) fused_dynamic_vars = [ v for v in variables.trainable_variables() if v.name.startswith("fused_dynamic/") ] sess.run([variables.global_variables_initializer()]) fused_dynamic_outputs, fused_dynamic_state = sess.run([outputs, state]) fused_dynamic_grads = sess.run( gradients_impl.gradients(outputs, inputs)) fused_dynamic_wgrads = sess.run( gradients_impl.gradients(outputs, fused_dynamic_vars)) self.assertAllClose(basic_outputs, fused_dynamic_outputs) self.assertAllClose(basic_state, fused_dynamic_state) self.assertAllClose(basic_grads, fused_dynamic_grads) for basic, fused in zip(basic_wgrads, fused_dynamic_wgrads): self.assertAllClose(basic, fused, rtol=1e-2, atol=1e-2) def testTimeReversedFusedRNN(self): with self.cached_session() as sess: initializer = init_ops.random_uniform_initializer( -0.01, 0.01, seed=19890213) fw_cell = rnn_cell.BasicRNNCell(10) bw_cell = rnn_cell.BasicRNNCell(10) batch_size = 5 input_size = 20 timelen = 15 inputs = constant_op.constant( np.random.randn(timelen, batch_size, input_size)) # test bi-directional rnn with variable_scope.variable_scope("basic", initializer=initializer): unpacked_inputs = array_ops.unstack(inputs) outputs, fw_state, bw_state = rnn.static_bidirectional_rnn( fw_cell, bw_cell, unpacked_inputs, dtype=dtypes.float64) packed_outputs = array_ops.stack(outputs) basic_vars = [ v for v in variables.trainable_variables() if v.name.startswith("basic/") ] sess.run([variables.global_variables_initializer()]) basic_outputs, basic_fw_state, basic_bw_state = sess.run( [packed_outputs, fw_state, bw_state]) basic_grads = sess.run(gradients_impl.gradients(packed_outputs, inputs)) basic_wgrads = sess.run( gradients_impl.gradients(packed_outputs, basic_vars)) with variable_scope.variable_scope("fused", initializer=initializer): fused_cell = fused_rnn_cell.FusedRNNCellAdaptor( rnn_cell.BasicRNNCell(10)) fused_bw_cell = fused_rnn_cell.TimeReversedFusedRNN( fused_rnn_cell.FusedRNNCellAdaptor(rnn_cell.BasicRNNCell(10))) fw_outputs, fw_state = fused_cell( inputs, dtype=dtypes.float64, scope="fw") bw_outputs, bw_state = fused_bw_cell( inputs, dtype=dtypes.float64, scope="bw") outputs = array_ops.concat([fw_outputs, bw_outputs], 2) fused_vars = [ v for v in variables.trainable_variables() if v.name.startswith("fused/") ] sess.run([variables.global_variables_initializer()]) fused_outputs, fused_fw_state, fused_bw_state = sess.run( [outputs, fw_state, bw_state]) fused_grads = sess.run(gradients_impl.gradients(outputs, inputs)) fused_wgrads = sess.run(gradients_impl.gradients(outputs, fused_vars)) self.assertAllClose(basic_outputs, fused_outputs) self.assertAllClose(basic_fw_state, fused_fw_state) self.assertAllClose(basic_bw_state, fused_bw_state) self.assertAllClose(basic_grads, fused_grads) for basic, fused in zip(basic_wgrads, fused_wgrads): self.assertAllClose(basic, fused, rtol=1e-2, atol=1e-2) if __name__ == "__main__": test.main()
Very often while watching a sci-fi movie we ask ourselves how the future’s cities will be. Already in the last centuries the humans asked themselves which new technologies will spread and which, instead, will irreparably disappear to let the progress go. Let’s see together what is easy to predict for the next future. One of the aspect that most characterises the today’s cities is the endless presence of houses, skyscrapers, buildings, car parkings, etc. This obviusly brings to the thing that we could define an important “visual pollution” which unfortunatelly denies the possibilty to see nothing more than cement’s buildings all around. One of the possible change of the future’s cities will be focused on this kind of problems. Already in many cities, infact, they started to adopt the strategy to put in the underground buildings like for example car parks going so to substantially reduce the visual pollution. As shown in many movies the future’s systems will be completely automated and they will allow to have platforms that will bring the car directly in its place. This will help to make the cities less busy from the structural point of view allowing the citiziens to enjoy even some interesting glimpse. How it is easy to predict in the future’s cities the main rule will be only one: the technology at the service of the human. This can obviusly have many different uses which, at least partly, are already visible nowadays. Let’s start for example from the one that will be the traffic and new cars’ managing. One of the problems in more or less all the cities is the one about the smog and the acoustic pollution caused by the cars. Vehicles that pollute and that generate a big noise in their way making some cities totally unlivable in the busy times. One of the solution that will be with every probability gave is the one about the electric cars, hybrids and with autonomous driving. We know well that those models are already developing and that their spread increase year by year at the point that according to the predicitons until the 2030 the number of the vehicles out there will reach important numbers. The technology though can’t be used only for the driving but, instead, there are many fields where it can be used. For example the domotics can be one of them because it represents a rapidly growing field. Currently the smart houses are able to regulate the temperatures, to communicate with their owner through an app, to switch on household appliances and so on. In the future obviusly there will be some improvments even under this point of view. There will be for example fridges that will tell us when a food is maturing, the heatings will switch on themselves only when there will be people for an energy saving and in general the functions of our home will be totally revolutionized. One of the question that is questionable at this point is: and there will be the robots in the future’s cities? The humanoid robotic during the last years made giant’s steps and it is easy to assume that in the next future they will be a constant presence. The robots could be in all the houses and they could really represent an important resource. We will have robots that will cook, other that will take care of us or of the children. This represent without any doubt an essential help even to do those activities that for many reasons we can’t do like heavy jobs, etc. Furthermore, it cannot be excluded that in the future they could represent a resource even for the public transport or for the services.
# -*- coding: UTF-8 -*- import wx from outwiker.core.application import Application from outwiker.core.events import PageDialogPageFactoriesNeededParams from outwiker.gui.preferences.baseprefpanel import BasePrefPanel from pagetypecolor.i18n import get_ from pagetypecolor.colorslist import ColorsList class PreferencePanel(BasePrefPanel): """ Панель с настройками """ def __init__(self, parent, config): """ parent - родитель панели(должен быть wx.Treebook) config - настройки из plugin._application.config """ super(PreferencePanel, self).__init__(parent) global _ _ = get_() self._application = Application # Key - page type string, value - ColorPicker instance self._colorPickers = {} self._colorsList = ColorsList(self._application) self.__createGui() self.SetupScrolling() def __createGui(self): """ Создать элементы управления """ mainSizer = wx.FlexGridSizer(cols=2) mainSizer.AddGrowableCol(0) mainSizer.AddGrowableCol(1) descriptionLabel = wx.StaticText( self, -1, _(u'The colors for the various page types') ) mainSizer.Add(descriptionLabel, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=2) mainSizer.AddSpacer(0) eventParams = PageDialogPageFactoriesNeededParams(None, None) self._application.onPageDialogPageFactoriesNeeded(None, eventParams) for factory in eventParams.pageFactories: label, colorPicker = self._createLabelAndColorPicker( factory.title, mainSizer ) self._colorPickers[factory.getTypeString()] = colorPicker self.SetSizer(mainSizer) def LoadState(self): self._colorsList.load() for pageType in self._colorsList.getPageTypes(): if pageType in self._colorPickers: color = self._colorsList.getColor(pageType) self._colorPickers[pageType].SetColour(color) def Save(self): self._colorsList.load() for pageType in self._colorsList.getPageTypes(): if pageType in self._colorPickers: color = self._colorPickers[pageType].GetColour().GetAsString(wx.C2S_HTML_SYNTAX) self._colorsList.setColor(pageType, color)
This articulated program aims to provide writers with the opportunity of enhancing their creative and practical skills in a framework of high quality academic study. The rapid pace of change in the ways in which information is accessed, utilised and converted into knowledge means that there is a growing need for graduates with both traditional and electronic professional and creative writing skills. The constant need for content in print, digital, film, and broadcast media means that writers are in greater demand than ever before. The Master of Writing allows students to acquire the skills needed to improve their creative and professional writing. Creative writing is a form of artistic expression through written language. It is a way for the writer to express their feelings, thoughts and ideas in a way that resonates with them and others. Postgraduate study in this field is a way for students to sharpen their skills not only as writers, but as editors, publishers and connoisseurs of literature. People have been expressing themselves through language since the earliest days of humankind. The invention of the written word in 3200 BCE began a tradition of transcribing tales and sagas orally passed down through generations. The great works of Homer, the Indian Vedas, Sanskrit poems and Mayan codices have paved the way toward a future in which literature still thrives. Postgraduate students of creative writing therefore uphold an ancient tradition of storytelling. In striving to master their craft, they pay homage to the great writers that came before and inspire those to come. Is creative writing for me? Creative writing is for anyone with a passion for storytelling. It requires a great deal of patience, persistence, humility and dedication to become proficient. Those that are passionate about developing their skills however are rewarded with work befitting their toil. If this sounds like you, then creative writing could very well be a great fit. Graduate certificates, diplomas and master degrees are available in creative writing. Each are designed for people with various levels of commitment and career progression. Certificate level courses provide students with immersion in the literary world through close ties to local writers, festivals, performances and readings. Courses like those offered by the University of Sydney provide students with the opportunity to improve their editing and structuring ability over the course of six months in conjunction with these relationships. Prospective students must achieve a high result in an English language proficiency test to enter, in addition to either professional experience in a relevant field or a bachelor degree from any field. Diploma level graduate courses grant students the opportunity to develop a broad array of literary skills through workshops. Macquarie University’s Graduate Diploma of Creative Writing is a great example of this, providing students with the opportunity to take units from master level programs that appeal to their specific interests and apply them to their diploma. These courses take a year of full time study to complete or two years full time, with similar entry requirements to certificate level courses. The Master of Creative Writing is a two year degree aimed at professionals already in the editing, publishing or creative writing industry. Those offered by the University of Melbourne are an example, providing students with the opportunity to publish in university journals and build relationships with published writers. A prior bachelor degree in any field is necessary for entry, with at least a 70% GPA in this particular case. Creative writing graduates are well-suited to becoming editors for companies like Hyland and Byrne and Lexington Writing Firm. This sort of career is perfectly suited, as it provides writers with the chance to exercise their literary and structural knowledge in the pursuit of improving others’ work. The world of advertising is in constant need of catchy slogans, creative campaigns and new ideas to entice consumers. Creative writing graduates are poised to do this well, finding themselves at companies like Showpony Advertising and McCann where they can utilise all they learned about proper phrasing, editing and grabbing a reader’s attention. Fluency in writing is essential to any news story, which is something creative writing graduates bring to the table. Creativity combined with proficiency in optimal phrasing go a long way for companies like Reuters, Informa and UBM. There is much to be learned on the job in the way of investigation, interviewing and acquiring stories, but a creative writing qualification puts students in good stead to get their foot in the door.
from __future__ import print_function, division from cols import * def cliffsDelta(lst1,lst2, dull = [0.147, # small 0.33, # medium 0.474 # large ][0] ): "Returns true if there are more than 'dull' differences" m, n = len(lst1), len(lst2) lst2 = sorted(lst2) j = more = less = 0 for repeats,x in runs(sorted(lst1)): while j <= (n - 1) and lst2[j] < x: j += 1 more += j*repeats while j <= (n - 1) and lst2[j] == x: j += 1 less += (n - j)*repeats d= (more - less) / (m*n) return abs(d) > dull def runs(lst): "Iterator, chunks repeated values" for j,two in enumerate(lst): if j == 0: one,i = two,0 if one!=two: yield j - i,one i = j one=two yield j - i + 1,two def fromFile(f=None): "utility for reading sample data from disk" source=open(f) if f else sys.stdin def labels(str): if str: words = re.split(dash,str) for n in range(len(words)): m = n + 1 yield ','.join(words[:m]) import re cache = {} num, space,dash = r'^\+?-?[0-9]', 'r[ \t\r\n]',r'[ \t]*-[ \t]*' now=None for line in source: line = line.strip() if line: for word in re.split(space,line): if re.match(num,word[0]): if now: for label in labels(now): cache[label] += float(word) else: for label in labels(word): if not label in cache: cache[label] = Nums() now = word print(cache.keys()) for k,v in cache.items(): print(k,v.n) return cache fromFile()
Jurek Czyzowicz, Konstantinos Georgiou, Ryan Killick, Evangelos Kranakis, Danny Krizanc, Lata Narayanan et al. This book constitutes the refereed post-conference proceedings of the 25th International Colloquium on Structural Information and Communication Complexity, SIROCCO 2018, held in Ma'ale HaHamisha, Israel, in June 2018. The 23 full papers and 8 short papers presented were carefully reviewed and selected from 47 submissions. They are devoted to the study of the interplay between structural knowledge, communications, and computing in decentralized systems of multiple communicating entities and cover a large range of topics.
# Copyright 2011 Nicira Networks, Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import netaddr from nova import ipv6 from nova.objects import fixed_ip as fixed_ip_obj from nova.objects import floating_ip as floating_ip_obj from nova.objects import network as network_obj from nova.objects import virtual_interface as vif_obj def get_ipam_lib(net_man): return NeutronNovaIPAMLib(net_man) class NeutronNovaIPAMLib(object): """Implements Neutron IP Address Management (IPAM) interface using the local Nova database. This implementation is inline with how IPAM is used by other NetworkManagers. """ def __init__(self, net_manager): """Holds a reference to the "parent" network manager, used to take advantage of various FlatManager methods to avoid code duplication. """ self.net_manager = net_manager def get_subnets_by_net_id(self, context, tenant_id, net_id, _vif_id=None): """Returns information about the IPv4 and IPv6 subnets associated with a Neutron Network UUID. """ n = network_obj.Network.get_by_uuid(context.elevated(), net_id) subnet_v4 = { 'network_id': n.uuid, 'cidr': n.cidr, 'gateway': n.gateway, 'broadcast': n.broadcast, 'netmask': n.netmask, 'version': 4, 'dns1': n.dns1, 'dns2': n.dns2} #TODO(tr3buchet): I'm noticing we've assumed here that all dns is v4. # this is probably bad as there is no way to add v6 # dns to nova subnet_v6 = { 'network_id': n.uuid, 'cidr': n.cidr_v6, 'gateway': n.gateway_v6, 'broadcast': None, 'netmask': n.netmask_v6, 'version': 6, 'dns1': None, 'dns2': None} def ips_to_strs(net): for key, value in net.items(): if isinstance(value, netaddr.ip.BaseIP): net[key] = str(value) return net return [ips_to_strs(subnet_v4), ips_to_strs(subnet_v6)] def get_routes_by_ip_block(self, context, block_id, project_id): """Returns the list of routes for the IP block.""" return [] def get_v4_ips_by_interface(self, context, net_id, vif_id, project_id): """Returns a list of IPv4 address strings associated with the specified virtual interface, based on the fixed_ips table. """ # TODO(tr3buchet): link fixed_ips to vif by uuid so only 1 db call vif_rec = vif_obj.VirtualInterface.get_by_uuid(context, vif_id) if not vif_rec: return [] fixed_ips = fixed_ip_obj.FixedIPList.get_by_virtual_interface_id( context, vif_rec.id) return [str(fixed_ip.address) for fixed_ip in fixed_ips] def get_v6_ips_by_interface(self, context, net_id, vif_id, project_id): """Returns a list containing a single IPv6 address strings associated with the specified virtual interface. """ admin_context = context.elevated() network = network_obj.Network.get_by_uuid(admin_context, net_id) vif_rec = vif_obj.VirtualInterface.get_by_uuid(context, vif_id) if network.cidr_v6 and vif_rec and vif_rec.address: ip = ipv6.to_global(network.cidr_v6, vif_rec.address, project_id) return [ip] return [] def get_floating_ips_by_fixed_address(self, context, fixed_address): return floating_ip_obj.FloatingIPList.get_by_fixed_address( context, fixed_address)
MCM London Comic Con – MCM London Comic Con is all set to give a right royal welcome to The Walking Dead’s King Ezekiel – aka screen actor and noted voice talent Khary Payton – and Cooper Andrews, who plays Ezekiel’s right hand man Jerry in the hit zombie apocalypse series. Payton’s character Ezekiel is the self-proclaimed monarch of a community known as The Kingdom. Usually a seemingly-benevolent settlement in The Walking Dead puts us on the alert for sinister secrets. With Ezekiel, the show pulls the reverse trick – it turns out that rather than being a tyrant, the tiger-owning king is a genuinely good guy! A kindhearted, noble leader who just wants to protect his people, King Ezekiel is faking an over-the-top regal persona so that his ‘subjects’ have a figurehead to follow. When he’s not ruling his zombie-infested kingdom, Khary Payton is best known for his voice acting work – in particular, for playing superhero Cyborg on Teen Titans, Teen Titans Go!, Justice League Action and other animated series. His extensive video game credits include the Batman: Arkham, Dead or Alive and Infamous franchises. Also known for his work behind the camera, Cooper Andrews joined the cast of The Walking Dead fresh from a recurring role as Yo-Yo Engberk on acclaimed Silicon Valley drama Halt and Catch Fire. Long Island-born Andrews plays Ezekiel’s loyal personal steward and bodyguard Jerry – a lovable, friendly guy with a penchant for puns who also happens to be a dab hand with a double-bladed battle axe …as people who attempt to harm his king discover to their cost!
# -*- coding: utf8 -*- u""" Mathics: a general-purpose computer algebra system Copyright (C) 2011-2013 The Mathics Team This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import cPickle as pickle import os import base64 def get_file_time(file): try: return os.stat(file).st_mtime except OSError: return 0 def valuesname(name): " 'NValues' -> 'n' " if name == 'Messages': return 'messages' else: return name[:-6].lower() class Definitions(object): def __init__(self, add_builtin=False, builtin_filename=None): super(Definitions, self).__init__() self.builtin = {} self.user = {} self.autoload_stage = False if add_builtin: from mathics.builtin import modules, contribute from mathics.core.evaluation import Evaluation from mathics.settings import ROOT_DIR loaded = False if builtin_filename is not None: builtin_dates = [get_file_time(module.__file__) for module in modules] builtin_time = max(builtin_dates) if get_file_time(builtin_filename) > builtin_time: builtin_file = open(builtin_filename, 'r') self.builtin = pickle.load(builtin_file) loaded = True if not loaded: contribute(self) if builtin_filename is not None: builtin_file = open(builtin_filename, 'w') pickle.dump(self.builtin, builtin_file, -1) self.autoload_stage = True for root, dirs, files in os.walk( # noqa os.path.join(ROOT_DIR, 'autoload')): for f in filter(lambda x: x.endswith('.m'), files): with open(os.path.join(root, f)) as stream: Evaluation(stream.read(), self, timeout=30) self.autoload_stage = False def get_builtin_names(self): return set(self.builtin) def get_user_names(self): return set(self.user) def get_names(self): return self.get_builtin_names() | self.get_user_names() def get_definition(self, name): user = self.user.get(name, None) builtin = self.builtin.get(name, None) if builtin: context = 'System`' else: context = 'Global`' if user is None and builtin is None: return Definition(name=name, context=context) if builtin is None: user.context = context return user if user is None: builtin.context = context return builtin if user: attributes = user.attributes elif builtin: attributes = builtin.attributes else: attributes = set() if not user: user = Definition(name=name) if not builtin: builtin = Definition(name=name) options = builtin.options.copy() options.update(user.options) formatvalues = builtin.formatvalues.copy() for form, rules in user.formatvalues.iteritems(): if form in formatvalues: formatvalues[form].extend(rules) else: formatvalues[form] = rules return Definition(name=name, ownvalues=user.ownvalues + builtin.ownvalues, downvalues=user.downvalues + builtin.downvalues, subvalues=user.subvalues + builtin.subvalues, upvalues=user.upvalues + builtin.upvalues, formatvalues=formatvalues, messages=user.messages + builtin.messages, attributes=attributes, options=options, nvalues=user.nvalues + builtin.nvalues, defaultvalues=user.defaultvalues + builtin.defaultvalues, context=context, ) def get_attributes(self, name): return self.get_definition(name).attributes def get_ownvalues(self, name): return self.get_definition(name).ownvalues def get_downvalues(self, name): return self.get_definition(name).downvalues def get_subvalues(self, name): return self.get_definition(name).subvalues def get_upvalues(self, name): return self.get_definition(name).upvalues def get_formats(self, name, format=''): formats = self.get_definition(name).formatvalues result = formats.get(format, []) + formats.get('', []) result.sort() return result def get_nvalues(self, name): return self.get_definition(name).nvalues def get_defaultvalues(self, name): return self.get_definition(name).defaultvalues def get_value(self, name, pos, pattern, evaluation): rules = self.get_definition(name).get_values_list(valuesname(pos)) for rule in rules: result = rule.apply(pattern, evaluation) if result is not None: return result def get_user_definition(self, name, create=True): if self.autoload_stage: existing = self.builtin.get(name) if existing is None: if not create: return None self.builtin[name] = Definition(name=name, attributes=set()) return self.builtin[name] existing = self.user.get(name) if existing: return existing else: if not create: return None builtin = self.builtin.get(name) if builtin: attributes = builtin.attributes else: attributes = set() self.user[name] = Definition(name=name, attributes=attributes) return self.user[name] def reset_user_definition(self, name): del self.user[name] def add_user_definition(self, name, definition): self.user[name] = definition def set_attribute(self, name, attribute): definition = self.get_user_definition(name) definition.attributes.add(attribute) def set_attributes(self, name, attributes): definition = self.get_user_definition(name) definition.attributes = set(attributes) def clear_attribute(self, name, attribute): definition = self.get_user_definition(name) if attribute in definition.attributes: definition.attributes.remove(attribute) def add_rule(self, name, rule, position=None): if position is None: return self.get_user_definition(name).add_rule(rule) else: return self.get_user_definition(name).add_rule_at(rule, position) def add_format(self, name, rule, form=''): definition = self.get_user_definition(name) if isinstance(form, tuple) or isinstance(form, list): forms = form else: forms = [form] for form in forms: if form not in definition.formatvalues: definition.formatvalues[form] = [] insert_rule(definition.formatvalues[form], rule) def add_nvalue(self, name, rule): definition = self.get_user_definition(name) definition.add_rule_at(rule, 'n') def add_default(self, name, rule): definition = self.get_user_definition(name) definition.add_rule_at(rule, 'default') def add_message(self, name, rule): definition = self.get_user_definition(name) definition.add_rule_at(rule, 'messages') def set_values(self, name, values, rules): pos = valuesname(values) definition = self.get_user_definition(name) definition.set_values_list(pos, rules) def get_options(self, name): return self.get_definition(name).options def reset_user_definitions(self): self.user = {} def get_user_definitions(self): return base64.b64encode(pickle.dumps(self.user, protocol=pickle.HIGHEST_PROTOCOL)) def set_user_definitions(self, definitions): if definitions: self.user = pickle.loads(base64.b64decode(definitions)) else: self.user = {} def get_ownvalue(self, name): ownvalues = self.get_definition(name).ownvalues if ownvalues: return ownvalues[0] return None def set_ownvalue(self, name, value): from expression import Symbol from rules import Rule self.add_rule(name, Rule(Symbol(name), value)) def set_options(self, name, options): definition = self.get_user_definition(name) definition.options = options def unset(self, name, expr): definition = self.get_user_definition(name) return definition.remove_rule(expr) def get_tag_position(pattern, name): if pattern.get_name() == name: return 'own' elif pattern.is_atom(): return None else: head_name = pattern.get_head_name() if head_name == name: return 'down' elif head_name == 'Condition' and len(pattern.leaves) > 0: return get_tag_position(pattern.leaves[0], name) elif pattern.get_lookup_name() == name: return 'sub' else: for leaf in pattern.leaves: if leaf.get_lookup_name() == name: return 'up' return None def insert_rule(values, rule): for index, existing in enumerate(values): if existing.pattern.same(rule.pattern): del values[index] break values.insert(0, rule) values.sort() class Definition(object): def __init__(self, name, rules=None, ownvalues=None, downvalues=None, subvalues=None, upvalues=None, formatvalues=None, messages=None, attributes=(), options=None, nvalues=None, defaultvalues=None, builtin=None, context='Global`'): super(Definition, self).__init__() self.name = name if rules is None: rules = [] if ownvalues is None: ownvalues = [] if downvalues is None: downvalues = [] if subvalues is None: subvalues = [] if upvalues is None: upvalues = [] if formatvalues is None: formatvalues = {} if options is None: options = {} if nvalues is None: nvalues = [] if defaultvalues is None: defaultvalues = [] if messages is None: messages = [] self.ownvalues = ownvalues self.downvalues = downvalues self.subvalues = subvalues self.upvalues = upvalues for rule in rules: self.add_rule(rule) self.formatvalues = dict((name, list) for name, list in formatvalues.items()) self.messages = messages self.attributes = set(attributes) self.options = options self.nvalues = nvalues self.defaultvalues = defaultvalues self.builtin = builtin self.context = context def get_values_list(self, pos): if pos == 'messages': return self.messages else: return getattr(self, '%svalues' % pos) def set_values_list(self, pos, rules): if pos == 'messages': self.messages = rules else: setattr(self, '%svalues' % pos, rules) def add_rule_at(self, rule, position): values = self.get_values_list(position) insert_rule(values, rule) return True def add_rule(self, rule): pos = get_tag_position(rule.pattern, self.name) if pos: return self.add_rule_at(rule, pos) return False def remove_rule(self, lhs): position = get_tag_position(lhs, self.name) if position: values = self.get_values_list(position) for index, existing in enumerate(values): if existing.pattern.expr.same(lhs): del values[index] return True return False def __repr__(self): return ( '<Definition: name: %s, ' 'downvalues: %s, formats: %s, attributes: %s>') % ( self.name, self.downvalues, self.formatvalues, self.attributes)
November 22, 2017 — DENSO Robotics announced publication of a product catalog featuring the company’s wide range of compact, high-speed industrial robots, which have reaches of 350 to 1,300 mm, payload capacities as high as 20 kg and repeatability to within ±0.015 mm. The 52-page publication, which is offered in an interactive online version or as a download, features detailed descriptions, specifications and schematics of DENSO’s entire lineup of four-axis SCARA and five- and six-axis articulated robots, robot controllers and programming software. A historical timeline in the catalog highlights milestones in the company’s 50 years of robot innovation, including its latest HSR four-axis SCARA robot. The HSR’s vibration control, lightweight arm and heat dissipation make it more efficient than previous models, allowing it to accelerate faster and stop more precisely, as well as run continuously at its highest rated speed. DENSO is a manufacturer — and user — of small assembly robots, employing over 18,000 of its robots in its own facilities. Over 77,000 additional DENSO robots are used by other companies worldwide.
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A library for cross-platform browser tests.""" import os import sys try: # This enables much better stack upon native code crashes. import faulthandler faulthandler.enable() except ImportError: pass # Ensure Python >= 2.7. if sys.version_info < (2, 7): print >> sys.stderr, 'Need Python 2.7 or greater.' sys.exit(-1) def _JoinPath(*path_parts): return os.path.abspath(os.path.join(*path_parts)) def _InsertPath(path): assert os.path.isdir(path), 'Not a valid path: %s' % path if path not in sys.path: # Some call sites that use Telemetry assume that sys.path[0] is the # directory containing the script, so we add these extra paths to right # after sys.path[0]. sys.path.insert(1, path) def _AddDirToPythonPath(*path_parts): path = _JoinPath(*path_parts) _InsertPath(path) # Add Catapult dependencies to our path. # util depends on py_utils, so we can't use it to get the catapult dir. _CATAPULT_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', '..') _AddDirToPythonPath(_CATAPULT_DIR, 'common', 'py_utils') _AddDirToPythonPath(_CATAPULT_DIR, 'dependency_manager') _AddDirToPythonPath(_CATAPULT_DIR, 'devil') _AddDirToPythonPath(_CATAPULT_DIR, 'systrace') _AddDirToPythonPath(_CATAPULT_DIR, 'tracing') _AddDirToPythonPath(_CATAPULT_DIR, 'common', 'py_trace_event') _AddDirToPythonPath(_CATAPULT_DIR, 'common', 'py_vulcanize') _AddDirToPythonPath(_CATAPULT_DIR, 'tracing', 'tracing_build') # pylint: disable=wrong-import-position from telemetry.core import util from telemetry.internal.util import global_hooks # pylint: enable=wrong-import-position # Add Catapult third party dependencies into our path. _AddDirToPythonPath(util.GetCatapultThirdPartyDir(), 'typ') # Required by websocket-client. _AddDirToPythonPath(util.GetCatapultThirdPartyDir(), 'six') # Add Telemetry third party dependencies into our path. _TELEMETRY_3P = util.GetTelemetryThirdPartyDir() _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'altgraph') _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'mock') _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'modulegraph') _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'mox3') _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'png') _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'pyfakefs') _AddDirToPythonPath(util.GetTelemetryThirdPartyDir(), 'websocket-client') # Install Telemtry global hooks. global_hooks.InstallHooks()
Open your Facebook page and click the upside-down triangle in the upper right hand corner. Select “Settings” and then in the left-hand column select “Ads”. You’ll see the new “Ads based on the use of my website and apps” setting. Click the “Edit” link, and then click the “Choose Setting” button and select “Off”.
""" This file contains celery tasks for contentstore views """ import base64 import json import os import pkg_resources import shutil import tarfile from datetime import datetime from tempfile import NamedTemporaryFile, mkdtemp import olxcleaner from ccx_keys.locator import CCXLocator from celery import shared_task from celery.utils.log import get_task_logger from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.core.exceptions import SuspiciousOperation from django.core.files import File from django.test import RequestFactory from django.utils.text import get_valid_filename from django.utils.translation import ugettext as _ from edx_django_utils.monitoring import ( set_code_owner_attribute, set_code_owner_attribute_from_module, set_custom_attribute, set_custom_attributes_for_course_key ) from olxcleaner.exceptions import ErrorLevel from olxcleaner.reporting import report_error_summary, report_errors from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import LibraryLocator from organizations.api import add_organization_course, ensure_organization from organizations.models import OrganizationCourse from path import Path as path from pytz import UTC from user_tasks.models import UserTaskArtifact, UserTaskStatus from user_tasks.tasks import UserTask from cms.djangoapps.contentstore.courseware_index import ( CoursewareSearchIndexer, LibrarySearchIndexer, SearchIndexingError ) from cms.djangoapps.contentstore.storage import course_import_export_storage from cms.djangoapps.contentstore.utils import initialize_permissions, reverse_usage_url, translation_language from cms.djangoapps.models.settings.course_metadata import CourseMetadata from common.djangoapps.course_action_state.models import CourseRerunState from common.djangoapps.student.auth import has_course_author_access from common.djangoapps.util.monitoring import monitor_import_failure from openedx.core.djangoapps.content.learning_sequences.api import key_supports_outlines from openedx.core.djangoapps.embargo.models import CountryAccessRule, RestrictedCourse from openedx.core.lib.extract_tar import safetar_extractall from xmodule.contentstore.django import contentstore from xmodule.course_module import CourseFields from xmodule.exceptions import SerializationError from xmodule.modulestore import COURSE_ROOT, LIBRARY_ROOT from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import DuplicateCourseError, ItemNotFoundError, InvalidProctoringProvider from xmodule.modulestore.xml_exporter import export_course_to_xml, export_library_to_xml from xmodule.modulestore.xml_importer import import_course_from_xml, import_library_from_xml from .outlines import update_outline_from_modulestore from .toggles import course_import_olx_validation_is_enabled User = get_user_model() LOGGER = get_task_logger(__name__) FILE_READ_CHUNK = 1024 # bytes FULL_COURSE_REINDEX_THRESHOLD = 1 ALL_ALLOWED_XBLOCKS = frozenset( [entry_point.name for entry_point in pkg_resources.iter_entry_points("xblock.v1")] ) def clone_instance(instance, field_values): """ Clones a Django model instance. The specified fields are replaced with new values. Arguments: instance (Model): Instance of a Django model. field_values (dict): Map of field names to new values. Returns: Model: New instance. """ instance.pk = None for field, value in field_values.items(): setattr(instance, field, value) instance.save() return instance @shared_task @set_code_owner_attribute def rerun_course(source_course_key_string, destination_course_key_string, user_id, fields=None): """ Reruns a course in a new celery task. """ # import here, at top level this import prevents the celery workers from starting up correctly from edxval.api import copy_course_videos source_course_key = CourseKey.from_string(source_course_key_string) destination_course_key = CourseKey.from_string(destination_course_key_string) try: # deserialize the payload fields = deserialize_fields(fields) if fields else None # use the split modulestore as the store for the rerun course, # as the Mongo modulestore doesn't support multiple runs of the same course. store = modulestore() with store.default_store('split'): store.clone_course(source_course_key, destination_course_key, user_id, fields=fields) # set initial permissions for the user to access the course. initialize_permissions(destination_course_key, User.objects.get(id=user_id)) # update state: Succeeded CourseRerunState.objects.succeeded(course_key=destination_course_key) # call edxval to attach videos to the rerun copy_course_videos(source_course_key, destination_course_key) # Copy OrganizationCourse organization_course = OrganizationCourse.objects.filter(course_id=source_course_key_string).first() if organization_course: clone_instance(organization_course, {'course_id': destination_course_key_string}) # Copy RestrictedCourse restricted_course = RestrictedCourse.objects.filter(course_key=source_course_key).first() if restricted_course: country_access_rules = CountryAccessRule.objects.filter(restricted_course=restricted_course) new_restricted_course = clone_instance(restricted_course, {'course_key': destination_course_key}) for country_access_rule in country_access_rules: clone_instance(country_access_rule, {'restricted_course': new_restricted_course}) org_data = ensure_organization(source_course_key.org) add_organization_course(org_data, destination_course_key) return "succeeded" except DuplicateCourseError: # do NOT delete the original course, only update the status CourseRerunState.objects.failed(course_key=destination_course_key) LOGGER.exception('Course Rerun Error') return "duplicate course" # catch all exceptions so we can update the state and properly cleanup the course. except Exception as exc: # pylint: disable=broad-except # update state: Failed CourseRerunState.objects.failed(course_key=destination_course_key) LOGGER.exception('Course Rerun Error') try: # cleanup any remnants of the course modulestore().delete_course(destination_course_key, user_id) except ItemNotFoundError: # it's possible there was an error even before the course module was created pass return "exception: " + str(exc) def deserialize_fields(json_fields): fields = json.loads(json_fields) for field_name, value in fields.items(): fields[field_name] = getattr(CourseFields, field_name).from_json(value) return fields def _parse_time(time_isoformat): """ Parses time from iso format """ return datetime.strptime( # remove the +00:00 from the end of the formats generated within the system time_isoformat.split('+')[0], "%Y-%m-%dT%H:%M:%S.%f" ).replace(tzinfo=UTC) @shared_task @set_code_owner_attribute def update_search_index(course_id, triggered_time_isoformat): """ Updates course search index. """ try: course_key = CourseKey.from_string(course_id) # We skip search indexing for CCX courses because there is currently # some issue around Modulestore caching that makes it prohibitively # expensive (sometimes hours-long for really complex courses). if isinstance(course_key, CCXLocator): LOGGER.warning( 'Search indexing skipped for CCX Course %s (this is currently too slow to run in production)', course_id ) return CoursewareSearchIndexer.index(modulestore(), course_key, triggered_at=(_parse_time(triggered_time_isoformat))) except SearchIndexingError as exc: error_list = exc.error_list LOGGER.error( "Search indexing error for complete course %s - %s - %s", course_id, str(exc), error_list, ) else: LOGGER.debug('Search indexing successful for complete course %s', course_id) @shared_task @set_code_owner_attribute def update_library_index(library_id, triggered_time_isoformat): """ Updates course search index. """ try: library_key = CourseKey.from_string(library_id) LibrarySearchIndexer.index(modulestore(), library_key, triggered_at=(_parse_time(triggered_time_isoformat))) except SearchIndexingError as exc: LOGGER.error('Search indexing error for library %s - %s', library_id, str(exc)) else: LOGGER.debug('Search indexing successful for library %s', library_id) class CourseExportTask(UserTask): # pylint: disable=abstract-method """ Base class for course and library export tasks. """ @staticmethod def calculate_total_steps(arguments_dict): """ Get the number of in-progress steps in the export process, as shown in the UI. For reference, these are: 1. Exporting 2. Compressing """ return 2 @classmethod def generate_name(cls, arguments_dict): """ Create a name for this particular import task instance. Arguments: arguments_dict (dict): The arguments given to the task function Returns: text_type: The generated name """ key = arguments_dict['course_key_string'] return f'Export of {key}' @shared_task(base=CourseExportTask, bind=True) # Note: The decorator @set_code_owner_attribute could not be used because # the implementation of this task breaks with any additional decorators. def export_olx(self, user_id, course_key_string, language): """ Export a course or library to an OLX .tar.gz archive and prepare it for download. """ set_code_owner_attribute_from_module(__name__) courselike_key = CourseKey.from_string(course_key_string) try: user = User.objects.get(pk=user_id) except User.DoesNotExist: with translation_language(language): self.status.fail(_('Unknown User ID: {0}').format(user_id)) return if not has_course_author_access(user, courselike_key): with translation_language(language): self.status.fail(_('Permission denied')) return if isinstance(courselike_key, LibraryLocator): courselike_module = modulestore().get_library(courselike_key) else: courselike_module = modulestore().get_course(courselike_key) try: self.status.set_state('Exporting') tarball = create_export_tarball(courselike_module, courselike_key, {}, self.status) artifact = UserTaskArtifact(status=self.status, name='Output') artifact.file.save(name=os.path.basename(tarball.name), content=File(tarball)) artifact.save() # catch all exceptions so we can record useful error messages except Exception as exception: # pylint: disable=broad-except LOGGER.exception('Error exporting course %s', courselike_key, exc_info=True) if self.status.state != UserTaskStatus.FAILED: self.status.fail({'raw_error_msg': str(exception)}) return def create_export_tarball(course_module, course_key, context, status=None): """ Generates the export tarball, or returns None if there was an error. Updates the context with any error information if applicable. """ name = course_module.url_name export_file = NamedTemporaryFile(prefix=name + '.', suffix=".tar.gz") root_dir = path(mkdtemp()) try: if isinstance(course_key, LibraryLocator): export_library_to_xml(modulestore(), contentstore(), course_key, root_dir, name) else: export_course_to_xml(modulestore(), contentstore(), course_module.id, root_dir, name) if status: status.set_state('Compressing') status.increment_completed_steps() LOGGER.debug('tar file being generated at %s', export_file.name) with tarfile.open(name=export_file.name, mode='w:gz') as tar_file: tar_file.add(root_dir / name, arcname=name) except SerializationError as exc: LOGGER.exception('There was an error exporting %s', course_key, exc_info=True) parent = None try: failed_item = modulestore().get_item(exc.location) parent_loc = modulestore().get_parent_location(failed_item.location) if parent_loc is not None: parent = modulestore().get_item(parent_loc) except: # pylint: disable=bare-except # if we have a nested exception, then we'll show the more generic error message pass context.update({ 'in_err': True, 'raw_err_msg': str(exc), 'edit_unit_url': reverse_usage_url("container_handler", parent.location) if parent else "", }) if status: status.fail(json.dumps({'raw_error_msg': context['raw_err_msg'], 'edit_unit_url': context['edit_unit_url']})) raise except Exception as exc: LOGGER.exception('There was an error exporting %s', course_key, exc_info=True) context.update({ 'in_err': True, 'edit_unit_url': None, 'raw_err_msg': str(exc)}) if status: status.fail(json.dumps({'raw_error_msg': context['raw_err_msg']})) raise finally: if os.path.exists(root_dir / name): shutil.rmtree(root_dir / name) return export_file class CourseImportTask(UserTask): # pylint: disable=abstract-method """ Base class for course and library import tasks. """ @staticmethod def calculate_total_steps(arguments_dict): """ Get the number of in-progress steps in the import process, as shown in the UI. For reference, these are: 1. Unpacking 2. Verifying 3. Updating """ return 3 @classmethod def generate_name(cls, arguments_dict): """ Create a name for this particular import task instance. Arguments: arguments_dict (dict): The arguments given to the task function Returns: text_type: The generated name """ key = arguments_dict['course_key_string'] filename = arguments_dict['archive_name'] return f'Import of {key} from {filename}' @shared_task(base=CourseImportTask, bind=True) # Note: The decorator @set_code_owner_attribute could not be used because # lint-amnesty, pylint: disable=too-many-statements # the implementation of this task breaks with any additional decorators. def import_olx(self, user_id, course_key_string, archive_path, archive_name, language): """ Import a course or library from a provided OLX .tar.gz archive. """ current_step = 'Unpacking' courselike_key = CourseKey.from_string(course_key_string) set_code_owner_attribute_from_module(__name__) set_custom_attributes_for_course_key(courselike_key) log_prefix = f'Course import {courselike_key}' self.status.set_state(current_step) data_root = path(settings.GITHUB_REPO_ROOT) subdir = base64.urlsafe_b64encode(repr(courselike_key).encode('utf-8')).decode('utf-8') course_dir = data_root / subdir def validate_user(): """Validate if the user exists otherwise log error. """ try: return User.objects.get(pk=user_id) except User.DoesNotExist as exc: with translation_language(language): self.status.fail(_('User permission denied.')) LOGGER.error(f'{log_prefix}: Unknown User: {user_id}') monitor_import_failure(courselike_key, current_step, exception=exc) return def user_has_access(user): """Return True if user has studio write access to the given course.""" has_access = has_course_author_access(user, courselike_key) if not has_access: message = f'User permission denied: {user.username}' with translation_language(language): self.status.fail(_('Permission denied. You do not have write access to this course.')) LOGGER.error(f'{log_prefix}: {message}') monitor_import_failure(courselike_key, current_step, message=message) return has_access def file_is_supported(): """Check if it is a supported file.""" file_is_valid = archive_name.endswith('.tar.gz') if not file_is_valid: message = f'Unsupported file {archive_name}' with translation_language(language): self.status.fail(_('We only support uploading a .tar.gz file.')) LOGGER.error(f'{log_prefix}: {message}') monitor_import_failure(courselike_key, current_step, message=message) return file_is_valid def file_exists_in_storage(): """Verify archive path exists in storage.""" archive_path_exists = course_import_export_storage.exists(archive_path) if not archive_path_exists: message = f'Uploaded file {archive_path} not found' with translation_language(language): self.status.fail(_('Uploaded Tar file not found. Try again.')) LOGGER.error(f'{log_prefix}: {message}') monitor_import_failure(courselike_key, current_step, message=message) return archive_path_exists def verify_root_name_exists(course_dir, root_name): """Verify root xml file exists.""" def get_all_files(directory): """ For each file in the directory, yield a 2-tuple of (file-name, directory-path) """ for directory_path, _dirnames, filenames in os.walk(directory): for filename in filenames: yield (filename, directory_path) def get_dir_for_filename(directory, filename): """ Returns the directory path for the first file found in the directory with the given name. If there is no file in the directory with the specified name, return None. """ for name, directory_path in get_all_files(directory): if name == filename: return directory_path return None dirpath = get_dir_for_filename(course_dir, root_name) if not dirpath: message = f'Could not find the {root_name} file in the package.' with translation_language(language): self.status.fail(_('Could not find the {0} file in the package.').format(root_name)) LOGGER.error(f'{log_prefix}: {message}') monitor_import_failure(courselike_key, current_step, message=message) return return dirpath user = validate_user() if not user: return if not user_has_access(user): return if not file_is_supported(): return is_library = isinstance(courselike_key, LibraryLocator) is_course = not is_library if is_library: root_name = LIBRARY_ROOT courselike_module = modulestore().get_library(courselike_key) import_func = import_library_from_xml else: root_name = COURSE_ROOT courselike_module = modulestore().get_course(courselike_key) import_func = import_course_from_xml # Locate the uploaded OLX archive (and download it from S3 if necessary) # Do everything in a try-except block to make sure everything is properly cleaned up. try: LOGGER.info(f'{log_prefix}: unpacking step started') temp_filepath = course_dir / get_valid_filename(archive_name) if not course_dir.isdir(): os.mkdir(course_dir) LOGGER.info(f'{log_prefix}: importing course to {temp_filepath}') # Copy the OLX archive from where it was uploaded to (S3, Swift, file system, etc.) if not file_exists_in_storage(): return with course_import_export_storage.open(archive_path, 'rb') as source: with open(temp_filepath, 'wb') as destination: def read_chunk(): """ Read and return a sequence of bytes from the source file. """ return source.read(FILE_READ_CHUNK) for chunk in iter(read_chunk, b''): destination.write(chunk) LOGGER.info(f'{log_prefix}: Download from storage complete') # Delete from source location course_import_export_storage.delete(archive_path) # If the course has an entrance exam then remove it and its corresponding milestone. # current course state before import. if is_course: if courselike_module.entrance_exam_enabled: fake_request = RequestFactory().get('/') fake_request.user = user from .views.entrance_exam import remove_entrance_exam_milestone_reference # TODO: Is this really ok? Seems dangerous for a live course remove_entrance_exam_milestone_reference(fake_request, courselike_key) LOGGER.info(f'{log_prefix}: entrance exam milestone content reference has been removed') # Send errors to client with stage at which error occurred. except Exception as exception: # pylint: disable=broad-except if course_dir.isdir(): shutil.rmtree(course_dir) LOGGER.info(f'{log_prefix}: Temp data cleared') self.status.fail(_('An Unknown error occurred during the unpacking step.')) LOGGER.exception(f'{log_prefix}: Unknown error while unpacking', exc_info=True) monitor_import_failure(courselike_key, current_step, exception=exception) return # try-finally block for proper clean up after receiving file. try: tar_file = tarfile.open(temp_filepath) try: safetar_extractall(tar_file, (course_dir + '/')) except SuspiciousOperation as exc: with translation_language(language): self.status.fail(_('Unsafe tar file. Aborting import.')) LOGGER.error(f'{log_prefix}: Unsafe tar file') monitor_import_failure(courselike_key, current_step, exception=exc) return finally: tar_file.close() current_step = 'Verifying' self.status.set_state(current_step) self.status.increment_completed_steps() LOGGER.info(f'{log_prefix}: Uploaded file extracted. Verification step started') dirpath = verify_root_name_exists(course_dir, root_name) if not dirpath: return if not validate_course_olx(courselike_key, dirpath, self.status): return dirpath = os.path.relpath(dirpath, data_root) current_step = 'Updating' self.status.set_state(current_step) self.status.increment_completed_steps() LOGGER.info(f'{log_prefix}: Extracted file verified. Updating course started') courselike_items = import_func( modulestore(), user.id, settings.GITHUB_REPO_ROOT, [dirpath], load_error_modules=False, static_content_store=contentstore(), target_id=courselike_key, verbose=True, status=self.status ) new_location = courselike_items[0].location LOGGER.debug('new course at %s', new_location) LOGGER.info(f'{log_prefix}: Course import successful') set_custom_attribute('course_import_completed', True) except Exception as exception: # pylint: disable=broad-except msg = str(exception) status_msg = _('Unknown error while importing course.') if isinstance(exception, InvalidProctoringProvider): status_msg = msg LOGGER.exception(f'{log_prefix}: Unknown error while importing course {str(exception)}') if self.status.state != UserTaskStatus.FAILED: self.status.fail(status_msg) monitor_import_failure(courselike_key, current_step, exception=exception) finally: if course_dir.isdir(): shutil.rmtree(course_dir) LOGGER.info(f'{log_prefix}: Temp data cleared') if self.status.state == 'Updating' and is_course: # Reload the course so we have the latest state course = modulestore().get_course(courselike_key) if course.entrance_exam_enabled: entrance_exam_chapter = modulestore().get_items( course.id, qualifiers={'category': 'chapter'}, settings={'is_entrance_exam': True} )[0] metadata = {'entrance_exam_id': str(entrance_exam_chapter.location)} CourseMetadata.update_from_dict(metadata, course, user) from .views.entrance_exam import add_entrance_exam_milestone add_entrance_exam_milestone(course.id, entrance_exam_chapter) LOGGER.info(f'Course import {course.id}: Entrance exam imported') @shared_task @set_code_owner_attribute def update_outline_from_modulestore_task(course_key_str): """ Celery task that creates a learning_sequence course outline. """ try: course_key = CourseKey.from_string(course_key_str) if not key_supports_outlines(course_key): LOGGER.warning( ( "update_outline_from_modulestore_task called for course key" " %s, which does not support learning_sequence outlines." ), course_key_str ) return update_outline_from_modulestore(course_key) except Exception: # pylint disable=broad-except LOGGER.exception("Could not create course outline for course %s", course_key_str) raise # Re-raise so that errors are noted in reporting. def validate_course_olx(courselike_key, course_dir, status): """ Validates course olx and records the errors as an artifact. Arguments: courselike_key: A locator identifies a course resource. course_dir: complete path to the course olx status: UserTaskStatus object. """ is_library = isinstance(courselike_key, LibraryLocator) olx_is_valid = True log_prefix = f'Course import {courselike_key}' if is_library: return olx_is_valid if not course_import_olx_validation_is_enabled(): return olx_is_valid try: __, errorstore, __ = olxcleaner.validate(course_dir, steps=8, allowed_xblocks=ALL_ALLOWED_XBLOCKS) except Exception: # pylint: disable=broad-except LOGGER.exception(f'{log_prefix}: CourseOlx Could not be validated') return olx_is_valid log_errors = len(errorstore.errors) > 0 if log_errors: log_errors_to_artifact(errorstore, status) has_errors = errorstore.return_error(ErrorLevel.ERROR.value) if not has_errors: return olx_is_valid LOGGER.error(f'{log_prefix}: CourseOlx validation failed') # TODO: Do not fail the task until we have some data about kinds of # olx validation failures. TNL-8151 return olx_is_valid def log_errors_to_artifact(errorstore, status): """Log errors as a task artifact.""" def get_error_by_type(error_type): return [error for error in error_report if error.startswith(error_type)] error_summary = report_error_summary(errorstore) error_report = report_errors(errorstore) message = json.dumps({ 'summary': error_summary, 'errors': get_error_by_type(ErrorLevel.ERROR.name), 'warnings': get_error_by_type(ErrorLevel.WARNING.name), }) UserTaskArtifact.objects.create(status=status, name='OLX_VALIDATION_ERROR', text=message)
When you make an effort to get as much as possible out of the photos that you take, you'll find that - over time - you have a number of night shots as well as day shots. Using a printed photo book can enable you to showcase both scenarios. With printed photo books, what you are going to discover is that you are able to look at the extremes. Rather than showing your home town by day, contrast it with the beauty of lit fountains and glowing church windows at night. Rather than simply showing the wedding couple during the wedding and at the reception, include a few shots of them getting ready in the photo book as well. When you're able to include a wide variety of shots - whether you shoot weddings, travel photos, or even family portraits - it is essential to show contrast in order to allow your clients (or those who purchase the photo books that you self-publish) to remember everything about the shoot. On the other hand if, rather than printed photo books that are specifically for your clients you are self-publishing photo books, including a diversity of shots shows your range. It's the diversity that you show within your work that fully establishes you as a photographer. When you use printed photo books, you'll find that you're able to take control of marketing your work: it really is that simple.
# TRANSFORM fasta sequence after mutation # /Memoire/DIDAfasta # coding=utf-8 from numpy import * import petl as etl import operator import pandas as pd import re import csv #------------------------------------------------------------------------------- # Download and modify files from DIDA website #------------------------------------------------------------------------------- DIDAgenes = 'DIDA_Genes_a000.csv' #Gene name + Uniprot ACC (delimiter='\t') table1 = etl.fromcsv('DIDA_Genes_a000.csv', delimiter='\t') table2 = etl.rename(table1, {'Uniprot ACC': 'Uniprot_ACC','Gene name': 'Gene_name' }) table3 = etl.cut(table2, 'Uniprot_ACC', 'Gene_name') etl.totsv(table3,'_didagenes.csv') #137 lignes table4 = etl.fromcsv('DIDA_Variants_108c0.csv', delimiter='\t') table5 = etl.split(table4, 'Protein change', '\)', ['Protein change','']) table6 = etl.cutout(table5,'') table7 = etl.split(table6, 'Protein change', '\(', ['','Protein change']) table8 = etl.cutout(table7,'') table9 = etl.rename(table8, {'Gene name': 'Gene_name','Variant effect':'Variant_effect','Protein change':'Protein_change' }) etl.totsv(table9,'_didavariants.csv') #------------------------------------------------------------------------------- # Creation of file with fasta sequence mutant #------------------------------------------------------------------------------- file_variants = '_didavariants.csv' #364 variants file_genes = '_didagenes.csv' #136 genes a = pd.read_csv(file_variants,'\t') b = pd.read_csv(file_genes,'\t') merged = a.merge(b, on='Gene_name') merged.to_csv('_didavariantsgenes.csv', index=False) V = open('_didavariantsgenes.csv','r') c1 = csv.reader(V,delimiter=',') variants = list(c1) variants.pop(0) file_fasta_wt = 'DIDAgenes_wt.txt' #136 sequences file_fasta_mut = 'DIDAgenes_mut.txt' # OUTPUT file fasta = open(file_fasta_wt,'r') mutant = open(file_fasta_mut,'w') lines = fasta.readlines() sequences={} #all fasta sequences without the 1st line > listID={} #to keep the first line of fasta sequence with all informations for i in range(0,len(lines)): if lines[i].startswith('>'): splitline = lines[i].split('|') accessorID = splitline[1] listID[accessorID] = lines[i].split(' ')[0] sequences[accessorID] = '' else: sequences[accessorID] = sequences[accessorID] + lines[i].rstrip('\n').rstrip('*') #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # LENGTH OF PROTEINS #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ fasta = open('DIDAgenes_wt.txt','r') lines = fasta.readlines() sequences={} for i in range(0,len(lines)): if lines[i].startswith('>'): splitline = lines[i].split('|') accessorID = splitline[1] sequences[accessorID] = '' else: sequences[accessorID] = sequences[accessorID] + lines[i].rstrip('\n').rstrip('*') csv_file = open('DIDAlength.csv','w') cL = csv.writer(csv_file) head_row = ['Uniprot_ACC','length'] cL.writerow(head_row) length_list=[] for key, value in sequences.items(): length = len(value) length_list.append(len(value)) cL.writerow([key,length]) csv_file.close() # BARCHART statistique import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('DIDAlength2.csv','\t') #df = df.set_index('Uniprot_ACC') df.plot(kind='bar',legend=False) plt.ylabel('Uniprot ACC') plt.savefig('barplotDIDA_length.png') # HISTOGRAMME from scipy import stats from pylab import plot, show, savefig, xlim, figure, \ hold, ylim, legend, boxplot, setp, axes fig = figure() mu2, std2 = stats.norm.fit(log(length_list)) bins = np.linspace(0, 99, 30) plt.hist(log(length_list),normed=True,bins=15,alpha=0.8) xmin2, xmax2 = plt.xlim() x2 = np.linspace(xmin2, xmax2, 100) p2 = stats.norm.pdf(x2, mu2, std2) plt.plot(x2, p2, 'k--',linewidth=2) plt.xlabel('log(protein length)') plt.ylabel('Frequence') #plt.xlim(-4,4) #plt.ylim(0,0.8) plt.title('fit results: mu=%.2f, std=%.2f'%(mu2, std2)) fig.savefig('histo_DIDA_length.png') #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # MODIFICATION of fasta sequence after mutation #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ PROBLEME =[] compteur = 0 for v in variants: for ID in sequences.keys(): if ID == v[4]: #--------------------------------------------------------------- if v[2]=='deletion': l1=list(v[3]) aa1 = l1[0] objet1 = re.search(r'[0-9]+',v[3]) position1 = int(objet1.group()) s1 = list(sequences[ID]) if s1[position1 - 1]==aa1 : s1[position1 - 1] = '' seq1=''.join(s1) mutant.write(listID[ID] + '|variant_' + v[0] + '\n') for i in range(0,len(seq1),60): mutant.write(seq1[i:min(len(seq1),i+60)] + '\n') else: str1='PROBLEME in '+ ID + ' position ' + str(position1) PROBLEME.append(str1) compteur = compteur + 1 #--------------------------------------------------------------- elif v[2]=='insertion': l3=list(v[3]) aa3 = l3[0] objet3 = re.search(r'[0-9]+',v[3]) position3 = int(objet3.group()) #new AA objet3bis = re.search(r'[A-Z]+$',v[3] ) new_aa3=objet3bis.group() s3 = list(sequences[ID]) if s3[position3 - 1]==aa3 : s3[position3] = new_aa3 + s3[position3] seq3=''.join(s3) mutant.write(listID[ID] + '|variant_' + v[0] + '\n') for i in range(0,len(seq3),60): mutant.write(seq3[i:min(len(seq3),i+60)] + '\n') else: str3 = 'PROBLEME in '+ ID + ' position '+ str(position3) PROBLEME.append(str3) compteur = compteur + 1 #----------------------------------------------------------------- elif v[2]=='missense': l4=list(v[3]) aa4 = l4[0] objet4 = re.search(r'[0-9]+',v[3]) position4 = int(objet4.group()) #new AA new_aa4=l4[-1] s4 = list(sequences[ID]) if s4[position4 - 1]==aa4 : s4[position4 - 1] = new_aa4 seq4=''.join(s4) mutant.write(listID[ID] + '|variant_' + v[0] + '\n') for i in range(0,len(seq4),60): mutant.write(seq4[i:min(len(seq4),i+60)] + '\n') else: str4 = 'PROBLEME in '+ ID + ' position '+ str(position4) PROBLEME.append(str4) compteur = compteur + 1 #---------------------------------------------------------------NO CHANGE elif v[2]=='silent': seq6 = sequences[ID] mutant.write(listID[ID] + '|variant_' + v[0] + '\n') for i in range(0,len(seq6),60): mutant.write(seq6[i:min(len(seq6),i+60)] + '\n') compteur = compteur + 1 fasta.close() V.close() mutant.close()
I've never been keen on it. I suppose it fits the origin story, but I wouldn't mind a change with something more original. I like it, it should stay as long as we're still in the current timeline. I wouldn't be against the original one making a comeback either. I'm not really sure what is meant by this. If it means Lara out in the wilderness and with a sense of danger (with Lara not always getting through unscathed), then yes, it should stay. Lara's always faced dangerous terrains, so it feels pretty normal to keep it. I love using the bow, if appropriate for the environment. It should definitely stay as part of Lara's arsenal. They're pretty much part of current Lara's gear now and have many uses, so should stay if appropriate. I think they work well for save points and for choosing weapons/fast travel etc. They may seem out of place though should Lara ever visit more modern locations. It's fine, but if the story can work around it with the myth chosen, then I think I'd prefer globe-trotting. I love the hub system, but they need to be worked into the main story path and included with mandatory exploration. I prefer sizes akin to Mountain Village, Geothermal Valley at most. Logo : similar to what you said, I want it to remain similar so it feels like the same timeline but with a small twist, like Underworld's. I'd only want a total, AoD-style change if the next game was revolutionary. Main theme : I definitely want a new theme. Compared to how the first 5 games played with similar notes or how AoD and LAU had completely different themes, the reboot trilogy constantly using the same music got a bit old. I want a new, more impactful theme, with the TR2013 one only appearing once in the game as a nod. Survival theme : No more survival. A survivor was born 6 bloody years ago, it's about time Lara goes into adventures voluntarily and stops struggling to survive, but just wins. The axe(s) : They're fun but I want less of them. Add something like the climbing in TRU where Lara used a lot of rocks, and only bring the axes to specific levels with full-on mountains in front of you. Fire camps : Super bored of them, don't need them. One location : Ideally I want Legend-style globetrotting to return, or at least something like Shadow's moving from one country to the next but with more locations than just 2. Semi open world : I'm tired of the semi open world. I'd rather have more linear, straight-forward environments. Hubs : A social hub like Paititi should only return if it's much more polished and much less pointlessly large. I'd rather have a hub that's a giant tomb, but still, I'm not particularly fond of hubs. As for me, I want it to stay because it had potential to be really fun if done right, at least for the skill tree. About weapon upgrades, keep it simple. Combining silencer or sights, more powerful or more ammos. Just that, good enough. Also I'm not interested about 100 versions of the same four weapons. I want quite but simple with their unique task : a gun, a shotgun, a bow, a sniper, a flamethrower, a grenade launcher, a rocket launcher, a machine gun, harpoon gun... Ok I stop there. Wait for the weapons it's logical but for the combat or the platforming don't it would be contradictory by playing with an experienced Lara Croft if she as to learn something ? I mean some new things never seen in the origin games. I don't want her to learn again old things, she has to have them right in the beginning. I just want new ones. Last edited by Chamayoo; 04-02-19 at 21:30. Logo - Ditch it, never matched what TR was anyway, too gritty. Main music theme - Dull and uninspired and irrelevant too. It not used in the same nature of previous entries either. Survival theme - Overused and boring, there weren't actually any real survival elements in the games anyway. Also its not a survival game toss it out. The bow - A bow isn't as effective as the reboots make them out to be, and beyond realism it just outright doesn't look flattering on the real Lara, its a mismatch and makes no sense to make her have something like that. How about we get the Crossbow back instead, that actually had much more sense and is more aesthetically fitting. The axe(s) - Barely keep them. They only have a place due to adding additional mechanics they should be redesigned, I'd prefer they don't come back however, I think they appeal too much to the whole idea of the game holding on to ledges for you. Fire camps - Why even bother keeping them? They don't really have a place in Tomb Raider, as in options? I'd want level ups removed and weapon upgrades implemented more akin to Resident Evil classics. Besides most of that could be accessible within an actual inventory, the backpack is more iconic and tops the fire camps any day. Besides this if the camps were to be back it should be as crystals, you know to restore a bit of identity to this franchise. One main location - As in a whole game in Russia or Egypt? If so I think its fine to do again but probably better not to and let her travel around. Really depends on the nature of the adventure. Semi open world - Only as far as Last Revelation. I suppose the reboots kind of did it in this vain too? Hubs - Only as far as the classics went. I feel they did it best. The reboot honestly did very little to actually add. LAU did the same thing of pretty much just removing. I don't see the point in respecting elements of a reboot that aren't even relevant to the franchise, top it off with the fact that most of these things barely matter anyway and some better form or alternative in the classics. This isn't a case of being rude towards the reboot, its just more the fact non of its elements actually matter. Moving forward with it actually being a "Tomb Raider" game the sequel should just outright drop many of its elements. You're a dream I'm an open door Put anything in I=Fantasy Fantasy! Last edited by jhons0529; 17-02-19 at 22:44. Logo - I don't mind the Logo, that's something that's never bothered me. I do think they need to stick to Tomb Raider: Insert Second Title. Survival theme - Lara's not a survivor, get rid. The bow - I love the bow, out of all reboots arsenal this is the one weapon I would hate to see be removed. The axe(s) - Get rid of them and give us a free climbing Lara. Sure the mechanics and animations where fun in TR'13 but they're starting to get boring and old now and having to upgrade Lara to climb faster in all three games is a joke. Fire camps - Keep them, remove them I don't actually care. The way I view campfires is the same way I look at the save crystals from TR1 (PS). Save points and perhaps upgrade if I wish. One main location - Sure as long as the one location is diverse. One thing I loved about TR'13 is that each part of the island was completely different. You had the dark forest, the snowy peak by the radio tower, the windy chasm and the sunny shipwreck beach. Hubs - Have them like TR'13. Whilst Shadow and Rise had stunning looking hubs, they were filled with pointless crap and collectibles that turned exploring into a chore.
##!/usr/bin/env python # encoding:utf-8 # # Copyright 2014-2017 Yoshihiro Tanaka # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __Author__ = "Yoshihiro Tanaka" __date__ = "2015-01-13" import smtplib from email.mime.text import MIMEText def send_gmail(sub, msg, address): From = "your gmail address" To = address Subject = sub Message = msg msg = MIMEText(Message) msg['Subject'] = Subject msg['From'] = From msg['To'] = To s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() s.ehlo() s.login(From, "your gmail password") s.sendmail(From, To, msg.as_string()) s.close()
Reuge Music 3.72 Note Musical Jewelry Box. This is an absolutely beautiful Vintage LARGE musical jewelry box MADE IN ITALY with a THREE TUNE 72 NOTE SWISS MOVEMENT. This box is in pristine condition except for some barely noticeable marks on the inside lid. Was never used, only displayed in a curio cabinet to show the beauty of the music box. The box measures approximately 21" long X 9-1/4" wide X 4-3/4 in height. The box is wood with inlays on the top cover displaying violin, musical instruments, sheet music and flowers. The inside is done in pink velvet type material. It has a top tray that lifts out with a velvet bottom for larger pieces of jewelry. The REUGE ROMANCE THREE TUNE 72 NOTE ROMANCE MOVEMENT is mounted on the right side of the box. The movement is wound from the bottom and has a key to lock it. BUT UNFORTUNATELY THE KEY FOR THE LOCK IS MISSING. The three tunes are from Tchaikovskys Nutcracker suite. 1: March of the toy soldier. 2: Waltz of the flower. 3: Dance of the sugar plum fairy. Pyotr Ilyich Tchaikovsky, often anglicized as Peter Ilich Tchaikovsky, was a Russian composer of the romantic period, some of whose works are among the most popular music in the classical repertoire. Please see video of music box playing at. The item "Reuge Music 3.72 Note Musical Jewelry Box Tchaikovsky Nutcracker 3 tunes LARGE" is in sale since Tuesday, September 4, 2018. This item is in the category "Collectibles\Decorative Collectibles\Music Boxes\1970-Now". The seller is "keswani" and is located in Yorba Linda, California. This item can be shipped to United States, Canada, United Kingdom, Denmark, Romania, Slovakia, Bulgaria, Czech republic, Finland, Hungary, Latvia, Lithuania, Malta, Estonia, Australia, Greece, Portugal, Cyprus, Slovenia, Japan, China, Sweden, South Korea, Indonesia, Taiwan, Thailand, Belgium, France, Hong Kong, Ireland, Netherlands, Poland, Spain, Italy, Germany, Austria, Israel, Mexico, New Zealand, Singapore, Switzerland, Norway, Saudi arabia, Ukraine, United arab emirates, Qatar, Kuwait, Bahrain, Croatia, Malaysia, Chile, Colombia, Costa rica, Panama, Trinidad and tobago, Guatemala, Honduras, Jamaica.