function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def tune(self, freq): result = self.u.set_center_freq(freq) return True
bistromath/gr-smartnet
[ 44, 22, 44, 4, 1301549389 ]
def setvolume(self, vol): self.audiogain.set_k(vol)
bistromath/gr-smartnet
[ 44, 22, 44, 4, 1301549389 ]
def unmute(self, volume): self.setvolume(volume)
bistromath/gr-smartnet
[ 44, 22, 44, 4, 1301549389 ]
def parsefreq(s, chanlist): retfreq = None [address, groupflag, command] = s.split(",") command = int(command) address = int(address) & 0xFFF0 groupflag = bool(groupflag) if chanlist is None: if command < 0x2d0: retfreq = getfreq(chanlist, command) else: if chanlist.get(str(command), None) is not None: #if it falls into the channel somewhere retfreq = getfreq(chanlist, command) return [retfreq, address] # mask so the squelch opens up on the entire group
bistromath/gr-smartnet
[ 44, 22, 44, 4, 1301549389 ]
def main(): # Create Options Parser: parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-f", "--freq", type="eng_float", default=866.9625e6, help="set control channel frequency to MHz [default=%default]", metavar="FREQ") parser.add_option("-c", "--centerfreq", type="eng_float", default=867.5e6, help="set center receive frequency to MHz [default=%default]. Set to center of 800MHz band for best results") parser.add_option("-g", "--gain", type="int", default=None, help="set RF gain", metavar="dB") parser.add_option("-b", "--bandwidth", type="eng_float", default=3e6, help="set bandwidth of DBS RX frond end [default=%default]") parser.add_option("-F", "--filename", type="string", default=None, help="read data from filename rather than USRP") parser.add_option("-t", "--tgfile", type="string", default="sf_talkgroups.csv", help="read in CSV-formatted talkgroup list for pretty printing of talkgroup names") parser.add_option("-C", "--chanlistfile", type="string", default="motochan14.csv", help="read in list of Motorola channel frequencies (improves accuracy of frequency decoding) [default=%default]") parser.add_option("-e", "--allowdupes", action="store_false", default=True, help="do not eliminate duplicate records (produces lots of noise)") parser.add_option("-E", "--error", type="eng_float", default=0, help="enter an offset error to compensate for USRP clock inaccuracy") parser.add_option("-u", "--audio", action="store_true", default=False, help="output audio on speaker") parser.add_option("-m", "--monitor", type="int", default=None, help="monitor a specific talkgroup") parser.add_option("-v", "--volume", type="eng_float", default=0.2, help="set volume gain for audio output [default=%default]") parser.add_option("-s", "--squelch", type="eng_float", default=28, help="set audio squelch level (default=%default, play with it)") parser.add_option("-s", "--subdev", type="string", help="UHD subdev spec", default=None) parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-r", "--rate", type="eng_float", default=64e6/18, help="set sample rate [default=%default]") parser.add_option("-a", "--addr", type="string", default="", help="address options to pass to UHD") #receive_path.add_options(parser, expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.tgfile is not None: tgreader=csv.DictReader(open(options.tgfile), quotechar='"') shorttglist = {"0": 0} longtglist = {"0": 0} for record in tgreader:
bistromath/gr-smartnet
[ 44, 22, 44, 4, 1301549389 ]
def __init__(self, name): self._name = name
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def size(self): raise NotImplementedError
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def str(self): if self.value() is not None: return self._register_fmt[self.size()] % self.value() chars_per_byte = 2 return ''.join(['-' * (self.size() * chars_per_byte)])
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def __init__(self, name): super(StaticRegister, self).__init__(name) self._size = register.size() self._value = register.value()
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def value(self): return self._value
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def __init__(self, cpu_factory, registers): self._registers = OrderedDict() for group, register_list in registers.iteritems(): registers = OrderedDict([(x.name(), cpu_factory.create_register(self, x)) for x in register_list]) self._registers[group] = registers
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def architecture(cls): raise NotImplementedError
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def registers(self): return self._registers.iteritems()
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def stack_pointer(self): raise NotImplementedError
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def program_counter(self): raise NotImplementedError
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def create_cpu(self, architecture): assert architecture in _cpu_map return _cpu_map.get(architecture, None)(self)
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def create_register(self, cpu, register): raise NotImplementedError
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def __init__(self, cpu_factory): self._cpu_factory = cpu_factory self._cpus = {}
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def register_cpu(cls): _cpu_map[cls.architecture()] = cls return cls
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def test_poses1_all_pairs(self): target_path = 1.0 tol = 0.0 id_pairs = filters.filter_pairs_by_path(POSES_1, target_path, tol, all_pairs=True) self.assertEqual(id_pairs, [(0, 2), (2, 3)])
MichaelGrupp/evo
[ 2455, 657, 2455, 17, 1505331600 ]
def test_poses2_all_pairs_low_tolerance(self): target_path = 1.0 tol = 0.001 id_pairs = filters.filter_pairs_by_path(POSES_2, target_path, tol, all_pairs=True) self.assertEqual(id_pairs, [(0, 3)])
MichaelGrupp/evo
[ 2455, 657, 2455, 17, 1505331600 ]
def test_poses5(self): tol = 0.001 expected_result = [(0, 1), (1, 2), (2, 4)] # Result should be unaffected by global transformation. for poses in (POSES_5, POSES_5_TRANSFORMED): target_angle = math.pi - tol id_pairs = filters.filter_pairs_by_angle(poses, target_angle, tol, all_pairs=False) self.assertEqual(id_pairs, expected_result) # Check for same result when using degrees: target_angle = np.rad2deg(target_angle) id_pairs = filters.filter_pairs_by_angle(poses, target_angle, tol, all_pairs=False, degrees=True) self.assertEqual(id_pairs, expected_result)
MichaelGrupp/evo
[ 2455, 657, 2455, 17, 1505331600 ]
def test_poses6(self): tol = 0.001 target_angle = math.pi - tol expected_result = [(0, 3)] # Result should be unaffected by global transformation. for poses in (POSES_6, POSES_6_TRANSFORMED): id_pairs = filters.filter_pairs_by_angle(poses, target_angle, tol, all_pairs=False) self.assertEqual(id_pairs, expected_result)
MichaelGrupp/evo
[ 2455, 657, 2455, 17, 1505331600 ]
def __init__(self, backendsdialog): """ Constructor, just initializes the gtk widgets @param backends: a reference to the dialog in which this is loaded """ super().__init__() self.dialog = backendsdialog self.req = backendsdialog.get_requester() self._init_liststore() self._init_renderers() self._init_signals() self.refresh()
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def on_backend_added(self, sender, backend_id): """ Signal callback executed when a new backend is loaded @param sender: not used, only here to let this function be used as a callback @param backend_id: the id of the backend to add """ # Add backend = self.req.get_backend(backend_id) if not backend: return self.add_backend(backend) self.refresh() # Select self.select_backend(backend_id) # Update it's enabled state self.on_backend_state_changed(None, backend.get_id())
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def on_backend_state_changed(self, sender, backend_id): """ Signal callback executed when a backend is enabled/disabled. @param sender: not used, only here to let this function be used as a callback @param backend_id: the id of the backend to add """ if backend_id in self.backendid_to_iter: b_iter = self.backendid_to_iter[backend_id] b_path = self.liststore.get_path(b_iter) backend = self.req.get_backend(backend_id) backend_name = backend.get_human_name() if backend.is_enabled(): text = backend_name else: # FIXME This snippet is on more than 2 places!!! # FIXME create a function which takes a widget and # flag and returns color as #RRGGBB style_context = self.get_style_context() color = style_context.get_color(Gtk.StateFlags.INSENSITIVE) color = rgba_to_hex(color) text = f"<span color='{color}'>{backend_name}</span>" self.liststore[b_path][self.COLUMN_TEXT] = text # Also refresh the tags new_tags = self._get_markup_for_tags(backend.get_attached_tags()) self.liststore[b_path][self.COLUMN_TAGS] = new_tags
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def remove_backend(self, backend_id): """ Removes a backend from the treeview, and selects the first (to show something in the configuration panel @param backend_id: the id of the backend to remove """ if backend_id in self.backendid_to_iter: self.liststore.remove(self.backendid_to_iter[backend_id]) del self.backendid_to_iter[backend_id] self.select_backend()
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def _init_renderers(self): """Initializes the cell renderers""" # We hide the columns headers self.set_headers_visible(False) # For the backend icon pixbuf_cell = Gtk.CellRendererPixbuf() tvcolumn_pixbuf = Gtk.TreeViewColumn('Icon', pixbuf_cell) tvcolumn_pixbuf.add_attribute(pixbuf_cell, 'pixbuf', self.COLUMN_ICON) self.append_column(tvcolumn_pixbuf) # For the backend name text_cell = Gtk.CellRendererText() tvcolumn_text = Gtk.TreeViewColumn('Name', text_cell) tvcolumn_text.add_attribute(text_cell, 'markup', self.COLUMN_TEXT) self.append_column(tvcolumn_text) text_cell.connect('edited', self.cell_edited_callback) text_cell.set_property('editable', True) # For the backend tags tags_cell = Gtk.CellRendererText() tvcolumn_tags = Gtk.TreeViewColumn('Tags', tags_cell) tvcolumn_tags.add_attribute(tags_cell, 'markup', self.COLUMN_TAGS) self.append_column(tvcolumn_tags)
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def _init_signals(self): """Initializes the backends and gtk signals """ self.connect("cursor-changed", self.on_select_row) _signals = BackendSignals() _signals.connect(_signals.BACKEND_ADDED, self.on_backend_added) _signals.connect(_signals.BACKEND_STATE_TOGGLED, self.on_backend_state_changed)
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def _get_selected_path(self): """ Helper function to get the selected path @return Gtk.TreePath : returns exactly one path for the selected object or None """ selection = self.get_selection() if selection: model, selected_paths = self.get_selection().get_selected_rows() if selected_paths: return selected_paths[0] return None
getting-things-gnome/gtg
[ 519, 158, 519, 226, 1394882179 ]
def deltaW(N, m, h): """Generate sequence of Wiener increments for m independent Wiener processes W_j(t) j=0..m-1 for each of N time intervals of length h. Returns: dW (array of shape (N, m)): The [n, j] element has the value W_j((n+1)*h) - W_j(n*h) """ return np.random.normal(0.0, np.sqrt(h), (N, m))
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def _dot(a, b): r""" for rank 3 arrays a and b, return \sum_k a_ij^k . b_ik^l (no sum on i) i.e. This is just normal matrix multiplication at each point on first axis """ return np.einsum('ijk,ikl->ijl', a, b)
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def Ikpw(dW, h, n=5): """matrix I approximating repeated Ito integrals for each of N time intervals, based on the method of Kloeden, Platen and Wright (1992). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (A, I) where A: array of shape (N, m, m) giving the Levy areas that were used. I: array of shape (N, m, m) giving an m x m matrix of repeated Ito integral values for each of the N time intervals. """ N = dW.shape[0] m = dW.shape[1] if dW.ndim < 3: dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1) if dW.shape[2] != 1 or dW.ndim > 3: raise(ValueError) A = _Aterm(N, h, m, 1, dW) for k in range(2, n+1): A += _Aterm(N, h, m, k, dW) A = (h/(2.0*np.pi))*A I = 0.5*(_dot(dW, _t(dW)) - np.diag(h*np.ones(m))) + A dW = dW.reshape((N, -1)) # change back to shape (N, m) return (A, I)
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def _vec(A): """ Linear operator _vec() from Wiktorsson2001 p478 Args: A: a rank 3 array of shape N x m x n, giving a matrix A[j] for each interval of time j in 0..N-1 Returns: array of shape N x mn x 1, made by stacking the columns of matrix A[j] on top of each other, for each j in 0..N-1 """ N, m, n = A.shape return A.reshape((N, m*n, 1), order='F')
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def _kp(a, b): """Special case Kronecker tensor product of a[i] and b[i] at each time interval i for i = 0 .. N-1 It is specialized for the case where both a and b are shape N x m x 1 """ if a.shape != b.shape or a.shape[-1] != 1: raise(ValueError) N = a.shape[0] # take the outer product over the last two axes, then reshape: return np.einsum('ijk,ilk->ijkl', a, b).reshape(N, -1, 1)
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def _P(m): """Returns m^2 x m^2 permutation matrix that swaps rows i and j where j = 1 + m((i - 1) mod m) + (i - 1) div m, for i = 1 .. m^2 """ P = np.zeros((m**2,m**2), dtype=np.int64) for i in range(1, m**2 + 1): j = 1 + m*((i - 1) % m) + (i - 1)//m P[i-1, j-1] = 1 return P
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def _AtildeTerm(N, h, m, k, dW, Km0, Pm0): """kth term in the sum for Atilde (Wiktorsson2001 p481, 1st eqn)""" M = m*(m-1)//2 Xk = np.random.normal(0.0, 1.0, (N, m, 1)) Yk = np.random.normal(0.0, 1.0, (N, m, 1)) factor1 = np.dot(Km0, Pm0 - np.eye(m**2)) factor1 = broadcast_to(factor1, (N, M, m**2)) factor2 = _kp(Yk + np.sqrt(2.0/h)*dW, Xk) return _dot(factor1, factor2)/k
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def _a(n): r""" \sum_{n+1}^\infty 1/k^2 """ return np.pi**2/6.0 - sum(1.0/k**2 for k in range(1, n+1))
mattja/sdeint
[ 128, 20, 128, 13, 1444052310 ]
def main(): """Instantiate a DockerStats object and collect stats.""" print('Docker Service Module')
gomex/docker-zabbix
[ 47, 13, 47, 8, 1430055996 ]
def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id))
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def save(self, doc): if doc.id: return self.update(doc) else: return self.insert(doc)
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS: pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced} else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e)
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def get_last_tid(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0
lvidarte/lai-client
[ 4, 3, 4, 5, 1334839689 ]
def eps(omk): return omk**2/(2+omk**2)
ester-project/ester
[ 15, 10, 15, 5, 1412668435 ]
def __init__(self, message_name): """Store the message name.""" self.message_name = message_name self.callback = None
GunGame-Dev-Team/GunGame-SP
[ 7, 1, 7, 5, 1390774094 ]
def _unload_instance(self): """Unregister the message hook.""" message_manager.unhook_message(self.message_name, self.callback)
GunGame-Dev-Team/GunGame-SP
[ 7, 1, 7, 5, 1390774094 ]
def __init__(self, message_prefix): """Store the message prefix.""" self.message_prefix = message_prefix self.callback = None
GunGame-Dev-Team/GunGame-SP
[ 7, 1, 7, 5, 1390774094 ]
def zscore(features, remove_outlier=0): zscores = scipy.stats.zscore(features, 0) # zscores = normalizeFeatures(features) return zscores
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def copySnapshots(df_in, snapshots_dir, output_dir): if not os.path.exists(output_dir): os.mkdir(output_dir) swc_files = df_in['swc_file_name'] if len(swc_files) > 0: for afile in swc_files: filename = snapshots_dir + '/' + afile.split('/')[-1] + '.BMP' if os.path.exists(filename): os.system("cp " + filename + " " + output_dir + "/\n") return
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def generateLinkerFileFromDF(df_in, output_ano_file, strip_path=False, swc_path=None): swc_files = df_in['swc_file_name'] if len(swc_files) > 0: with open(output_ano_file, 'w') as outf: for afile in swc_files: if swc_path is not None: filename = swc_path + '/'+afile else: filename = afile if strip_path: filename = afile.split('/')[-1] line = 'SWCFILE=' + filename + '\n' outf.write(line) outf.close() return
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def plot_confusion_matrix(cm, xlabel, ylabel, xnames, ynames, title='Confusion matrix', cmap=pl.cm.Blues): pl.grid(False) pl.imshow(cm, interpolation = 'none',cmap=cmap) pl.title(title) pl.colorbar() tick_marksx = np.arange(len(xnames)) tick_marksy = np.arange(len(ynames)) pl.xticks(tick_marksx, xnames) pl.yticks(tick_marksy, ynames) pl.tight_layout() pl.ylabel(ylabel) pl.xlabel(xlabel)
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def heatmap_plot_zscore_bbp(df_zscore_features, df_all, output_dir, title=None): print "heatmap plot" metric ='m-type' mtypes = np.unique(df_all[metric]) print mtypes mtypes_pal = sns.color_palette("hls", len(mtypes)) mtypes_lut = dict(zip(mtypes, mtypes_pal)) # map creline type to color mtypes_colors = df_all[metric].map(mtypes_lut) layers = np.unique(df_all['layer']) layer_pal = sns.light_palette("green", len(layers)) layers_lut = dict(zip(layers, layer_pal)) layer_colors = df_all['layer'].map(layers_lut) # Create a custom colormap for the heatmap values #cmap = sns.diverging_palette(240, 10, as_cmap=True) linkage = hierarchy.linkage(df_zscore_features, method='ward', metric='euclidean') data = df_zscore_features.transpose() row_linkage = hierarchy.linkage(data, method='ward', metric='euclidean') feature_order = hierarchy.leaves_list(row_linkage) #print data.index matchIndex = [data.index[x] for x in feature_order] #print matchIndex data = data.reindex(matchIndex) g = sns.clustermap(data, row_cluster = False, col_linkage=linkage, method='ward', metric='euclidean', linewidths = 0.0,col_colors = [mtypes_colors,layer_colors], cmap = sns.cubehelix_palette(light=1, as_cmap=True),figsize=(40,20)) #g.ax_heatmap.xaxis.set_xticklabels() pl.setp(g.ax_heatmap.xaxis.get_majorticklabels(), rotation=90 ) pl.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) pl.subplots_adjust(left=0.1, bottom=0.5, right=0.9, top=0.95) # !!!!! #pl.tight_layout( fig, h_pad=20.0, w_pad=20.0) if title: pl.title(title) location ="best" num_cols=1 # Legend for row and col colors for label in mtypes: g.ax_row_dendrogram.bar(0, 0, color=mtypes_lut[label], label=label, linewidth=0.0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols,borderpad=0) for i in range(3): g.ax_row_dendrogram.bar(0, 0, color = "white", label=" ", linewidth=0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols, borderpad=0.0) for label in layers: g.ax_row_dendrogram.bar(0, 0, color=layers_lut[label], label=label, linewidth=0.0) g.ax_row_dendrogram.legend(loc=location, ncol=num_cols,borderpad=0) filename = output_dir + '/zscore_feature_heatmap.png' pl.savefig(filename, dpi=300) #pl.show() print("save zscore matrix heatmap figure to :" + filename) pl.close() return linkage
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def remove_correlated_features(df_all, feature_names, coef_threshold=0.98): num_features = len(feature_names) removed_names = [] for i in range(num_features): if not feature_names[i] in removed_names: a = df_all[feature_names[i]].astype(float) for j in range(i + 1, num_features): if not feature_names[j] in removed_names: b = df_all[feature_names[j]].astype(float) corrcoef = pearsonr(a, b) if (corrcoef[0] > coef_threshold): removed_names.append(feature_names[j]) print("highly correlated:[" + feature_names[i] + ", " + feature_names[j] + " ]") subset_features_names = feature_names.tolist() for i in range(len(removed_names)): if removed_names[i] in subset_features_names: print ("remove " + removed_names[i]) subset_features_names.remove(removed_names[i]) return np.asarray(subset_features_names)
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def delta(ck, cl): values = np.ones([len(ck), len(cl)]) * 10000 for i in range(0, len(ck)): for j in range(0, len(cl)): values[i, j] = np.linalg.norm(ck[i] - cl[j]) return np.min(values)
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def dunn(k_list): """ Dunn index [CVI] Parameters ---------- k_list : list of np.arrays A list containing a numpy array for each cluster |c| = number of clusters c[K] is np.array([N, p]) (N : number of samples in cluster K, p : sample dimension) """ deltas = np.ones([len(k_list), len(k_list)]) * 1000000 big_deltas = np.zeros([len(k_list), 1]) l_range = range(0, len(k_list)) for k in l_range: for l in (l_range[0:k] + l_range[k + 1:]): deltas[k, l] = delta(k_list[k], k_list[l]) big_deltas[k] = big_delta(k_list[k]) di = np.min(deltas) / np.max(big_deltas) return di
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def cluster_specific_features(df_all, assign_ids, feature_names, output_csv_fn): #student t to get cluster specific features labels=[] clusters = np.unique(assign_ids) num_cluster = len(clusters) df_pvalues = pd.DataFrame(index = feature_names, columns = clusters) for cluster_id in clusters: ids_a = np.nonzero(assign_ids == cluster_id)[0] # starting from 0 ids_b = np.nonzero(assign_ids != cluster_id)[0] # starting from 0 labels.append("C"+str(cluster_id) + "("+ str(len(ids_a))+")" ) for feature in feature_names: a = df_all.iloc[ids_a][feature] b = df_all.iloc[ids_b][feature] t_stats,pval = stats.ttest_ind(a,b,equal_var=False) df_pvalues.loc[feature,cluster_id] = -np.log10(pval) df_pvalues.to_csv(output_csv_fn) ### visulaize df_pvalues.index.name = "Features" df_pvalues.columns.name ="Clusters" d=df_pvalues[df_pvalues.columns].astype(float) g = sns.heatmap(data=d,linewidths=0.1) # cmap =sns.color_palette("coolwarm",7, as_cmap=True)) g.set_xticklabels(labels) pl.yticks(rotation=0) pl.xticks(rotation=90) pl.subplots_adjust(left=0.5, right=0.9, top=0.9, bottom=0.1) pl.title('-log10(P value)') filename = output_csv_fn + '.png' pl.savefig(filename, dpi=300) #pl.show() pl.close() return df_pvalues
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def get_zscore_features(df_all, feature_names, out_file, REMOVE_OUTLIER=0, zscore_threshold=ZSCORE_OUTLIER_THRESHOLD): # if remove_outlier ==0 , just clip at threshold featureArray = df_all[feature_names].astype(float) featureArray.fillna(0,inplace=True) ### might introduce some bias normalized = zscore(featureArray) # normalized = featureArray # normalized[~np.isnan(featureArray)] = zscore(featureArray[~np.isnan(featureArray)]) num_outliers = np.count_nonzero(normalized < -zscore_threshold) + np.count_nonzero( normalized > zscore_threshold) print("Found %d |z score| > %f in zscore matrix :" % (num_outliers, zscore_threshold) ) df_all_modified = df_all df_outliers = pd.DataFrame() if num_outliers > 0: if not REMOVE_OUTLIER: # just clip normalized[normalized < -zscore_threshold] = -zscore_threshold normalized[normalized > zscore_threshold] = zscore_threshold # else: # outliers_l = np.nonzero(normalized < -zscore_threshold) # outliers_h = np.nonzero(normalized > zscore_threshold) # outlier_index = np.unique((np.append(outliers_l[0], outliers_h[0]))) # # # remove outlier rows # df_all_modified = df_all_modified.drop(df_all_modified.index[outlier_index]) # normalized = np.delete(normalized, outlier_index, 0) # # # re-zscoring and clipping # # m_featureArray = df_all_modified[feature_names].astype(float) # # normalized = zscore(m_featureArray) # # normalized[normalized < -zscore_threshold] = -zscore_threshold # # normalized[normalized > zscore_threshold] = zscore_threshold # # # print("Removed %d outlier neurons" % len(outlier_index)) # # df_outliers = df_all.iloc[outlier_index] df_z = pd.DataFrame(normalized) df_z.columns = feature_names df_z.index = df_all['swc_file_name'] if out_file: df_z.to_csv(out_file, index=True) print("save to " + out_file ) if (df_z.shape[0] != df_all_modified.shape[0]): print ("error: the sample size of the zscore and the original table does not match!") return df_z, df_all_modified, df_outliers
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def output_single_cluster_results(df_cluster, output_dir, output_prefix, snapshots_dir=None, swc_path = None): csv_file = output_dir + '/' + output_prefix + '.csv' df_cluster.to_csv(csv_file, index=False) ano_file = output_dir + '/' + output_prefix + '.ano' generateLinkerFileFromDF(df_cluster, ano_file, False, swc_path) # copy bmp vaa3d snapshots images over if (snapshots_dir): copySnapshots(df_cluster, snapshots_dir, output_dir + '/' + output_prefix) assemble_screenshots(output_dir + '/' + output_prefix, output_dir + '/' + output_prefix + '_assemble.png', 128) else: print "no bmp copying from:", snapshots_dir return
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def ward_cluster(df_all, feature_names, max_cluster_num, output_dir, snapshots_dir= None, RemoveOutliers = 0, datasetType='ivscc'): print("\n\n\n *************** ward computation, max_cluster = %d *************:" % max_cluster_num) if not os.path.exists(output_dir): os.mkdir(output_dir) else: os.system("rm -r " + output_dir + '/*') #### similarity plots # df_simMatrix = distance_matrix(df_all, feature_names, output_dir + "/morph_features_similarity_matrix.csv", 1) # # visualize heatmap using ward on similarity matrix # out = heatmap_plot_distancematrix(df_simMatrix, df_all, output_dir, "Similarity") # linkage = out.dendrogram_row.calculated_linkage ##### zscores featuer plots df_zscores, df_all_outlier_removed, df_outliers = get_zscore_features(df_all, feature_names, output_dir + '/zscore.csv', RemoveOutliers) if (df_outliers.shape[0] > 0 ): output_single_cluster_results(df_outliers, output_dir, "outliers", snapshots_dir) if datasetType =='ivscc': linkage = heatmap_plot_zscore_ivscc(df_zscores, df_all_outlier_removed, output_dir, "feature zscores") if datasetType =='bbp': linkage = heatmap_plot_zscore_bbp(df_zscores, df_all_outlier_removed, output_dir, "feature zscores") assignments = hierarchy.fcluster(linkage, max_cluster_num, criterion="maxclust") #hierarchy.dendrogram(linkage) ## put assignments into ano files and csv files clusters_list = output_clusters(assignments, df_zscores, df_all_outlier_removed, feature_names, output_dir, snapshots_dir) dunn_index = dunn(clusters_list) print("dunn index is %f" % dunn_index) return linkage,df_zscores
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def dunnindex_clusternumber(linkage,df_zscores, output_dir ="."): index_list=[] for n_clusters in range(2,30): assignments = hierarchy.fcluster(linkage, n_clusters, criterion="maxclust") df_assign_id = pd.DataFrame() df_assign_id['cluster_id'] = assignments clusters = np.unique(assignments) num_cluster = len(clusters) cluster_list = [] # for dunn index calculation df_cluster = pd.DataFrame() df_zscore_cluster = pd.DataFrame() for i in clusters: ids = np.nonzero(assignments == i)[0] # starting from 0 df_zscore_cluster = df_zscores.iloc[ids] cluster_list.append(df_zscore_cluster.values) dunn_index = dunn(cluster_list) index_list.append(dunn_index) pl.figure() pl.plot(range(2,30),index_list,"*-") pl.xlabel("cluster number") pl.ylabel("dunn index") pl.savefig(output_dir+'/dunnindex_clusternumber.pdf') #pl.show() return
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def run_ward_cluster(df_features, feature_names, num_clusters,output_dir,output_postfix): redundancy_removed_features_names = remove_correlated_features(df_features, feature_names, 0.95) print(" The %d features that are not closely correlated are %s" % ( len(redundancy_removed_features_names), redundancy_removed_features_names)) #num_clusters, dunn_index1 = affinity_propagation(merged, redundancy_removed_features_names, output_dir + '/ap' + postfix, swc_screenshot_folder, REMOVE_OUTLIERS) linkage, df_zscore = ward_cluster(df_features, redundancy_removed_features_names, num_clusters, output_dir + '/ward' + output_postfix) silhouette_clusternumber(linkage, df_zscore, output_dir + '/ward' + output_postfix) return redundancy_removed_features_names
XiaoxiaoLiu/morphology_analysis
[ 6, 1, 6, 1, 1447194203 ]
def add_arguments(self, parser): parser.add_argument('qid',type=int)
mcallaghan/tmv
[ 13, 8, 13, 30, 1476195091 ]
def __init__(self): super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill") # initialize your variables self.reload_skill = False self.active = True self.parser = None self.service = None self.TIMEOUT = 2
ElliotTheRobot/LILACS-mycroft-core
[ 4, 1, 4, 19, 1491303887 ]
def ping(self): while True: i = 0 if self.active: self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill", "utterances": [ "bump chat to active skill list"]})) while i < 60 * self.TIMEOUT: i += 1 sleep(1) i = 0
ElliotTheRobot/LILACS-mycroft-core
[ 4, 1, 4, 19, 1491303887 ]
def build_intents(self): # build intents deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \ .require("deactivateChatBotKeyword").build() activate_intent=IntentBuilder("ActivateChatbotIntent") \ .require("activateChatBotKeyword").build() bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \ require("bumpChatBotKeyword").build() # register intents self.register_intent(deactivate_intent, self.handle_deactivate_intent) self.register_intent(activate_intent, self.handle_activate_intent) self.register_intent(bump_intent, self.handle_set_on_top_active_list())
ElliotTheRobot/LILACS-mycroft-core
[ 4, 1, 4, 19, 1491303887 ]
def handle_deactivate_intent(self, message): self.active = False self.speak_dialog("chatbot_off")
ElliotTheRobot/LILACS-mycroft-core
[ 4, 1, 4, 19, 1491303887 ]
def stop(self): self.handle_deactivate_intent("global stop")
ElliotTheRobot/LILACS-mycroft-core
[ 4, 1, 4, 19, 1491303887 ]
def __init__(self, parent, modifications): self.modifications = modifications self.document_generated = False # Instead of calling wx.Dialog.__init__ we precreate the dialog # so we can set an extra style that must be set before # creation, and then we create the GUI object using the Create # method. pre = wx.PreDialog() pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP) pre.Create(parent, -1, "Génération de document") # This next step is the most important, it turns this Python # object into the real wrapper of the dialog (instead of pre) # as far as the wxPython extension is concerned. self.PostCreate(pre) self.sizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.StaticText(self, -1, "Format :"), 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) if not IsOODocument(modifications.template): self.format = wx.Choice(self, -1, choices=["Texte"]) elif sys.platform == 'win32': self.format = wx.Choice(self, -1, choices=["LibreOffice", "PDF"]) else: self.format = wx.Choice(self, -1, choices=["LibreOffice"]) self.format.SetSelection(0) self.Bind(wx.EVT_CHOICE, self.onFormat, self.format) sizer.Add(self.format, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5) default_output = normalize_filename(modifications.default_output) self.extension = os.path.splitext(default_output)[-1] wildcard = "OpenDocument (*%s)|*%s|PDF files (*.pdf)|*.pdf" % (self.extension, self.extension) self.fbb = wx.lib.filebrowsebutton.FileBrowseButton(self, -1, size=(600, -1), labelText="Nom de fichier :", startDirectory=config.documents_directory, initialValue=os.path.join(config.documents_directory, default_output), fileMask=wildcard, fileMode=wx.SAVE) sizer.Add(self.fbb, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5) self.sizer.Add(sizer, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.gauge = wx.Gauge(self, -1, size=(-1, 10)) self.gauge.SetRange(100) self.sizer.Add(self.gauge, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT | wx.TOP, 5) line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL) self.sizer.Add(line, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, 5) sizer = wx.BoxSizer(wx.HORIZONTAL) self.sauver_ouvrir = wx.Button(self, -1, "Sauver et ouvrir") self.sauver_ouvrir.SetDefault() self.Bind(wx.EVT_BUTTON, self.OnSauverOuvrir, self.sauver_ouvrir) sizer.Add(self.sauver_ouvrir, 0, wx.LEFT | wx.RIGHT, 5) self.sauver = wx.Button(self, -1, "Sauver") self.Bind(wx.EVT_BUTTON, self.OnSauver, self.sauver) sizer.Add(self.sauver, 0, wx.RIGHT, 5) if modifications.multi: button = wx.Button(self, -1, "Sauver individuellement") self.Bind(wx.EVT_BUTTON, self.OnSauverUnitaire, button) sizer.Add(button, 0, wx.RIGHT, 5) if modifications.email: self.sauver_envoyer = wx.Button(self, -1, "Sauver et envoyer par email") self.Bind(wx.EVT_BUTTON, self.OnSauverEnvoyer, self.sauver_envoyer) sizer.Add(self.sauver_envoyer, 0, wx.RIGHT, 5) if modifications.multi is False and not modifications.email_to: self.sauver_envoyer.Disable() if database.creche.caf_email: self.sauver_envoyer = wx.Button(self, -1, "Sauver et envoyer par email à la CAF") self.Bind(wx.EVT_BUTTON, self.OnSauverEnvoyerCAF, self.sauver_envoyer) sizer.Add(self.sauver_envoyer, 0, wx.LEFT | wx.RIGHT, 5) # btnsizer.Add(self.ok) btn = wx.Button(self, wx.ID_CANCEL) sizer.Add(btn, 0, wx.RIGHT, 5) self.sizer.Add(sizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.SetSizer(self.sizer) self.sizer.Fit(self) self.CenterOnScreen()
studio1247/gertrude
[ 14, 7, 14, 2, 1385708758 ]
def Sauver(self): self.fbb.Disable() self.sauver.Disable() if self.sauver_ouvrir: self.sauver_ouvrir.Disable() self.filename = self.fbb.GetValue() f, e = os.path.splitext(self.filename) if e == ".pdf": self.pdf = True self.oo_filename = f + self.extension else: self.pdf = False self.oo_filename = self.filename config.documents_directory = os.path.dirname(self.filename) dlg = None try: if self.modifications.multi is not False: errors = {} simple_modifications = self.modifications.get_simple_modifications(self.oo_filename) for i, (filename, modifs) in enumerate(simple_modifications): self.gauge.SetValue((100 * i) / len(simple_modifications)) errors.update(GenerateDocument(modifs, filename=filename)) if self.pdf: f, e = os.path.splitext(filename) convert_to_pdf(filename, f + ".pdf") os.remove(filename) else: self.filename = self.filename.replace(" <prenom> <nom>", "") self.oo_filename = self.oo_filename.replace(" <prenom> <nom>", "") errors = GenerateDocument(self.modifications, filename=self.oo_filename, gauge=self.gauge) if self.pdf: convert_to_pdf(self.oo_filename, self.filename) os.remove(self.oo_filename) self.document_generated = True if errors: message = "Document %s généré avec des erreurs :\n" % self.filename for label in errors.keys(): message += '\n' + label + ' :\n ' message += '\n '.join(errors[label]) dlg = wx.MessageDialog(self, message, 'Message', wx.OK | wx.ICON_WARNING) except IOError: print(sys.exc_info()) dlg = wx.MessageDialog(self, "Impossible de sauver le document. Peut-être est-il déjà ouvert ?", 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() return except Exception as e: info = sys.exc_info() message = ' [type: %s value: %s traceback: %s]' % (info[0], info[1], traceback.extract_tb(info[2])) dlg = wx.MessageDialog(self, message, 'Erreur', wx.OK | wx.ICON_WARNING) if dlg: dlg.ShowModal() dlg.Destroy() self.EndModal(wx.ID_OK)
studio1247/gertrude
[ 14, 7, 14, 2, 1385708758 ]
def OnSauverOuvrir(self, event): self.OnSauver(event) if self.document_generated: if self.filename.endswith(".pdf"): StartAcrobatReader(self.filename) else: StartLibreOffice(self.filename)
studio1247/gertrude
[ 14, 7, 14, 2, 1385708758 ]
def OnSauverEnvoyer(self, event): self.OnSauverUnitaire(event) if self.document_generated: if self.modifications.multi is not False: simple_modifications = self.modifications.get_simple_modifications(self.oo_filename) emails = '\n'.join( [" - %s (%s)" % (modifs.email_subject, ", ".join(modifs.email_to)) for filename, modifs in simple_modifications]) if len(emails) > 1000: emails = emails[:1000] + "\n..." dlg = wx.MessageDialog(self, "Ces emails seront envoyés :\n" + emails, 'Confirmation', wx.OK | wx.CANCEL | wx.ICON_WARNING) response = dlg.ShowModal() dlg.Destroy() if response != wx.ID_OK: return for filename, modifs in simple_modifications: if self.pdf: oo_filename = filename filename, e = os.path.splitext(oo_filename) filename += ".pdf" try: SendDocument(filename, modifs) except Exception as e: dlg = wx.MessageDialog(self, "Impossible d'envoyer le document %s\n%r" % (filename, e), 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() else: try: SendDocument(self.filename, self.modifications) except Exception as e: dlg = wx.MessageDialog(self, "Impossible d'envoyer le document %s\n%r" % (self.filename, e), 'Erreur', wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy()
studio1247/gertrude
[ 14, 7, 14, 2, 1385708758 ]
def StartLibreOffice(filename): if sys.platform == 'win32': filename = "".join(["file:", urllib.pathname2url(os.path.abspath(filename.encode("utf-8")))]) # print filename try: StarDesktop, objServiceManager, core_reflection = getOOoContext() StarDesktop.LoadComponentFromURL(filename, "_blank", 0, MakePropertyValues(objServiceManager, [ ["ReadOnly", False], ["Hidden", False]])) except Exception as e: print("Exception ouverture LibreOffice", e) dlg = wx.MessageDialog(None, "Impossible d'ouvrir le document\n%r" % e, "Erreur", wx.OK|wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() else: paths = [] if sys.platform == "darwin": paths.append("/Applications/LibreOffice.app/Contents/MacOS/soffice") paths.append("/Applications/OpenOffice.app/Contents/MacOS/soffice") else: paths.append("/usr/bin/libreoffice") paths.append("ooffice") for path in paths: try: print(path, filename) subprocess.Popen([path, filename]) return except Exception as e: print(e) pass dlg = wx.MessageDialog(None, "Impossible de lancer OpenOffice / LibreOffice", 'Erreur', wx.OK|wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy()
studio1247/gertrude
[ 14, 7, 14, 2, 1385708758 ]
def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.")
dotancohen/burton
[ 1, 1, 1, 16, 1372155757 ]
def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True
dotancohen/burton
[ 1, 1, 1, 16, 1372155757 ]
def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func
psy0rz/zfs_autobackup
[ 387, 49, 387, 18, 1446023195 ]
def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {}
psy0rz/zfs_autobackup
[ 387, 49, 387, 18, 1446023195 ]
def __init__(self, data_override=None): self.cfg = configparser.ConfigParser() self.datapath = data_override self.logpath = None self.dbpath = None self.sessionspath = None print("Created a new gcfg...")
btxgit/gazee
[ 1, 2, 1, 1, 1506935060 ]
def create_init_dirs(self, data_dir): ''' Sets up the data_dir plus the two paths that aren't configurable, and are relative to the data_dir - the log_dir and db_dir '''
btxgit/gazee
[ 1, 2, 1, 1, 1506935060 ]
def find_config(self): ''' Looks for where the data dir is located. Once it finds the dir, it calls create_ ''' dirfound = None firstdir = None cfgfound = None
btxgit/gazee
[ 1, 2, 1, 1, 1506935060 ]
def configWrite(self): ''' Write self.cfg to disk ''' with open(self.cfgpath, 'w') as configfile: self.cfg.write(configfile) return True
btxgit/gazee
[ 1, 2, 1, 1, 1506935060 ]
def get_yn(self, msg): while True: v = input(msg) if v.lower() in ['y', 'n']: break print("\nInvalid response. Enter 'y' or 'n'.") return v.lower() == 'y'
btxgit/gazee
[ 1, 2, 1, 1, 1506935060 ]
def configRead(self): ''' Read the app.ini config file. '''
btxgit/gazee
[ 1, 2, 1, 1, 1506935060 ]
def p1(): p1 = Polygon([Point('A', 0.5, 0.5), Point('B', 3, 1), Point('C', 3.2, 4), Point('D', 0.8, 3) ]) p1.side[0].label = Value(4, unit='cm') p1.side[1].label = Value(3, unit='cm') p1.side[2].label = Value(2, unit='cm') p1.side[3].label = Value(6.5, unit='cm') p1.angle[0].label = Value(64, unit="\\textdegree") p1.angle[1].label = Value(128, unit="\\textdegree") p1.angle[2].label = Value(32, unit="\\textdegree") p1.angle[3].label = Value(256, unit="\\textdegree") p1.angle[0].mark = 'simple' p1.angle[1].mark = 'simple' p1.angle[2].mark = 'simple' p1.angle[3].mark = 'simple' return p1
nicolashainaux/mathmaker
[ 4, 1, 4, 34, 1468416792 ]
def test_p1_rename_errors(p1): """Check wrong arguments trigger exceptions when renaming.""" with pytest.raises(TypeError): p1.rename(5678) with pytest.raises(ValueError): p1.rename('KJLIZ')
nicolashainaux/mathmaker
[ 4, 1, 4, 34, 1468416792 ]
def __str__(cls): return "Median Filter"
efce/voltPy
[ 1, 1, 1, 14, 1500044176 ]
def __perform(self, dataset): for cd in dataset.curves_data.all(): yvec = cd.yVector newyvec = medfilt(yvec) dataset.updateCurve(self.model, cd, newyvec) dataset.save()
efce/voltPy
[ 1, 1, 1, 14, 1500044176 ]
def errorExit(msg): print(msg) sys.exit(1)
DeadSix27/python_cross_compile_script
[ 30, 11, 30, 8, 1490050084 ]
def version_str(args): return str(args.major) + "." + str(args.minor) + "." + str(args.maintenance)
morinim/vita
[ 29, 6, 29, 12, 1448976139 ]
def changelog_rule(data, args): new_version = version_str(args) regex = r"## \[Unreleased\]" subst = r"## [Unreleased]\n\n## [" + new_version + r"] - " + datetime.date.today().isoformat() result = re.subn(regex, subst, data) if result[1] != 1: return None regex = r"(\[Unreleased)(\]: https://github.com/morinim/vita/compare/v)(.+)(\.\.\.HEAD)" subst = r"\g<1>\g<2>" + new_version + r"\g<4>\n[" + new_version + r"\g<2>\g<3>...v" + new_version result = re.subn(regex, subst, result[0]) return result[0] if result[1] == 1 else None
morinim/vita
[ 29, 6, 29, 12, 1448976139 ]
def get_cmd_line_options(): description = "Helps to set up a new version of Vita" parser = argparse.ArgumentParser(description = description) parser.add_argument("-v", "--verbose", action = "store_true", help = "Turn on verbose mode") # Now the positional arguments. parser.add_argument("major", type=int) parser.add_argument("minor", type=int) parser.add_argument("maintenance", type=int) return parser
morinim/vita
[ 29, 6, 29, 12, 1448976139 ]
def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]
def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]
def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]
def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]
def __init__(self, destination): self.destination = destination
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]
def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]
def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list
digidotcom/transport_examples
[ 6, 12, 6, 2, 1448060105 ]