code stringlengths 1 18.2k |
|---|
def _resolve_command(self, command, target): """Get the correct event for the command Only for 'privmsg' and 'notice' commands. :param command: The command string :type command: :class:`str` :param target: either a user or a channel :type target: :class:`str` :returns: the correct event type :rtype: :class:`str` :raise... |
def _handle_message(self, tags, source, command, target, msg): """Construct the correct events and handle them :param tags: the tags of the message :type tags: :class:`list` of :class:`message.Tag` :param source: the sender of the message :type source: :class:`str` :param command: the event type :type command: :class:`... |
%s, command: %s, source: %s, target: %s, " "arguments: %s", tags, command, source, target, [msg]) event = Event3(command, source, target, [msg], tags=tags) self._handle_event(event) |
def _process_tags(self, tags): """Process the tags of the message :param tags: the tags string of a message :type tags: :class:`str` | None :returns: list of tags :rtype: :class:`list` of :class:`message.Tag` :raises: None """ if not tags: return [] return [message.Tag.from_str(x) for x in tags.split(';')] |
def _process_arguments(self, arguments): """Process the arguments :param arguments: arguments string of a message :type arguments: :class:`str` | None :returns: A list of arguments :rtype: :class:`list` of :class:`str` | None :raises: None """ if not arguments: return None a = arguments.split(" :", 1) arglist = a[0].sp... |
def build_mongo_doc(self, key_list): """ Creates the components of aggregation pipeline :param key_list: list of key which will be used to create the components of aggregation pipeline :type key_list: list :returns mongo_doc: dict """ mongo_doc = {} if isinstance(key_list, list) and key_list: for key in key_list: mongo... |
def build_pipeline(self, collection): """ Creates aggregation pipeline for aggregation :param collection: Mongo collection for aggregation :type collection: MongoCollection :return pipeline: list of dicts """ pipeline = [] if isinstance(collection.where_dict, dict) and collection.where_dict: match_dict = { "$match": co... |
def fetch_and_process_data(self, collection, pipeline): """ Fetches and Processess data from the input collection by aggregating using the pipeline :param collection: The collection object for which mongo connection has to be made :type collection: MongoCollection :param pipeline: The pipeline using which aggregation w... |
def get_collections_data(self): """ Driver function to fetch the data from the two collections """ collections = { 'left': self.left_collection, 'right': self.right_collection } for collection_type, collection in collections.iteritems(): pipeline = self.build_pipeline(collection) self.collections_data[collection_type] ... |
def parse_duration(string): """ Parse human readable duration. >>> parse_duration('1m') 60 >>> parse_duration('7 days') == 7 * 24 * 60 * 60 True """ if string.isdigit(): return int(string) try: return float(string) except ValueError: pass string = string.rstrip() for (suf, mult) in DURATION_SUFFIX_MAP.items(): if strin... |
def create_session(): """ shell = CommandShell('http://192.168.145.132:5985/wsman', 'Administrator', 'Pa55w0rd') """ shell = CommandShell('http://192.168.137.238:5985/wsman', 'Administrator', 'Pa55w0rd') shell.open() command_id = shell.run('ipconfig', ['/all']) (stdout, stderr, exit_code) = shell.receive(command_id) sy... |
def fake_chars_or_choice(self, field_name): """ Return fake chars or choice it if the `field_name` has choices. Then, returning random value from it. This specially for `CharField`. Usage: faker.fake_chars_or_choice('field_name') Example for field: TYPE_CHOICES = ( ('project', 'I wanna to talk about project'), ('feedba... |
def fake_decimal(self, field_name): """ Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number. Usage: faker.fake_decimal('field_name') Example: 10.7, 13041.00, 200.000.000 """ return self.djipsum_fields().randomDecimalField( self.model_class(), field_name=field_name ) |
def fake_fk(self, field_name): """ Return related random object to set as ForeignKey. Example Output: <User: username> """ return self.djipsum_fields().getOrCreateForeignKey( model_class=self.model_class(), field_name=field_name ) |
def fake_m2m(self, obj, field_name): """ Return the random objects from m2m relationship. The ManyToManyField need specific object, so i handle it after created the object. """ instance_m2m = getattr(obj, field_name) objects_m2m = instance_m2m.model.objects.all() if objects_m2m.exists(): ids_m2m = [i.pk for i in object... |
def create(self, fields): """ Create the object only once. So, you need loop to usage. :param `fields` is dictionary fields. """ try: # Cleaning the fields, and check if has `ForeignKey` type. cleaned_fields = {} for key, value in fields.items(): if type(value) is dict: try: if value['type'] == 'fk': fake_fk = self.fak... |
def trading_dates(start, end, calendar='US'): """ Trading dates for given exchange Args: start: start date end: end date calendar: exchange as string Returns: pd.DatetimeIndex: datetime index Examples: >>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-27'] >>> trd_dates = trading_dates(start='2018-12-23', end='2018... |
def get_logger( name_or_func, log_file='', level=logging.INFO, types='stream', **kwargs ): """ Generate logger Args: name_or_func: logger name or current running function log_file: logger file level: level of logs - debug, info, error types: file or stream, or both Returns: logger Examples: >>> get_logger(name_or_func=... |
def set_password(self, raw_password): """Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user. If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`. """ if raw_password is None: self.set_unusable_password() else: xmpp_backend.set_password(self.nod... |
def check_password(self, raw_password): """Calls :py:func:`~xmpp_backends.base.XmppBackendBase.check_password` for the user.""" return xmpp_backend.check_password(self.node, self.domain, raw_password) |
def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json() |
def get_client_data(self, client): """ Returns a client. """ data = self._request('GET', '/clients/{}'.format(client)) return data.json() |
def get_client_history(self, client): """ Returns the history for a client. """ data = self._request('GET', '/clients/{}/history'.format(client)) return data.json() |
def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json() |
def get_event(self, client, check): """ Returns an event for a given client & check name. """ data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json() |
def delete_event(self, client, check): """ Resolves an event for a given check on a given client. (delayed action) """ self._request('DELETE', '/events/{}/{}'.format(client, check)) return True |
def post_event(self, client, check): """ Resolves an event. (delayed action) """ self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True |
def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json() |
def post_check_request(self, check, subscribers): """ Issues a check execution request. """ data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True |
def post_silence_request(self, kwargs): """ Create a silence entry. """ self._request('POST', '/silenced', data=json.dumps(kwargs)) return True |
def clear_silence(self, kwargs): """ Clear a silence entry. """ self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True |
def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json() |
def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False |
def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json() |
def get_result(self, client, check): """ Returns an event for a given client & result name. """ data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json() |
def delete_result(self, client, check): """ Deletes an check result data for a given check on a given client. """ self._request('DELETE', '/results/{}/{}'.format(client, check)) return True |
def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True |
def create_stash(self, payload, path=None): """ Create a stash. (JSON document) """ if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True |
def get_subscriptions(self, nodes=[]): """ Returns all the channels where (optionally specified) nodes are subscribed """ if len(nodes) > 0: data = [node for node in self.get_clients() if node['name'] in nodes] else: data = self.get_clients() channels = [] for client in data: if 'subscriptions' in client: if isinstance... |
def get_subscriptions_channel(self, search_channel): """ Return all the nodes that are subscribed to the specified channel """ data = self.get_clients() clients = [] for client in data: if 'subscriptions' in client: if isinstance(client['subscriptions'], list): if search_channel in client['subscriptions']: clients.appe... |
def build_extension(self, ext): """ build clrmagic.dll using csc or mcs """ if sys.platform == "win32": _clr_compiler = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe" else: _clr_compiler = "mcs" cmd = [ _clr_compiler, "/target:library", "clrmagic.cs" ] check_call(" ".join(cmd), shell=True) |
def wait_for_event(self, event, timeout=10): """ Block waiting for the given event. Returns the event params. :param event: The event to handle. :return: The event params. :param timeout: The maximum time to wait before raising :exc:`.TimeoutError`. """ return self.__handler.wait_for_event(event, timeout=timeout) |
def search_greater(values, target): """ Return the first index for which target is greater or equal to the first item of the tuple found in values """ first = 0 last = len(values) while first < last: middle = (first + last) // 2 if values[middle][0] < target: first = middle + 1 else: last = middle return first |
def add(self, value): """ Add a value to the reservoir The value will be casted to a floating-point, so a TypeError or a ValueError may be raised. """ if not isinstance(value, float): value = float(value) return self._do_add(value) |
def same_kind(self, other): """ Return True if "other" is an object of the same type and it was instantiated with the same parameters """ return type(self) is type(other) and self._same_parameters(other) |
def _lookup(self, timestamp): """ Return the index of the value associated with "timestamp" if any, else None. Since the timestamps are floating-point values, they are considered equal if their absolute difference is smaller than self.EPSILON """ idx = search_greater(self._values, timestamp) if (idx < len(self._values)... |
def _put(self, timestamp, value): """Replace the value associated with "timestamp" or add the new value""" idx = self._lookup(timestamp) if idx is not None: self._values[idx] = (timestamp, value) else: self._values.append((timestamp, value)) |
def get(self): """Return the computed statistics over the gathered data""" values = self.reservoir.sorted_values def safe(f, *args): try: return f(values, *args) except exceptions.StatisticsError: return 0.0 plevels = [50, 75, 90, 95, 99, 99.9] percentiles = [safe(statistics.percentile, p) for p in plevels] try: histog... |
def reload_glance(self, target_app, slices=None): """ Reloads an app's glance. Blocks as long as necessary. :param target_app: The UUID of the app for which to reload its glance. :type target_app: ~uuid.UUID :param slices: The slices with which to reload the app's glance. :type slices: list[.AppGlanceSlice] """ glance ... |
def network_sketch(ax, highlight=None, labels=True, yscaling=1.): ''' highlight : None or string if string, then only the label of this population is set and the box is highlighted ''' name_to_id_mapping={'L6E':(0,0), 'L6I':(0,1), 'L5E':(1,0), 'L5I':(1,1), 'L4E':(2,0), 'L4I':(2,1), 'L23E':(3,0), 'L23I':(3,1) } showgrid... |
thalamo-cortical synapses (relative to cortex population) exc_clr = 'k' if analysis_params.bw else analysis_params.colorE ## color of excitatory axons/synapses inh_clr = 'gray' if analysis_params.bw else analysis_params.colorI ## color of inhibitory axons/synapses lw_pop=0.5 ## linewidth for populations lw_axons=0.4 ##... |
position.''' ax.text(xy[0],xy[1],txt,fontdict=fontdict,color=clr,zorder=zorder) def draw_line(ax,path,lw=1.,ls='solid',lclr='k',zorder=0): '''Draws a path.''' #pth = path.Path(np.array(path)) pth = Path(np.array(path)) patch = patches.PathPatch(pth, fill=False, lw=lw,ls=ls,ec=lclr,fc=lclr,zorder=zorder) ax.add_patch(pa... |
c_center_x=layer_x+layer_width/2. ## x position of cortex center t_pos=[c_center_x-t_pop_size/2.,t_pop_y*yscaling,t_pop_size,t_pop_size] ## thalamus position #draw_box(ax,t_pos,lw=lw_pop,eclr='k',fclr='w',zorder=2) ## Th draw_box(ax,t_pos,lw=lw_pop,eclr='k',fclr='k',zorder=2, boxstyle=patches.BoxStyle("Round", pad=0.02... |
[c_pop_pos[i][0][0]+c_pop_size/2.,c_pop_pos[i][0][1]-axon_y_dist], [c_axon_x[i][0],c_pop_pos[i][0][1]-axon_y_dist]] draw_line(ax,path,lw=lw_axons,ls='solid',lclr=exc_clr,zorder=1) ## excitatory draw_circle(ax,path[-1],conn_radius,lw=0,fclr=exc_clr,zorder=0) ## connector path=[[c_pop_pos[i][1][0]+c_pop_size/2.,c_pop_pos... |
right vertical branch path=[[c_pop_pos[0][0][0]-(axon_cell_sep+axon_y_dist),c_pop_pos[2][0][1]+tc_input_y*c_pop_size], [c_pop_pos[0][0][0],c_pop_pos[2][0][1]+tc_input_y*c_pop_size],] draw_arrow(ax,path,lw=lw_axons,ls='solid',lclr=exc_clr,arrow_size=arrow_size,zorder=1) ## Th -> L4E synapses (arrows) draw_circle(ax,path... |
name_to_id_mapping[highlight] fontdict1['fontsize']=4 put_text(ax,[c_pop_pos[ids[0]][ids[1]][0]+c_pop_size/2.,c_pop_pos[ids[0]][ids[1]][1]+c_pop_size/2.],highlight,'k',fontdict1) ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) ax.axis(ax.axis('equal')) return ax |
def plot_population(ax, params, aspect='tight', isometricangle=0, plot_somas = True, plot_morphos = False, num_unitsE = 1, num_unitsI=1, clip_dendrites=False, main_pops=True, Y = None, big=True, title='cell positions', rasterized=True): ''' Plot the geometry of the column model, optionally with somatic locations and op... |
bool if False: leave out labels and reduce marker size return: :: axis : list the plt.axis() corresponding to input aspect ''' name_to_id_mapping={'L6E':(3,0), 'L6I':(3,1), 'L5E':(2,0), 'L5I':(2,1), 'L4E':(1,0), 'L4I':(1,1), 'L23E':(0,0), 'L23I':(0,1) } # DRAW OUTLINE OF POPULATIONS ax.xaxis.set_ticks([]) ax.yaxis.set_... |
if big: ax.text(r, z, ' %s' % layers[i], va='center', ha='left') for i, zval in enumerate(zpos): if i == 0: ax.plot(r*np.cos(theta0), r*np.sin(theta0)*np.sin(isometricangle)+zval, color='k', zorder=-r, clip_on=False) ax.plot(r*np.cos(theta1), r*np.sin(theta1)*np.sin(isometricangle)+zval, color='k', zorder=r, clip_on=Fa... |
zorder for each datapoint by binning pitch = 100 for lower in np.arange(-600, 601, pitch): upper = lower + pitch inds = (somapos[:, 1] >= lower) & (somapos[:, 1] < upper) if np.any(inds): if big: ax.scatter(somapos[inds, 0], somapos[inds, 2] - somapos[inds, 1] * np.sin(isometricangle), s=10, facecolors=colors[i], edgec... |
for i, pops in enumerate(pops_): layer = np.unique(pop)[i] if layer.rfind('p') >= 0 or layer.rfind('E') >= 0: marker = '^' elif layer.rfind('b') >= 0 or layer.rfind('I') >= 0: marker = '*' elif layer.rfind('ss') >= 0: marker = 'o' else: raise Exception #get the somapos somapos = [] for j, lname in enumerate(pops): fnam... |
elif layer.rfind('ss') >= 0: marker = 'x' else: raise Exception #get the somapos fname = glob.glob(os.path.join(params.populations_path, '%s*somapos.gdf' % layer))[0] somapos = np.loadtxt(fname).reshape((-1, 3)) plot_pop_scatter(somapos, marker, colors, i) i += 1 #plot morphologies in their appropriate locations if plo... |
if num_units > somapos.shape[0]: n = somapos.shape[0] else: n = num_units #find some morphos for this population: morphos = [] for fname in params.m_y: if fname.rfind(layer) >= 0: morphos.append(fname) #plot some units for j in range(n): cell = LFPy.Cell(morphology=os.path.join(params.PATH_m_y, np.random.permutation(mo... |
>= 0: num_units = num_unitsE else: num_units = num_unitsI if num_units > somapos.shape[0]: n = somapos.shape[0] else: n = num_units #plot some units for j in range(n): cell = LFPy.Cell(morphology=os.path.join(params.PATH_m_y, morpho), nsegs_method='lambda_f', lambda_f=10, extracellular=False ) cell.set_pos(somapos[j, 0... |
def plot_signal_sum(ax, params, fname='LFPsum.h5', unit='mV', scaling_factor=1., ylabels=True, scalebar=True, vlimround=None, T=[800, 1000], ylim=[-1500, 0], color='k', fancy=False, label='', transient=200, clip_on=False, rasterized=True, **kwargs): ''' on axes plot the summed LFP contributions args: :: ax : matplotlib... |
to ax.plot() returns: :: vlimround : float, scalebar scaling factor, i.e., to match up plots ''' if type(fname) == str and os.path.isfile(fname): f = h5py.File(fname) #load data data = f['data'].value tvec = np.arange(data.shape[1]) * 1000. / f['srate'].value #for mean subtraction datameanaxis1 = f['data'].value[:, tve... |
is None: vlimround = 2.**np.round(np.log2(vlim)) else: pass yticklabels=[] yticks = [] if fancy: colors=phlp.get_colors(data.shape[0]) else: colors = [color]*data.shape[0] for i, z in enumerate(params.electrodeParams['z']): if i == 0: ax.plot(tvec[slica], data[i] * 100 / vlimround + z, color=colors[i], rasterized=raste... |
def plotConnectivity(ax): '''make an imshow of the intranetwork connectivity''' im = ax.pcolor(params.C_YX, cmap='hot') ax.axis(ax.axis('tight')) ax.invert_yaxis() ax.xaxis.set_ticks_position('top') ax.set_xticks(np.arange(9)+0.5) ax.set_yticks(np.arange(8)+0.5) ax.set_xticklabels(params.X, rotation=270) ax.set_ytickla... |
def getMeanInpCurrents(params, numunits=100, filepattern=os.path.join('simulation_output_default', 'population_input_spikes*')): '''return a dict with the per population mean and std synaptic current, averaging over numcells recorded units from each population in the network Returned currents are in unit of nA. ''' #co... |
else: numcells = numunits units = units[:numcells] #churn through data and extract the input currents per cell for j, unit in enumerate(units): slc = rawdata[:, 0] == unit #just the spikes: if j == 0: dataslc = rawdata[slc, 2:] else: dataslc = np.r_['0,3', dataslc, rawdata[slc, 2:]] #fix the datatype, it may be object ... |
def getMeanVoltages(params, numunits=100, filepattern=os.path.join('simulation_output_default', 'voltages')): '''return a dict with the per population mean and std synaptic current, averaging over numcells recorded units from each population in the network Returned currents are in unit of nA. ''' data = {} #loop over n... |
dataslc, rawdata[slc, 2:]] #fix the datatype, it may be object dataslc = dataslc.astype(float) #fill in data-structure data.update({ Y : { 'data' : dataslc[:, :, 0].mean(axis=0), 'std' : dataslc[:, :, 0].std(axis=0), 'sample' : dataslc[0, :, 0], 'tvec' : rawdata[slc, 1], 'numunits' : numunits, } }) data = COMM.allgathe... |
def plot_signal_sum_colorplot(ax, params, fname='LFPsum.h5', unit='mV', N=1, ylabels = True, T=[800, 1000], ylim=[-1500, 0], fancy=False, colorbar=True, cmap='spectral_r', absmax=None, transient=200, rasterized=True): ''' on colorplot and as background plot the summed CSD contributions args: :: ax : matplotlib.axes.Axe... |
normalize data = data/N zvec = params.electrodeParams['z'] if fancy: colors = phlp.get_colors(data.shape[0]) else: colors = ['k']*data.shape[0] if absmax == None: absmax=abs(np.array([data.max(), data.min()])).max() im = ax.pcolormesh(tvec[slica], np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] + 50, data, rasterized=rasteri... |
def calc_signal_power(params, fname, transient=200, Df=None, mlab=True, NFFT=1000, noverlap=0, window=plt.mlab.window_hanning): ''' calculates power spectrum of sum signal for all channels ''' if type(fname) is str and os.path.isfile(fname): #open file f = h5py.File(fname) data = f['data'].value srate = f['srate'].valu... |
= Pxx[mask] Pxx = Pxx/tvec[tvec >= transient].size**2 PSD +=[Pxx.flatten()] PSD=np.array(PSD) return freqs, PSD |
def plot_signal_power_colorplot(ax, params, fname, transient=200, Df=None, mlab=True, NFFT=1000, window=plt.mlab.window_hanning, noverlap=0, cmap = plt.cm.get_cmap('jet', 21), vmin=None, vmax=None): ''' on axes plot the LFP power spectral density The whole signal duration is used. args: :: ax : matplotlib.axes.AxesSubp... |
def plotPowers(ax, params, popkeys, dataset, linestyles, linewidths, transient=200, SCALING_POSTFIX='', markerstyles=None): '''plot power (variance) as function of depth for total and separate contributors Plot variance of sum signal ''' colors = phlp.get_colors(len(popkeys)) depth = params.electrodeParams['z'] zpos = ... |
def plotting_correlation(params, x0, x1, ax, lag=20., scaling=None, normalize=True, color='k', unit=r'$cc=%.3f$' , title='firing_rate vs LFP', scalebar=True, **kwargs): ''' mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - the LFP usually here ax : matplotlib.axes.Axes... |
== 1: x2 = x1[i, ] xcorr1 = np.correlate(x0,x2, 'same') elif x0.ndim == 2: xcorr1 = np.correlate(x0[i, ],x1[i, ], 'same') xcorr_all[i,:]=xcorr1 # Find limits for the plot if scaling is None: vlim = abs(xcorr_all).max() vlimround = 2.**np.round(np.log2(vlim)) else: vlimround = scaling yticklabels=[] yticks = [] #tempora... |
return xcorr_all[:, inds[::-1]], vlimround |
def do_GET(self, ): """Handle GET requests If the path is '/', a site which extracts the token will be generated. This will redirect the user to the '/sucess' page, which shows a success message. :returns: None :rtype: None :raises: None """ urld = {self.extract_site_url: 'extract_token_site.html', self.success_site_ur... |
def _write_html(self, filename): """Read the html site with the given filename from the data directory and write it to :data:`RedirectHandler.wfile`. :param filename: the filename to read :type filename: :class:`str` :returns: None :rtype: None :raises: None """ datapath = os.path.join('html', filename) sitepath = pkg_... |
def do_POST(self, ): """Handle POST requests When the user is redirected, this handler will respond with a website which will send a post request with the url fragment as parameters. This will get the parameters and store the original redirection url and fragments in :data:`LoginServer.tokenurl`. :returns: None :rtype:... |
def set_token(self, redirecturl): """Set the token on the session :param redirecturl: the original full redirect url :type redirecturl: :class:`str` :returns: None :rtype: None :raises: None """ log.debug('Setting the token on %s.' % self.session) self.session.token_from_fragment(redirecturl) |
def _add_bearer_token(self, *args, **kwargs): """Add a bearer token to the request uri, body or authorization header. This is overwritten to change the headers slightly. """ s = super(TwitchOAuthClient, self) uri, headers, body = s._add_bearer_token(*args, **kwargs) authheader = headers.get('Authorization') if authhead... |
def install_template(username, repo): """Installs a Blended template from GitHub""" print("Installing template from " + username + "/" + repo) dpath = os.path.join(cwd, "templates") getunzipped(username, repo, dpath) |
def import_wp(filepath): """Imports A WordPress export and converts it to a Blended site""" print("\nBlended: Static Website Generator -\n") checkConfig() print("Importing from WordPress...") wp = parseXML(filepath) wname = wp.rss.channel.title.cdata wdesc = wp.rss.channel.description.cdata wlan = wp.rss.channel.langua... |
def import_blogger(filepath): """Imports A Blogger export and converts it to a Blended site""" print("\nBlended: Static Website Generator -\n") checkConfig() print("Importing from Blogger...") blogger = parseXML(filepath) wname = blogger.feed.title.cdata aname = blogger.feed.author.name.cdata.strip() createBlendedFolde... |
def install_plugin(username, repo): """Installs a Blended plugin from GitHub""" print("Installing plugin from " + username + "/" + repo) pip.main(['install', '-U', "git+git://github.com/" + username + "/" + repo + ".git"]) |
def init(): """Initiates a new website""" print("Blended: Static Website Generator -\n") checkConfig() if (sys.version_info > (3, 0)): wname = input("Website Name: ") wdesc = input("Website Description: ") wlan = input("Website Language: ") wlic = input("Website License: ") aname = input("Author(s) Name(s): ") else: wn... |
def placeFiles(ftp, path): """Upload the built files to FTP""" for name in os.listdir(path): if name != "config.py" and name != "config.pyc" and name != "templates" and name != "content": localpath = os.path.join(path, name) if os.path.isfile(localpath): print("STOR", name, localpath) ftp.storbinary('STOR ' + name, ope... |
def send_ftp(outdir): """Upload the built website to FTP""" print("Uploading the files in the " + outdir + "/ directory!\n") # Make sure there is actually a configuration file config_file_dir = os.path.join(cwd, "config.py") if not os.path.exists(config_file_dir): sys.exit( "There dosen't seem to be a configuration fil... |
def clean_built(outdir): """Removes all built files""" print("Removing the built files!") # Remove the build folder build_dir = os.path.join(cwd, outdir) if os.path.exists(build_dir): shutil.rmtree(build_dir) |
def zip_built(outdir): """Packages the build folder into a zip""" print("Zipping the built files!") config_file_dir = os.path.join(cwd, "config.py") if not os.path.exists(config_file_dir): sys.exit( "There dosen't seem to be a configuration file. Have you run the init command?") else: sys.path.insert(0, cwd) try: from ... |
def purge(): """Removes all files generated by Blended""" print("Purging the Blended files!") # Remove the templates folder templ_dir = os.path.join(cwd, "templates") if os.path.exists(templ_dir): shutil.rmtree(templ_dir) # Remove the content folder cont_dir = os.path.join(cwd, "content") if os.path.exists(cont_dir): s... |
def convert_text(filename): """Convert the post/page content using the converters""" text_content = open(filename, "r") if ".md" in filename: text_cont1 = "\n" + markdown.markdown(text_content.read()) + "\n" elif ".docx" in filename: with open(os.path.join(cwd, "content", filename), "rb") as docx_file: result = mammoth... |
def build_files(outdir): """Build the files!""" # Make sure there is actually a configuration file config_file_dir = os.path.join(cwd, "config.py") if not os.path.exists(config_file_dir): sys.exit( "There dosen't seem to be a configuration file. Have you run the init command?") else: sys.path.insert(0, cwd) try: from c... |
old. Run 'blended init' to fix.\n") # Create the build folder build_dir = os.path.join(cwd, outdir) if "." not in outdir and ".." not in outdir and "..." not in outdir and "...." not in outdir and "....." not in outdir: replace_folder(build_dir) # Make sure there is actually a header template file header_file_dir = os.... |
page listing page_list_item_file = os.path.join(cwd, "templates", "page_list_item.html") if not os.path.exists(page_list_item_file): page_list = '<ul class="page-list">\n' for root, dirs, files in os.walk(os.path.join(cwd, "content")): for filename in files: top = os.path.dirname(os.path.join(root, filename)) top2 = to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.