Import connectivity rules from Excel sheet
7319
def importConnFromExcel (fileName, sheetName):
    ''' '''
    import openpyxl as xl

    # set columns
    colPreTags = 0 # 'A'
    colPostTags = 1 # 'B'
    colConnFunc = 2 # 'C'
    colSyn = 3 # 'D'
    colProb = 5 # 'F'
    colWeight = 6 # 'G'
    colAnnot = 8 # 'I' 

    outFileName = fileName[:-5]+'_'+sheetName+'.py' # set output file name

    connText = """## Generated using importConnFromExcel() function in params/utils.py \n\nnetParams['connParams'] = [] \n\n"""
    
    # open excel file and sheet
    wb = xl.load_workbook(fileName)
    sheet = wb.get_sheet_by_name(sheetName)
    numRows = sheet.get_highest_row()

    with open(outFileName, 'w') as f:
        f.write(connText)  # write starting text
        for row in range(1,numRows+1):
            if sheet.cell(row=row, column=colProb).value:  # if not empty row
                print('Creating conn rule for row ' + str(row))
                # read row values
                pre = sheet.cell(row=row, column=colPreTags).value
                post = sheet.cell(row=row, column=colPostTags).value
                func = sheet.cell(row=row, column=colConnFunc).value
                syn = sheet.cell(row=row, column=colSyn).value
                prob = sheet.cell(row=row, column=colProb).value
                weight = sheet.cell(row=row, column=colWeight).value

                # write preTags
                line = "netParams['connParams'].append({'preConds': {"
                for i,cond in enumerate(pre.split(';')):  # split into different conditions
                    if i>0: line = line + ", "
                    cond2 = cond.split('=')  # split into key and value
                    line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','')   # generate line
                line = line + "}" # end of preTags      

                # write postTags
                line = line + ",\n'postConds': {"
                for i,cond in enumerate(post.split(';')):  # split into different conditions
                    if i>0: line = line + ", "
                    cond2 = cond.split('=')  # split into key and value
                    line = line + "'" + cond2[0].replace(' ','') + "': " + cond2[1].replace(' ','')   # generate line
                line = line + "}" # end of postTags         
                line = line + ",\n'connFunc': '" + func + "'"  # write connFunc
                line = line + ",\n'synMech': '" + syn + "'"  # write synReceptor
                line = line + ",\n'probability': " + str(prob)  # write prob
                line = line + ",\n'weight': " + str(weight)  # write prob
                line = line + "})"  # add closing brackets
                line = line + '\n\n' # new line after each conn rule
                f.write(line)
615569
def generate_import_from(module_, names):
        
        regular_names = [n for n in names if "::" not in n]
        as_names = [n for n in names if "::" in n]

        line = ""
        if len(regular_names) > 0:
            slots = {"m": module_, "n": ", ".join(sorted(regular_names))}
            line = "from %(m)s import %(n)s" % slots
            if len(line) > LINE_LENGTH_LIMIT:
                slots["n"] = INDENT + (",\n" + INDENT).join(sorted(regular_names)) + ","
                line = "from %(m)s import (\n%(n)s\n)" % slots
            if len(as_names) > 0:
                line += "\n"

        for as_name in as_names:
            a, n = as_name.split("::")
            line += "from %(m)s import %(n)s as %(a)s" % {"m": module_, "n": n, "a": a}
        return line
1000608
def to_excel(self, *args):
        
        path = os.getcwd()
        fname = self.fname.replace(".tpl", "_tpl") + ".xlsx"
        idxs = self.filter_trends("")
        for idx in idxs:
            self.extract(idx)
        data_df = pd.DataFrame(self.data)
        data_df.columns = self.label.values()
        data_df.insert(0, "Time [s]", self.time)
        if len(args) > 0 and args[0] != "":
            path = args[0]
            if os.path.exists(path) == False:
                os.mkdir(path)
            data_df.to_excel(path + os.sep + fname)
        else:
            data_df.to_excel(self.path + os.sep + fname)
934833
def ImportTrips(self, trips_file):
    ""
    for trip_id, trip_starttime, line, strli, direction,  \
        stoptime_id, schedule_id, daytype_id, restriction_id,  \
        dest_station_id, dest_stop_id, trip_type in  \
        ReadCSV(trips_file,
            ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR',
             'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB',
             'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']):
      if trip_type != '1':
        print("skipping Trip ", trip_id, line, direction, \
              dest_station_id, trip_type)
        continue  # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other
      trip = Trip()
      #The trip_id (FRT_FID) field is not unique in the vbz data, as of Dec 2009
      # to prevent overwritingimported trips when we key them by trip.id
      # we should make trip.id unique, by combining trip_id and line
      trip.id = ("%s_%s") % (trip_id, line)
      trip.starttime = int(trip_starttime)
      trip.route = self.routes[line]
      dest_station = self.stations[dest_station_id]
      pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
      trip.pattern = self.patterns[pattern_id]
      trip.stoptimes = trip.pattern.stoptimes[stoptime_id]
      if restriction_id:
        service_id = u'VB%s.%s' % (schedule_id, restriction_id)
      else:
        service_id = u'C%s.%s' % (schedule_id, daytype_id)
      trip.service_id = service_id
      assert len(self.services[service_id]) > 0
      assert not trip.id in self.trips
      self.trips[trip.id] = trip
474556
def connectivity(ax):

    ''''''
    masked_array = np.ma.array(params.C_YX, mask=params.C_YX==0)
    # if analysis_params.bw:
    #     cmap = plt.get_cmap(gray, 20)
    #     cmap.set_bad('k', 1.)
    # else:
    #     cmap = plt.get_cmap('hot', 20)
    #     cmap.set_bad('k', 0.5)
    # im = ax.imshow(masked_array, cmap=cmap, vmin=0, interpolation='nearest')
    im = ax.pcolormesh(masked_array, cmap=cmap, vmin=0, ) #interpolation='nearest')
    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_yticklabels(params.Y, )
    ax.xaxis.set_label_position('top')
    ax.set_xlabel(r'$X$', labelpad=-1,fontsize=8)
    ax.set_ylabel(r'$Y$', labelpad=0, rotation=0,fontsize=8)

    rect = np.array(ax.get_position().bounds)
    rect[0] += rect[2] + 0.01
    rect[2] = 0.01
    fig = plt.gcf()
    cax = fig.add_axes(rect)

    cbar = plt.colorbar(im, cax=cax)
    #cbar.set_label(r'$C_{YX}$', ha='center')
    cbar.set_label(r'$C_{YX}$', labelpad=0)
733288
def connection_from_list(data, args=None, **kwargs):
    '''
    
    '''
    _len = len(data)
    return connection_from_list_slice(
        data,
        args,
        slice_start=0,
        list_length=_len,
        list_slice_length=_len,
        **kwargs
    )
601712
def import_setting(self):
        """"""
        LOGGER.debug('Import button clicked')
        home_directory = os.path.expanduser('~')
        file_path, __ = QFileDialog.getOpenFileName(
            self,
            self.tr('Import InaSAFE settings'),
            home_directory,
            self.tr('JSON File (*.json)'))
        if file_path:
            title = tr('Import InaSAFE Settings.')
            question = tr(
                'This action will replace your current InaSAFE settings with '
                'the setting from the file. This action is not reversible. '
                'Are you sure to import InaSAFE Setting?')
            answer = QMessageBox.question(
                self, title, question, QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.Yes:
                LOGGER.debug('Import from %s' % file_path)
                import_setting(file_path)
845095
def graph_from_seeds(seeds, cell_source):
    

    # when called from Spreadsheet instance, use the Spreadsheet cellmap and graph
    if hasattr(cell_source, 'G'): # ~ cell_source is a Spreadsheet
        cellmap = cell_source.cellmap
        cells = cellmap
        G = cell_source.G
        for c in seeds:
            G.add_node(c)
            cellmap[c.address()] = c
    # when called from ExcelCompiler instance, construct cellmap and graph from seeds
    else: # ~ cell_source is a ExcelCompiler
        cellmap = dict([(x.address(),x) for x in seeds])
        cells = cell_source.cells
        # directed graph
        G = networkx.DiGraph()
        # match the info in cellmap
        for c in cellmap.values(): G.add_node(c)

    # cells to analyze: only formulas
    todo = [s for s in seeds if s.formula]
    steps = [i for i,s in enumerate(todo)]
    names = cell_source.named_ranges

    while todo:
        c1 = todo.pop()
        step = steps.pop()
        cursheet = c1.sheet

        ###### 1) looking for cell c1 dependencies ####################
        # print 'C1', c1.address()
        # in case a formula, get all cells that are arguments
        pystr, ast = cell2code(c1, names)
        # set the code & compile it (will flag problems sooner rather than later)
        c1.python_expression = pystr.replace('"', "'") # compilation is done later

        if 'OFFSET' in c1.formula or 'INDEX' in c1.formula:
            if c1.address() not in cell_source.named_ranges: # pointers names already treated in ExcelCompiler
                cell_source.pointers.add(c1.address())

        # get all the cells/ranges this formula refers to
        deps = [x for x in ast.nodes() if isinstance(x,RangeNode)]
        # remove dupes
        deps = uniqueify(deps)

        ###### 2) connect dependencies in cells in graph ####################

        # ### LOG
        # tmp = []
        # for dep in deps:
        #     if dep not in names:
        #         if "!" not in dep and cursheet != None:
        #             dep = cursheet + "!" + dep
        #     if dep not in cellmap:
        #         tmp.append(dep)
        # #deps = tmp
        # logStep = "%s %s = %s " % ('|'*step, c1.address(), '',)
        # print logStep

        # if len(deps) > 1 and 'L' in deps[0] and deps[0] == deps[-1].replace('DG','L'):
        #     print logStep, "[%s...%s]" % (deps[0], deps[-1])
        # elif len(deps) > 0:
        #     print logStep, "->", deps
        # else:
        #     print logStep, "done"

        for dep in deps:
            dep_name = dep.tvalue.replace('$','')

            # this is to avoid :A1 or A1: dep due to clean_pointers() returning an ExcelError
            if dep_name.startswith(':') or dep_name.endswith(':'):
                dep_name = dep_name.replace(':', '')

            # if not pointer, we need an absolute address
            if dep.tsubtype != 'pointer' and dep_name not in names and "!" not in dep_name and cursheet != None:
                dep_name = cursheet + "!" + dep_name

            # Named_ranges + ranges already parsed (previous iterations)
            if dep_name in cellmap:
                origins = [cellmap[dep_name]]
                target = cellmap[c1.address()]
            # if the dep_name is a multi-cell range, create a range object
            elif is_range(dep_name) or (dep_name in names and is_range(names[dep_name])):
                if dep_name in names:
                    reference = names[dep_name]
                else:
                    reference = dep_name

                if 'OFFSET' in reference or 'INDEX' in reference:
                    start_end = prepare_pointer(reference, names, ref_cell = c1)
                    rng = cell_source.Range(start_end)

                    if dep_name in names: # dep is a pointer range
                        address = dep_name
                    else:
                        if c1.address() in names: # c1 holds is a pointer range
                            address = c1.address()
                        else: # a pointer range with no name, its address will be its name
                            address = '%s:%s' % (start_end["start"], start_end["end"])
                            cell_source.pointers.add(address)
                else:
                    address = dep_name

                    # get a list of the addresses in this range that are not yet in the graph
                    range_addresses = list(resolve_range(reference, should_flatten=True)[0])
                    cellmap_add_addresses = [addr for addr in range_addresses if addr not in cellmap.keys()]

                    if len(cellmap_add_addresses) > 0:
                        # this means there are cells to be added

                        # get row and col dimensions for the sheet, assuming the whole range is in one sheet
                        sheet_initial = split_address(cellmap_add_addresses[0])[0]
                        max_rows, max_cols = max_dimension(cellmap, sheet_initial)

                        # create empty cells that aren't in the cellmap
                        for addr in cellmap_add_addresses:
                            sheet_new, col_new, row_new = split_address(addr)

                            # if somehow a new sheet comes up in the range, get the new dimensions
                            if sheet_new != sheet_initial:
                                sheet_initial = sheet_new
                                max_rows, max_cols = max_dimension(cellmap, sheet_new)

                            # add the empty cells
                            if int(row_new) <= max_rows and int(col2num(col_new)) <= max_cols:
                                # only add cells within the maximum bounds of the sheet to avoid too many evaluations
                                # for A:A or 1:1 ranges

                                cell_new = Cell(addr, sheet_new, value="", should_eval='False') # create new cell object
                                cellmap[addr] = cell_new # add it to the cellmap
                                G.add_node(cell_new) # add it to the graph
                                cell_source.cells[addr] = cell_new # add it to the cell_source, used in this function

                    rng = cell_source.Range(reference)

                if address in cellmap:
                    virtual_cell = cellmap[address]
                else:
                    virtual_cell = Cell(address, None, value = rng, formula = reference, is_range = True, is_named_range = True )
                    # save the range
                    cellmap[address] = virtual_cell

                # add an edge from the range to the parent
                G.add_node(virtual_cell)
                # Cell(A1:A10) -> c1 or Cell(ExampleName) -> c1
                G.add_edge(virtual_cell, c1)
                # cells in the range should point to the range as their parent
                target = virtual_cell
                origins = []

                if len(list(rng.keys())) != 0: # could be better, but can't check on Exception types here...
                    for child in rng.addresses:
                        if child not in cellmap:
                            origins.append(cells[child])
                        else:
                            origins.append(cellmap[child])
            else:
                # not a range
                if dep_name in names:
                    reference = names[dep_name]
                else:
                    reference = dep_name

                if reference in cells:
                    if dep_name in names:
                        virtual_cell = Cell(dep_name, None, value = cells[reference].value, formula = reference, is_range = False, is_named_range = True )

                        G.add_node(virtual_cell)
                        G.add_edge(cells[reference], virtual_cell)

                        origins = [virtual_cell]
                    else:
                        cell = cells[reference]
                        origins = [cell]

                    cell = origins[0]

                    if cell.formula is not None and ('OFFSET' in cell.formula or 'INDEX' in cell.formula):
                        cell_source.pointers.add(cell.address())
                else:
                    virtual_cell = Cell(dep_name, None, value = None, formula = None, is_range = False, is_named_range = True )
                    origins = [virtual_cell]

                target = c1


            # process each cell
            for c2 in flatten(origins):

                # if we havent treated this cell allready
                if c2.address() not in cellmap:
                    if c2.formula:
                        # cell with a formula, needs to be added to the todo list
                        todo.append(c2)
                        steps.append(step+1)
                    else:
                        # constant cell, no need for further processing, just remember to set the code
                        pystr,ast = cell2code(c2, names)
                        c2.python_expression = pystr
                        c2.compile()

                    # save in the cellmap
                    cellmap[c2.address()] = c2
                    # add to the graph
                    G.add_node(c2)

                # add an edge from the cell to the parent (range or cell)
                if(target != []):
                    # print "Adding edge %s --> %s" % (c2.address(), target.address())
                    G.add_edge(c2,target)

        c1.compile() # cell compilation is done here because pointer ranges might update python_expressions


    return (cellmap, G)
976097
def _import_data(self):
        
        # set default state to ironpython for very old ironpython (2.7.0)
        iron_python = True
        try:
            iron_python = True if platform.python_implementation() == 'IronPython' \
                else False
        except ValueError as e:
            # older versions of IronPython fail to parse version correctly
            # failed to parse IronPython sys.version: '2.7.5 (IronPython 2.7.5 (2.7.5.0)
            # on .NET 4.0.30319.42000 (64-bit))'
            if 'IronPython' in str(e):
                iron_python = True

        if iron_python:
            statwin = codecs.open(self.file_path, 'r')
        else:
            statwin = codecs.open(self.file_path, 'r', encoding='utf-8', errors='ignore')
        try:
            line = statwin.readline()
            # import header with location
            self._header = [line] + [statwin.readline() for i in xrange(9)]
            self._body = statwin.read()
        except Exception as e:
            import traceback
            raise Exception('{}\n{}'.format(e, traceback.format_exc()))
        else:

            # import location data
            loc_name = self._header[2].strip().replace('Location -- ', '')
            if ' - ' in loc_name:
                city = ' '.join(loc_name.split(' - ')[:-1])
            else:
                # for US stat files it is full name separated by spaces
                city = ' '.join(loc_name.split()[:-2])
            country = loc_name.split(' ')[-1]
            source = self._header[6].strip().replace('Data Source -- ', '')
            station_id = self._header[8].strip().replace('WMO Station ', '')
            if iron_python:
                # IronPython
                coord_pattern = re.compile(r"{([NSEW])(\s*\d*)deg(\s*\d*)")
                matches = coord_pattern.findall(self._header[3].replace('\xb0', 'deg'))
            else:
                # CPython
                coord_pattern = re.compile(r"{([NSEW])(\s*\d*) (\s*\d*)")
                matches = coord_pattern.findall(self._header[3])
            lat_sign = -1 if matches[0][0] == 'S' else 1
            latitude = lat_sign * (float(matches[0][1]) + (float(matches[0][2]) / 60))
            lon_sign = -1 if matches[1][0] == 'W' else 1
            longitude = lon_sign * (float(matches[1][1]) + (float(matches[1][2]) / 60))
            time_zone = self._regex_check(r"{GMT\s*(\S*)\s*Hours}", self._header[3])
            elev_pattern = re.compile(r"Elevation\s*[-]*\s*(\d*)m\s*(\S*)")
            elev_matches = elev_pattern.findall(self._header[4])
            if len(elev_matches) == 0:
                elev_pattern = re.compile(r"Elevation\s*[-]*\s*(\d*)\s*m\s*(\S*)")
                elev_matches = elev_pattern.findall(self._header[4])
            elev_sign = -1 if elev_matches[0][-1].lower() == 'below' else 1
            elevation = elev_sign * float(elev_matches[0][0])
            self._location = Location()
            self._location.city = city
            self._location.country = country
            self._location.source = source
            self._location.station_id = station_id
            self._location.latitude = latitude
            self._location.longitude = longitude
            self._location.time_zone = time_zone
            self._location.elevation = elevation

            # pull out individual properties
            self._stand_press_at_elev = self._regex_check(
                r"Elevation\s*[-]*\s*(\d*)", self._header[5])
            self._ashrae_climate_zone = self._regex_check(
                r'Climate type\s"(\S*)"\s\(A', self._body)
            self._koppen_climate_zone = self._regex_check(
                r'Climate type\s"(\S*)"\s\(K', self._body)

            # pull out extreme and seasonal weeks.
            self._extreme_hot_week = self._regex_week_parse(
                r"Extreme Hot Week Period selected:"
                "\s*(\w{3})\s*(\d{1,2}):\s*(\w{3})\s*(\d{1,2}),")
            self._extreme_cold_week = self._regex_week_parse(
                r"Extreme Cold Week Period selected:"
                "\s*(\w{3})\s*(\d{1,2}):\s*(\w{3})\s*(\d{1,2}),")
            self._typical_weeks = self._regex_typical_week_parse()

            # pull out annual design days
            winter_vals = self._regex_parse(r"Heating\s(\d.*)")
            for key, val in zip(DesignDay.heating_keys, winter_vals):
                self._winter_des_day_dict[key] = val
            summer_vals = self._regex_parse(r"Cooling\s(\d.*)")
            for key, val in zip(DesignDay.cooling_keys, summer_vals):
                self._summer_des_day_dict[key] = val

            # Pull out relevant monthly information
            self._monthly_tau_beam = self._regex_parse(r"taub \(beam\)(.*)")
            self._monthly_tau_diffuse = self._regex_parse(r"taud \(diffuse\)(.*)")
            self._monthly_db_50 = self._regex_parse(r"Drybulb 5.0%(.*)")
            self._monthly_wb_50 = self._regex_parse(r"Coincident Wetbulb 5.0%(.*)")
            self._monthly_db_100 = self._regex_parse(r"Drybulb 10.%(.*)")
            self._monthly_wb_100 = self._regex_parse(r"Coincident Wetbulb 10.%(.*)")
            self._monthly_db_20 = self._regex_parse(r"Drybulb 2.0%(.*)")
            self._monthly_wb_20 = self._regex_parse(r"Coincident Wetbulb 2.0%(.*)")
            self._monthly_db_04 = self._regex_parse(r"Drybulb 0.4%(.*)")
            self._monthly_wb_04 = self._regex_parse(r"Coincident Wetbulb 0.4%(.*)")
            self._monthly_db_range_50 = self._regex_parse(r"Drybulb range - DB 5%(.*)")
            self._monthly_wb_range_50 = self._regex_parse(r"Wetbulb range - DB 5%(.*)")
            self._monthly_wind = self._regex_parse(
                r"Monthly Statistics for Wind Speed[\s\S]*Daily Avg(.*)")
            for direction in self._wind_dir_names:
                re_string = r"Monthly Wind Direction %[\s\S]*" + direction + r"\s(.*)"
                dirs = self._regex_parse(re_string)
                if dirs != []:
                    self._monthly_wind_dirs.append(dirs)
            if self._monthly_wind_dirs == []:
                self._monthly_wind_dirs = [[0] * 12 for i in xrange(8)]

        finally:
            statwin.close()
422316
def excel_to_dict(excel_filepath, encapsulate_filepath=False, **kwargs):
    
    result = {}
    try:
        callbacks = {'to_dictlist': excel_todictlist}  # Default callback
        callbacks.update(kwargs.get('alt_callbacks', {}))

        # Retrieve excel data as dict of sheets lists
        excel_data = callbacks.get('to_dictlist')(excel_filepath, **kwargs)
        for sheet in excel_data.keys():
            try:
                kwargs['rows'] = excel_data.get(sheet, [])
                result[sheet] = csv_to_dict(excel_filepath, **kwargs)
            except Exception as ex:
                logger.error('Fail to parse sheet {} - {}'.format(sheet, ex))
                result[sheet] = []
                continue

        if encapsulate_filepath:
            result = {excel_filepath: result}

    except Exception as ex:
        msg = 'Fail transform excel to dict - {}'.format(ex)
        logger.error(msg, excel_filepath=excel_filepath)

    return result
1288913
private void importCell(Cell cell) {
        this.content = new ArrayList();
        
        if(cell == null) {
            this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, this.parentRow.getParentTable().getBorders());
            return;
        }
        
        this.colspan = cell.getColspan();
        this.rowspan = cell.getRowspan();
        if(cell.getRowspan() > 1) {
            this.mergeType = MERGE_VERT_PARENT;
        }
        if(cell instanceof RtfCell) {
            this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, ((RtfCell) cell).getBorders());
        } else {
            this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, cell.getBorder(), cell.getBorderWidth(), cell.getBorderColor());
        }
        this.verticalAlignment = cell.getVerticalAlignment();
        if(cell.getBackgroundColor() == null) {
            this.backgroundColor = new RtfColor(this.document, 255, 255, 255);
        } else {
            this.backgroundColor = new RtfColor(this.document, cell.getBackgroundColor());
        }
        
        this.cellPadding = (int) this.parentRow.getParentTable().getCellPadding();
        
        Iterator cellIterator = cell.getElements();
        Paragraph container = null;
        while(cellIterator.hasNext()) {
            try {
                Element element = (Element) cellIterator.next();
                // should we wrap it in a paragraph
                if(!(element instanceof Paragraph) && !(element instanceof List)) {
                    if(container != null) {
                        container.add(element);
                    } else {
                        container = new Paragraph();
                        container.setAlignment(cell.getHorizontalAlignment());
                        container.add(element);
                    }
                } else {
                    if(container != null) {
                        RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
                        for(int i = 0; i < rtfElements.length; i++) {
                            rtfElements[i].setInTable(true);
                            this.content.add(rtfElements[i]);
                        }
                        container = null;
                    }
                    // if horizontal alignment is undefined overwrite
                    // with that of enclosing cell
                    if (element instanceof Paragraph && ((Paragraph) element).getAlignment() == Element.ALIGN_UNDEFINED) {
                        ((Paragraph) element).setAlignment(cell.getHorizontalAlignment());
                    }

                    RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(element);
                    for(int i = 0; i < rtfElements.length; i++) {
                        rtfElements[i].setInTable(true);
                        this.content.add(rtfElements[i]);
                    }
                }
            } catch(DocumentException de) {
                de.printStackTrace();
            }
        }
        if(container != null) {
            try {
                RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
                for(int i = 0; i < rtfElements.length; i++) {
                    rtfElements[i].setInTable(true);
                    this.content.add(rtfElements[i]);
                }
            } catch(DocumentException de) {
                de.printStackTrace();
            }
        }
    }
132517
def import_static_data(self):
        

        package_path = ding0.__path__[0]

        static_data = {}

        equipment_mv_parameters_trafos = cfg_ding0.get('equipment',
                                                       'equipment_mv_parameters_trafos')
        static_data['MV_trafos'] = pd.read_csv(os.path.join(package_path, 'data',
                                   equipment_mv_parameters_trafos),
                                   comment='#',
                                   delimiter=',',
                                   decimal='.',
                                   converters={'S_nom': lambda x: int(x)})

        # import equipment
        equipment_mv_parameters_lines = cfg_ding0.get('equipment',
                                                      'equipment_mv_parameters_lines')
        static_data['MV_overhead_lines'] = pd.read_csv(os.path.join(package_path, 'data',
                                           equipment_mv_parameters_lines),
                                           comment='#',
                                           converters={'I_max_th': lambda x: int(x),
                                                       'U_n': lambda x: int(x),
                                                       'reinforce_only': lambda x: int(x)})

        equipment_mv_parameters_cables = cfg_ding0.get('equipment',
                                                       'equipment_mv_parameters_cables')
        static_data['MV_cables'] = pd.read_csv(os.path.join(package_path, 'data',
                                   equipment_mv_parameters_cables),
                                   comment='#',
                                   converters={'I_max_th': lambda x: int(x),
                                               'U_n': lambda x: int(x),
                                               'reinforce_only': lambda x: int(x)})

        equipment_lv_parameters_cables = cfg_ding0.get('equipment',
                                                       'equipment_lv_parameters_cables')
        static_data['LV_cables'] = pd.read_csv(os.path.join(package_path, 'data',
                                   equipment_lv_parameters_cables),
                                   comment='#',
                                   index_col='name',
                                   converters={'I_max_th': lambda x: int(x), 'U_n': lambda x: int(x)})

        equipment_lv_parameters_trafos = cfg_ding0.get('equipment',
                                                       'equipment_lv_parameters_trafos')
        static_data['LV_trafos'] = pd.read_csv(os.path.join(package_path, 'data',
                                   equipment_lv_parameters_trafos),
                                   comment='#',
                                   delimiter=',',
                                   decimal='.',
                                   converters={'S_nom': lambda x: int(x)})

        # import LV model grids
        model_grids_lv_string_properties = cfg_ding0.get('model_grids',
                                                         'model_grids_lv_string_properties')
        static_data['LV_model_grids_strings'] = pd.read_csv(os.path.join(package_path, 'data',
                                                model_grids_lv_string_properties),
                                                comment='#',
                                                delimiter=';',
                                                decimal=',',
                                                index_col='string_id',
                                                converters={'string_id': lambda x: int(x),
                                                            'type': lambda x: int(x),
                                                            'Kerber Original': lambda x: int(x),
                                                            'count house branch': lambda x: int(x),
                                                            'distance house branch': lambda x: int(x),
                                                            'cable width': lambda x: int(x),
                                                            'string length': lambda x: int(x),
                                                            'length house branch A': lambda x: int(x),
                                                            'length house branch B': lambda x: int(x),
                                                            'cable width A': lambda x: int(x),
                                                            'cable width B': lambda x: int(x)})

        model_grids_lv_apartment_string = cfg_ding0.get('model_grids',
                                                        'model_grids_lv_apartment_string')
        converters_ids = {}
        for id in range(1,47):  # create int() converter for columns 1..46
            converters_ids[str(id)] = lambda x: int(x)
        static_data['LV_model_grids_strings_per_grid'] = pd.read_csv(os.path.join(package_path, 'data',
                                                         model_grids_lv_apartment_string),
                                                         comment='#',
                                                         delimiter=';',
                                                         decimal=',',
                                                         index_col='apartment_count',
                                                         converters=dict({'apartment_count': lambda x: int(x)},
                                                                         **converters_ids))

        return static_data
234243
def usufyToXlsxExport(d, fPath):
    
    from pyexcel_xlsx import get_data
    try:
        #oldData = get_data(fPath)
        # A change in the API now returns only an array of arrays if there is only one sheet.
        oldData = {"OSRFramework": get_data(fPath) }
    except:
        # No information has been recovered
        oldData = {"OSRFramework":[]}

    # Generating the new tabular data
    tabularData = _generateTabularData(d, oldData)

    from pyexcel_xlsx import save_data
    # Storing the file
    save_data(fPath, tabularData)
407207
public static List<Import> getImportList(final List<String> importCells) {
        final List<Import> importList = new ArrayList<Import>();
        if ( importCells == null ) return importList;

        for( String importCell: importCells ){
            final StringTokenizer tokens = new StringTokenizer( importCell, "," );
            while ( tokens.hasMoreTokens() ) {
                final Import imp = new Import();
                imp.setClassName( tokens.nextToken().trim() );
                importList.add( imp );
            }
        }
        return importList;
    }
895373
def fromxls(filename, sheet=None, use_view=True):
    
    
    return XLSView(filename, sheet=sheet, use_view=use_view)
1165953
def usufyToOdsExport(d, fPath):
    
    from pyexcel_ods import get_data
    try:
        #oldData = get_data(fPath)
        # A change in the API now returns only an array of arrays if there is only one sheet.
        oldData = {"OSRFramework": get_data(fPath) }
    except:
        # No information has been recovered
        oldData = {"OSRFramework":[]}

    # Generating the new tabular data
    tabularData = _generateTabularData(d, oldData)

    from pyexcel_ods import save_data
    # Storing the file
    save_data(fPath, tabularData)
472528
def fromListConn (self, preCellsTags, postCellsTags, connParam):
    from .. import sim

    ''' '''
    if sim.cfg.verbose: print('Generating set of connections from list (rule: %s) ...' % (connParam['label']))

    orderedPreGids = sorted(preCellsTags)
    orderedPostGids = sorted(postCellsTags)

    # list of params that can have a lambda function
    paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] 
    for paramStrFunc in paramsStrFunc:
        # replace lambda function (with args as dict of lambda funcs) with list of values
        connParam[paramStrFunc[:-4]+'List'] = {(orderedPreGids[preId],orderedPostGids[postId]): 
            connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellsTags[orderedPreGids[preId]], postCellsTags[orderedPostGids[postId]]) 
            for k,v in connParam[paramStrFunc+'Vars'].items()}) for preId,postId in connParam['connList']}

    if 'weight' in connParam and isinstance(connParam['weight'], list): 
        connParam['weightFromList'] = list(connParam['weight'])  # if weight is a list, copy to weightFromList
    if 'delay' in connParam and isinstance(connParam['delay'], list): 
        connParam['delayFromList'] = list(connParam['delay'])  # if delay is a list, copy to delayFromList
    if 'loc' in connParam and isinstance(connParam['loc'], list): 
        connParam['locFromList'] = list(connParam['loc'])  # if delay is a list, copy to locFromList


    for iconn, (relativePreId, relativePostId) in enumerate(connParam['connList']):  # for each postsyn cell
        preCellGid = orderedPreGids[relativePreId]     
        postCellGid = orderedPostGids[relativePostId]
        if postCellGid in self.gid2lid:  # check if postsyn is in this node's list of gids
            
            if 'weightFromList' in connParam: connParam['weight'] = connParam['weightFromList'][iconn] 
            if 'delayFromList' in connParam: connParam['delay'] = connParam['delayFromList'][iconn]
            if 'locFromList' in connParam: connParam['loc'] = connParam['locFromList'][iconn]
    
            if preCellGid != postCellGid: # if not self-connection
                self._addCellConn(connParam, preCellGid, postCellGid)