Appends synset to Polaris IO file <fileName>
331086
def write(self,fileName):
        '''
        '''
        f = open(fileName, 'ab')
        f.write('%s%s' % (self.polarisText,
                          Synset.linebreak)
                )
        f.close()
468100
def write_file(fname, info):
    """"""
    with open(fname, 'w') as outfile:
        # File header
        outfile.write('# Copyright (c) 2018 MetPy Developers.\n')
        outfile.write('# Distributed under the terms of the BSD 3-Clause License.\n')
        outfile.write('# SPDX-License-Identifier: BSD-3-Clause\n\n')
        outfile.write('# flake8: noqa\n')
        outfile.write('# Generated file -- do not modify\n')

        # Variable descriptions
        outfile.write('descriptions = {')
        outdata = ',\n                '.join('"{name}": "{desc}"'.format(
            **i) for i in info if need_desc(i))
        outfile.write(outdata)
        outfile.write('}\n\n')

        # Now the struct format
        outfile.write('fields = [')
        outdata = ',\n          '.join('({fname}, "{fmt}")'.format(
            fname=field_name(i), **i) for i in info)
        outfile.write(outdata)
        outfile.write(']\n')
162790
def add_files(session, imagedir, verbose):
  """"""

  def add_file(session, basename, userid, shotid, sessionid):
    """Parse a single filename and add it to the list."""
    session.add(File(userid, basename, sessionid, shotid))

  filenames = os.listdir(imagedir)
  for filename in filenames:
    basename, extension = os.path.splitext(filename)
    if extension == db_file_extension:
      if verbose>1: print("  Adding file '%s'..." % (basename))
      parts = string.split(basename, "_")
      ctype = parts[0]
      shotid = int(parts[2])
      userid = ctype + '_%d' % int(parts[1])
      if parts[0] == "Impostor":
        sessionid = 3
      elif parts[0] == "Genuine" and shotid <= 6:
        sessionid = 1
      elif parts[0] == "Genuine" and shotid > 6:
        sessionid = 2
        shotid = shotid - 6
      add_file(session, basename, userid, shotid, sessionid)
982628
def add_file(self, filename):
        """"""

        assert not self.final, 'Trying to mutate a final graph.'
        self.add_source_file(filename)
        resolved, unresolved = self.get_file_deps(filename)
        self.graph.add_node(filename)
        for f in resolved:
            self.graph.add_node(f)
            self.graph.add_edge(filename, f)
        for imp in unresolved:
            self.broken_deps[filename].add(imp)
1176937
def add(context, filenames):
    
    logging.info(_('Current Mode: Add Linux data'))
    context.obj['database'].add_data(filenames)
    sys.exit(0)
1349252
def tcl_add_fileset_file(filename: str):
    
    if filename.endswith(".vhd"):
        t = "VHDL"
    elif filename.endswith(".v") or filename.endswith(".sv"):
        t = "VERILOG"
    else:
        raise NotImplementedError(
            "Can not resolve type of file by extension", filename)
    name = basename(filename)

    return "add_fileset_file %s %s PATH %s" % (name, t, filename)
229441
def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
	
	deprecated("'create_append' is deprecated. See https://github.com/linnarsson-lab/loompy/issues/42")
	if os.path.exists(filename):
		with connect(filename) as ds:
			ds.add_columns(layers, col_attrs, fill_values=fill_values)
	else:
		create(filename, layers, row_attrs, col_attrs, file_attrs=file_attrs)
639923
def insert_infocontent_data(germanet_db):
    '''
    
    '''
    gnet           = germanet.GermaNet(germanet_db)
    # use add one smoothing
    gn_counts      = defaultdict(lambda: 1.)
    total_count    = 1
    input_file     = gzip.open(os.path.join(os.path.dirname(__file__),
                                            WORD_COUNT_FILE))
    num_lines_read = 0
    num_lines      = 0
    for line in input_file:
        line       = line.decode('utf-8').strip().split('\t')
        num_lines += 1
        if len(line) != 3:
            continue
        count, pos, word = line
        num_lines_read += 1
        count           = int(count)
        synsets         = set(gnet.synsets(word, pos))
        if not synsets:
            continue
        # Although Resnik (1995) suggests dividing count by the number
        # of synsets, Patwardhan et al (2003) argue against doing
        # this.
        count = float(count) / len(synsets)
        for synset in synsets:
            total_count += count
            paths = synset.hypernym_paths
            scount = float(count) / len(paths)
            for path in paths:
                for ss in path:
                    gn_counts[ss._id] += scount
    print('Read {0} of {1} lines from count file.'.format(num_lines_read,
                                                          num_lines))
    print('Recorded counts for {0} synsets.'.format(len(gn_counts)))
    print('Total count is {0}'.format(total_count))
    input_file.close()
    # update all the synset records in GermaNet
    num_updates = 0
    for synset in germanet_db.synsets.find():
        synset['infocont'] = gn_counts[synset['_id']] / total_count
        germanet_db.synsets.save(synset)
        num_updates += 1
    print('Updated {0} synsets.'.format(num_updates))
1029725
function buildMetadata(f, metadataTarget, options, isText) {

  var ext = path.extname(f);
  var name = path.basename(f, ext);

  var data = buildMetadataContent(name, options, ext, isText);

  fs.ensureFileSync(metadataTarget);
  fs.writeFileSync(metadataTarget, data, 'utf8');

}
818689
def add_fileobj(self, fname, fcontent):
        
        tar_info = tarfile.TarInfo(fname)
        if isinstance(fcontent, io.BytesIO):
            tar_info.size = len(fcontent.getvalue())
        elif isinstance(fcontent, io.StringIO):
            tar_info.size = len(fcontent.getvalue())
            fcontent = io.BytesIO(fcontent.getvalue().encode("utf8"))
        else:
            if hasattr(fcontent, "readable"):
                fcontent = fcontent
            tar_info.size = len(fcontent)
            if isinstance(fcontent, str):
                fcontent = fcontent.encode("utf8")
            fcontent = io.BytesIO(fcontent)
        self._ios_to_add[tar_info] = fcontent
1130509
def push(description, datasets, wait, verbose):
    """"""
    # Loading config
    config = _get_config()
    file_patterns = config["contents"]
    if not isinstance(file_patterns, type([])):
        # put it into an array so we can iterate it, if it isn't already an array
        file_patterns = [file_patterns]
    if datasets:
        datasets_string = datasets.split(',')
    else:
        datasets_string = config.get("datasets", '')


    # Getting all file names/globs -- making sure we get CONFIG_FILE
    files = {CONFIG_FILE}  # use a set so we don't get duplicates
    for pattern in file_patterns:
        files.update(glob.glob(pattern))
    if not files:
        print "No files could be found? Check your contents section in `CONFIG_FILE`!"
        exit(-1)

    if verbose:
        print ""
        print "gatherered files:"
        for path in files:
            print "\t", path
        print ""

    # Zipping
    _print("zipping...")

    if not os.path.exists("brains_history"):
        os.mkdir("brains_history")

    zip_path = 'brains_history/%s.zip' % str(datetime.datetime.now())
    with ZipFile(zip_path, 'w') as zip_file:
        for path in files:
            zip_file.write(path)
    cprint("done", 'green')

    # Sending to server
    with open(zip_path, 'rb') as zip_file:
        _print("sending to server...")
        try:
            response = requests.post(
                URL_SUBMIT,
                files={
                    "zip_file": zip_file,
                },
                data={
                    "name": config["name"],
                    "description": description or '',
                    "languages": config["languages"],
                    "datasets": datasets_string,
                    "wait": wait,
                },
                stream=wait  # if we're waiting for response then stream
            )

            if response.status_code == 200:
                cprint("done", 'green')

                if wait:
                    _print("\nOutput: ")
                    cprint(" " * 72, 'green', attrs=('underline',))

                    chunk_buffer = ""
                    # read in 1 chunk at a time for carriage return detection
                    for chunk in response.iter_content(chunk_size=1):
                        chunk_buffer += chunk

                        if chunk == '\r':
                            # We hit the end of a message!
                            try:
                                data = json.loads(chunk_buffer)
                                if "stdout" not in data or "stderr" not in data:
                                    print "dis one"
                                    continue
                            except (ValueError,):
                                continue

                            if data["stdout"]:
                                # Get rid of termination string, if it's there
                                data["stdout"] = data["stdout"].replace("-%-%-%-%-END BRAIN SEQUENCE-%-%-%-%-", "")
                                _print(data["stdout"])
                            if data["stderr"]:
                                _print(colored(data["stderr"], 'red'))

                            # Clear buffer after reading message
                            chunk_buffer = ""
            else:
                cprint(response.json()["error"], 'red')
        except requests.exceptions.ConnectionError:
            cprint("failed to connect to server!", 'red')
            exit(-2)
1022189
def _addDataFile(self, filename):
        
        if filename.endswith('.ttl'):
            self._rdfGraph.parse(filename, format='n3')
        else:
            self._rdfGraph.parse(filename, format='xml')
716155
def insert(self, filename):
        
        errors = []
        if os.path.isfile(filename):
            log.info('loading IOC from: {}'.format(filename))
            if not self.parse(filename):
                log.warning('Failed to prase [{}]'.format(filename))
                errors.append(filename)
        elif os.path.isdir(filename):
            log.info('loading IOCs from: {}'.format(filename))
            for fn in glob.glob(filename + os.path.sep + '*.ioc'):
                if not os.path.isfile(fn):
                    continue
                else:
                    if not self.parse(fn):
                        log.warning('Failed to parse [{}]'.format(filename))
                        errors.append(fn)
        else:
            pass
        log.info('Parsed [%s] IOCs' % str(len(self)))
        return errors
1293117
def write_options_to_YAML(self, filename):
        
        fd = open(filename, "w")
        yaml.dump(_options_to_dict(self.gc), fd, default_flow_style=False)
        fd.close()
507674
function addFiles(sources, dest, options) {
      var opt = _.extend({}, defaultOptions, options || {});

      if(_.isString(sources)) {
        sources = [sources];
      }

      if(!inCwd(dest) || _.any(sources, function(src) {
        return !inCwd(src);
      })) {
        grunt.verbose.writeln('Ignore %s to %s: not in CWD.');
        return;
      }

      return addToQueueCopy(sources, dest, opt);
    }
1356632
def update(self):
        """"""
        self.filename = self.parent.info.dataset.filename

        self.chan = self.parent.info.dataset.header['chan_name']
        for chan in self.chan:
            self.idx_chan.addItem(chan)
1291148
def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False):
    

    # if overwrite is false load existing data and append to new instruments
    if os.path.isfile(filename) and overwrite == False:
        data_dict = load_b26_file(filename)
    else:
        data_dict = {}

    if instruments is not None:
        if 'instruments' in data_dict:
            data_dict['instruments'].update(instruments)
        else:
            data_dict['instruments'] = instruments

    if scripts is not None:
        if 'scripts' in data_dict:
            data_dict['scripts'].update(scripts)
        else:
            data_dict['scripts'] = scripts

    if probes is not None:
        probe_instruments = list(probes.keys())
        if 'probes' in data_dict:
            # all the instruments required for old and new probes
            probe_instruments= set(probe_instruments + list(data_dict['probes'].keys()))
        else:
            data_dict.update({'probes':{}})

        for instrument in probe_instruments:
            if instrument in data_dict['probes'] and instrument in probes:
                # update the data_dict
                data_dict['probes'][instrument] = ','.join(set(data_dict['probes'][instrument].split(',') + probes[instrument].split(',')))
            else:
                data_dict['probes'].update(probes)

    if verbose:
        print(('writing ', filename))

    if data_dict != {}:

        # if platform == 'Windows':
        #     # windows can't deal with long filenames so we have to use the prefix '\\\\?\\'
        #     if len(filename.split('\\\\?\\')) == 1:
        #         filename = '\\\\?\\'+ filename
        # create folder if it doesn't exist
        if verbose:
            print(('filename', filename))
            print(('exists', os.path.exists(os.path.dirname(filename))))

        if os.path.exists(os.path.dirname(filename)) is False:
            # print(('creating', os.path.dirname(filename)))
            os.makedirs(os.path.dirname(filename))

        with open(filename, 'w') as outfile:
            tmp = json.dump(data_dict, outfile, indent=4)