Returns path to temporary copy of embedded QuickLook preview, if it exists
184455
def embedded_preview(src_path):
  '''  '''
  try:
    assert(exists(src_path) and isdir(src_path))

    preview_list = glob(join(src_path, '[Q|q]uicklook', '[P|p]review.*'))
    assert(preview_list)  # Assert there's at least one preview file
    preview_path = preview_list[0]  # Simplistically, assume there's only one

    with NamedTemporaryFile(prefix='pyglass', suffix=extension(preview_path), delete=False) as tempfileobj:
      dest_path = tempfileobj.name
      shutil.copy(preview_path, dest_path)

    assert(exists(dest_path))
    return dest_path
  except:
    return None
541283
def preview_from_config(name, url, backend,
                        description=None,
                        frequency=DEFAULT_HARVEST_FREQUENCY,
                        owner=None,
                        organization=None,
                        config=None,
                        ):
    ''''''
    if owner and not isinstance(owner, User):
        owner = User.get(owner)

    if organization and not isinstance(organization, Organization):
        organization = Organization.get(organization)

    source = HarvestSource(
        name=name,
        url=url,
        backend=backend,
        description=description,
        frequency=frequency or DEFAULT_HARVEST_FREQUENCY,
        owner=owner,
        organization=organization,
        config=config,
    )
    cls = backends.get(current_app, source.backend)
    max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']
    backend = cls(source, dryrun=True, max_items=max_items)
    return backend.harvest()
422667
def copy_path(self, fnames=None, method="absolute"):
        """"""
        cb = QApplication.clipboard()
        explorer_dir = self.fsmodel.rootPath()
        if fnames is None:
            fnames = self.get_selected_filenames()
        if not isinstance(fnames, (tuple, list)):
            fnames = [fnames]
        fnames = [_fn.replace(os.sep, "/") for _fn in fnames]
        if len(fnames) > 1:
            if method == "absolute":
                clipboard_files = ',\n'.join('"' + _fn + '"' for _fn in fnames)
            elif method == "relative":
                clipboard_files = ',\n'.join('"' +
                                             osp.relpath(_fn, explorer_dir).
                                             replace(os.sep, "/") + '"'
                                             for _fn in fnames)
        else:
            if method == "absolute":
                clipboard_files = fnames[0]
            elif method == "relative":
                clipboard_files = (osp.relpath(fnames[0], explorer_dir).
                                   replace(os.sep, "/"))
        copied_from = self.parent_widget.__class__.__name__
        if copied_from == 'ProjectExplorerWidget' and method == 'relative':
            clipboard_files = [path.strip(',"') for path in
                               clipboard_files.splitlines()]
            clipboard_files = ['/'.join(path.strip('/').split('/')[1:]) for
                               path in clipboard_files]
            if len(clipboard_files) > 1:
                clipboard_files = ',\n'.join('"' + _fn + '"' for _fn in
                                             clipboard_files)
            else:
                clipboard_files = clipboard_files[0]
        cb.setText(clipboard_files, mode=cb.Clipboard)
1065865
def get_temp_file (mode='r', **kwargs):
    """"""
    fd, filename = tempfile.mkstemp(**kwargs)
    return os.fdopen(fd, mode), filename
745771
def temporary_object_path(self, name):
        
        return os.path.join(self._path, self.TMP_OBJ_DIR, name)
121974
function(callback) {
          if (!context.copyOriginal) {
            return callback(null);
          }
          var suffix = 'original.' + context.extension;
          var tempFile = context.tempFolder + '/' + suffix;
          if (context.extension !== 'jpg') {
            // Don't forget to tell the caller that we did the work,
            // even if it was just a copy
            context.adjustedOriginal = tempFile;
            return copyFile(context.workingPath, tempFile, callback);
          }

          var args = [ context.workingPath ];
          if (context.crop) {
            args.push('-crop');
            args.push(context.crop.left);
            args.push(context.crop.top);
            args.push(context.crop.width);
            args.push(context.crop.height);
          }
          args.push('-write');
          args.push(tempFile);
          context.adjustedOriginal = tempFile;

          var proc = childProcess.spawn('imagecrunch', args);
          proc.on('close', function(code) {
            if (code !== 0) {
              return callback(code);
            }
            return callback(null);
          });
        }
822542
def preview(ident):
    ''''''
    source = get_source(ident)
    cls = backends.get(current_app, source.backend)
    max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']
    backend = cls(source, dryrun=True, max_items=max_items)
    return backend.harvest()
310448
def __load_temp_file(self):
        """"""
        if not osp.isfile(self.TEMPFILE_PATH):
            # Creating temporary file
            default = ['# -*- coding: utf-8 -*-',
                       '"""', _("Spyder Editor"), '',
                       _("This is a temporary script file."),
                       '"""', '', '']
            text = os.linesep.join([encoding.to_unicode(qstr)
                                    for qstr in default])
            try:
                encoding.write(to_text_string(text), self.TEMPFILE_PATH,
                               'utf-8')
            except EnvironmentError:
                self.new()
                return

        self.load(self.TEMPFILE_PATH)
167482
def save(self, path, verbose=False):
        
        path = os.path.realpath(path)
        if os.path.exists(path):
            if self.load_path and self.load_path == path:
                if verbose:
                    print "saving over previous suite..."
                for context_name in self.context_names:
                    self.context(context_name)  # load before dir deleted
                shutil.rmtree(path)
            else:
                raise SuiteError("Cannot save, path exists: %r" % path)

        contexts_path = os.path.join(path, "contexts")
        os.makedirs(contexts_path)

        # write suite data
        data = self.to_dict()
        filepath = os.path.join(path, "suite.yaml")
        with open(filepath, "w") as f:
            f.write(dump_yaml(data))

        # write contexts
        for context_name in self.context_names:
            context = self.context(context_name)
            context._set_parent_suite(path, context_name)
            filepath = self._context_path(context_name, path)
            if verbose:
                print "writing %r..." % filepath
            context.save(filepath)

        # create alias wrappers
        tools_path = os.path.join(path, "bin")
        os.makedirs(tools_path)
        if verbose:
            print "creating alias wrappers in %r..." % tools_path

        tools = self.get_tools()
        for tool_alias, d in tools.iteritems():
            tool_name = d["tool_name"]
            context_name = d["context_name"]

            data = self._context(context_name)
            prefix_char = data.get("prefix_char")

            if verbose:
                print ("creating %r -> %r (%s context)..."
                       % (tool_alias, tool_name, context_name))
            filepath = os.path.join(tools_path, tool_alias)

            create_forwarding_script(filepath,
                                     module="suite",
                                     func_name="_FWD__invoke_suite_tool_alias",
                                     context_name=context_name,
                                     tool_name=tool_name,
                                     prefix_char=prefix_char)
503201
def _paste(self, sources, destination, copy):
        
        for src in sources:
            debug('%s <%s> to <%s>' % (
                'copying' if copy else 'cutting', src, destination))
            perform_copy = True
            ext = os.path.splitext(src)[1]
            original = os.path.splitext(os.path.split(src)[1])[0]
            filename, status = QtWidgets.QInputDialog.getText(
                self.tree_view, _('Copy'), _('New name:'),
                QtWidgets.QLineEdit.Normal, original)
            if filename == '' or not status:
                return
            filename = filename + ext
            final_dest = os.path.join(destination, filename)
            if os.path.exists(final_dest):
                rep = QtWidgets.QMessageBox.question(
                    self.tree_view, _('File exists'),
                    _('File <%s> already exists. Do you want to erase it?') %
                    final_dest,
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                    QtWidgets.QMessageBox.No)
                if rep == QtWidgets.QMessageBox.No:
                    perform_copy = False
            if not perform_copy:
                continue
            try:
                if os.path.isfile(src):
                    shutil.copy(src, final_dest)
                else:
                    shutil.copytree(src, final_dest)
            except (IOError, OSError) as e:
                QtWidgets.QMessageBox.warning(
                    self.tree_view, _('Copy failed'), _('Failed to copy "%s" to "%s".\n\n%s' %
                                                        (src, destination, str(e))))
                _logger().exception('failed to copy "%s" to "%s', src,
                                    destination)
            else:
                debug('file copied %s', src)
            if not copy:
                debug('removing source (cut operation)')
                if os.path.isfile(src):
                    os.remove(src)
                else:
                    shutil.rmtree(src)
                self.tree_view.files_renamed.emit([(src, final_dest)])
991521
function(ql) {
				var fm      = ql.fm,
			preview = ql.preview,
			textMaxlen = parseInt(ql.options.textMaxlen) || 2000,
			prettify = function() {
				if (fm.options.cdns.prettify) {
					fm.loadScript([fm.options.cdns.prettify + (fm.options.cdns.prettify.match(/\?/)? '&' : '?') + 'autorun=false']);
					prettify = function() { return true; };
				} else {
					prettify = function() { return false; };
				}
			},
			PRcheck = function(node, cnt) {
				if (prettify()) {
					if (typeof window.PR === 'undefined' && cnt--) {
						setTimeout(function() { PRcheck(node, cnt); }, 100);
					} else {
						if (typeof window.PR === 'object') {
							node.css('cursor', 'wait');
							requestAnimationFrame(function() {
								PR.prettyPrint && PR.prettyPrint(null, node.get(0));
								node.css('cursor', '');
							});
						} else {
							prettify = function() { return false; };
						}
					}
				}
			};
		
		preview.on(ql.evUpdate, function(e) {
			var file = e.file,
				mime = file.mime,
				jqxhr, loading;
			
			if (fm.mimeIsText(file.mime) && (!ql.options.getSizeMax || file.size <= ql.options.getSizeMax)) {
				e.stopImmediatePropagation();
				
				(typeof window.PR === 'undefined') && prettify();
				
				loading = $('<div class="elfinder-quicklook-info-data"> '+fm.i18n('nowLoading')+'<span class="elfinder-info-spinner"></div>').appendTo(ql.info.find('.elfinder-quicklook-info'));

				// stop loading on change file if not loadin yet
				preview.one('change', function() {
					jqxhr.state() == 'pending' && jqxhr.reject();
				});
				
				jqxhr = fm.request({
					data           : {cmd : 'get', target : file.hash, conv : 1, _t : file.ts},
					options        : {type: 'get', cache : true},
					preventDefault : true
				})
				.done(function(data) {
					var reg = new RegExp('^(data:'+file.mime.replace(/([.+])/g, '\\$1')+';base64,)', 'i'),
						text = data.content,
						part, more, node, m;
					ql.hideinfo();
					if (window.atob && (m = text.match(reg))) {
						text = atob(text.substr(m[1].length));
					}
					
					more = text.length - textMaxlen;
					if (more > 100) {
						part = text.substr(0, textMaxlen) + '...';
					} else {
						more = 0;
					}
					
					node = $('<div class="elfinder-quicklook-preview-text-wrapper"><pre class="elfinder-quicklook-preview-text prettyprint"></pre></div>');
					
					if (more) {
						node.append($('<div class="elfinder-quicklook-preview-charsleft"><hr/><span>' + fm.i18n('charsLeft', fm.toLocaleString(more)) + '</span></div>')
							.on('click', function() {
								var top = node.scrollTop();
								$(this).remove();
								node.children('pre').removeClass('prettyprinted').text(text).scrollTop(top);
								PRcheck(node, 100);
							})
						);
					}
					node.children('pre').text(part || text);
					
					node.on('touchstart', function(e) {
						if ($(this)['scroll' + (fm.direction === 'ltr'? 'Right' : 'Left')]() > 5) {
							e.originalEvent._preventSwipeX = true;
						}
					}).appendTo(preview);
					
					PRcheck(node, 100);
				})
				.always(function() {
					loading.remove();
				});
			}
		});
	}
1154306
function(path) {

        var _this = this,
            target = PATH.resolve(this.root, this.target, path),
            repo = joinUrlPath(this.url, path);

        return QFS.exists(target)
            .then(function(exists) {

                var cmd = exists?
                        _this.getUpdateCmd(repo, target) :
                        _this.getInitialCheckoutCmd(repo, target),
                    d = Q.defer();

                _this.log(cmd);

                CP.exec(cmd, function(err, stdout, stderr) {
                    stdout && _this.log(stdout);
                    stderr && _this.log(stderr);

                    if (err) return d.reject(err);

                    _this.lastRunTime = Date.now();
                    d.resolve();
                });

                return d.promise;

            });

    }
508518
function findImportedPath(url, prev, includedFilesMap, includedPaths) {
  let candidateFromPaths;

  if(prev !== 'stdin') {
    const prevPath = path.posix.dirname(prev);
    candidateFromPaths = [prevPath, ...includedPaths];
  } else {
    candidateFromPaths = [...includedPaths];
  }

  for(let i = 0; i < candidateFromPaths.length; i++) {
    let candidatePath;
    let candidateFromPath = normalizePath(makeAbsolute(candidateFromPaths[i]));
    if (path.isAbsolute(url)) {
      candidatePath = normalizePath(url);
    } else {
      // Get normalize absolute candidate from path
      candidatePath = path.posix.join(candidateFromPath, url);
    }

    if(includedFilesMap[candidatePath]) {
      return candidatePath;
    } else {
      let urlBasename = path.posix.basename(url);
      let indexOfBasename = url.lastIndexOf(urlBasename);
      let partialUrl = `${url.substring(0, indexOfBasename)}_${urlBasename}`;

      if (path.isAbsolute(partialUrl)) {
        candidatePath = normalizePath(partialUrl);
      } else {
        candidatePath = path.posix.join(candidateFromPath, partialUrl);
      }

      if(includedFilesMap[candidatePath]) {
        return candidatePath;
      }
    }
  }

  return null;
}
1173712
def jsPath(path):
    ''''''
    shortPath=path.replace(
            "C:\\Users\\scheinerbock\\Desktop\\"+
            "ideogram\\scrapeSource\\test\\","")
    noDash = shortPath.replace("-","_dash_")
    jsPath=noDash.replace("\\","_slash_").replace(".","_dot_")
    return jsPath
636389
function updatePreview() {
  // Toggle between LTR/RTL if needed (also used in first display).
  var newDir = document.getElementById('direction').value;
  if (oldDir != newDir) {
    if (previewWorkspace) {
      previewWorkspace.dispose();
    }
    var rtl = newDir == 'rtl';
    previewWorkspace = Blockly.inject('preview',
        {rtl: rtl,
         media: '../../media/',
         scrollbars: true});
    oldDir = newDir;
  }
  previewWorkspace.clear();

  // Fetch the code and determine its format (JSON or JavaScript).
  var format = document.getElementById('format').value;
  if (format == 'Manual') {
    var code = document.getElementById('languageTA').value;
    // If the code is JSON, it will parse, otherwise treat as JS.
    try {
      JSON.parse(code);
      format = 'JSON';
    } catch (e) {
      format = 'JavaScript';
    }
  } else {
    var code = document.getElementById('languagePre').textContent;
  }
  if (!code.trim()) {
    // Nothing to render.  Happens while cloud storage is loading.
    return;
  }

  // Backup Blockly.Blocks object so that main workspace and preview don't
  // collide if user creates a 'factory_base' block, for instance.
  var backupBlocks = Blockly.Blocks;
  try {
    // Make a shallow copy.
    Blockly.Blocks = {};
    for (var prop in backupBlocks) {
      Blockly.Blocks[prop] = backupBlocks[prop];
    }

    if (format == 'JSON') {
      var json = JSON.parse(code);
      Blockly.Blocks[json.id || UNNAMED] = {
        init: function() {
          this.jsonInit(json);
        }
      };
    } else if (format == 'JavaScript') {
      eval(code);
    } else {
      throw 'Unknown format: ' + format;
    }

    // Look for a block on Blockly.Blocks that does not match the backup.
    var blockType = null;
    for (var type in Blockly.Blocks) {
      if (typeof Blockly.Blocks[type].init == 'function' &&
          Blockly.Blocks[type] != backupBlocks[type]) {
        blockType = type;
        break;
      }
    }
    if (!blockType) {
      return;
    }

    // Create the preview block.
    var previewBlock = previewWorkspace.newBlock(blockType);
    previewBlock.initSvg();
    previewBlock.render();
    previewBlock.setMovable(false);
    previewBlock.setDeletable(false);
    previewBlock.moveBy(15, 10);
    previewWorkspace.clearUndo();

    updateGenerator(previewBlock);
  } finally {
    Blockly.Blocks = backupBlocks;
  }
}
261915
function getPathsToSync(fs, path, callback) {
  getAttr(fs, path, constants.attributes.pathsToSync, callback);
}
558261
def save_current_as(self):
        
        if not self.current_widget():
            return
        mem = self.current_widget().file.path
        self.current_widget().file._path = None
        self.current_widget().file._old_path = mem
        CodeEditTabWidget.default_directory = os.path.dirname(mem)
        widget = self.current_widget()
        try:
            success = self.main_tab_widget.save_widget(widget)
        except Exception as e:
            QtWidgets.QMessageBox.warning(
                self, _('Failed to save file as'),
                _('Failed to save file as %s\nError=%s') % (
                    widget.file.path, str(e)))
            widget.file._path = mem
        else:
            if not success:
                widget.file._path = mem
            else:
                CodeEditTabWidget.default_directory = os.path.expanduser('~')
                self.document_saved.emit(widget.file.path, '')

                # rename tab
                tw = widget.parent_tab_widget
                tw.setTabText(tw.indexOf(widget),
                              os.path.split(widget.file.path)[1])

        return self.current_widget().file.path