Takes a post path and returns a dictionary of variables
435796
def parse_md(self):
    """"""
    post_content = _MARKDOWN.convert(self.raw_src)

    if hasattr(_MARKDOWN, 'Meta'):
      # 'Meta' in _MARKDOWN and _MARKDOWN.Meta:
      for key in _MARKDOWN.Meta:
        print "\t meta: %s: %s (%s)" % (key, _MARKDOWN.Meta[key][0], type(_MARKDOWN.Meta[key][0]))
        if key == 'pubdate':
          setattr(self, key, datetime.datetime.fromtimestamp(float(_MARKDOWN.Meta[key][0])))
        else:
          setattr(self, key, _MARKDOWN.Meta[key][0])
      
    self.content = post_content
    self.stub = self.__key__
  
    # set required fields
    # @TODO required in schema rather than here
    
    if not hasattr(self, 'pubdate'):
      print '\t Notice: setting default pubdate'
      setattr(self, 'pubdate', datetime.datetime.now())
1204848
def get_posts(self, include_draft=False, filter_functions=None):
        

        def posts_generator(path):
            """Loads valid posts one by one in the given path."""
            if os.path.isdir(path):
                for file in os.listdir(path):
                    filename, ext = os.path.splitext(file)
                    format_name = get_standard_format_name(ext[1:])
                    if format_name is not None and re.match(
                            r'\d{4}-\d{2}-\d{2}-.+', filename):
                        # the format is supported and the filename is valid,
                        # so load this post
                        post = Post()
                        post.format = format_name
                        post.meta, post.raw_content = FileStorage.read_file(
                            os.path.join(path, file))
                        post.rel_url = filename.replace('-', '/', 3) + '/'
                        post.unique_key = '/post/' + post.rel_url
                        yield post

        posts_path = os.path.join(current_app.instance_path, 'posts')
        result = filter(lambda p: include_draft or not p.is_draft,
                        posts_generator(posts_path))
        result = self._filter_result(result, filter_functions)

        return sorted(result, key=lambda p: p.created, reverse=True)
538407
def _dict_from_path(path, val, delimiter=DEFAULT_TARGET_DELIM):
    '''
    
    '''
    nested_dict = _infinitedict()
    keys = path.rsplit(delimiter)
    lastplace = reduce(operator.getitem, keys[:-1], nested_dict)
    lastplace[keys[-1]] = val

    return nested_dict
254528
function getPostPaths (dir) {
  return fs.readdir(dir).then(function (files) {
    return all(files.map(function (file) {
      var path = pathify(dir, file);
      return fs.stat(path).then(function (stats) {
        return stats.isDirectory() ?
          getPostPaths(path) :
          path;
      });
    }));
  }).then(function (files) {
    return _.flatten(files);
  });
}
1248453
function paramsFromStringPath(path, paramsObj) {
        //Get all the parameter names from the path.
        var elements = path.split('/');
        var params = elements.reduce(function(params, element) {
            if (element.charAt(0) === ':') {
                var paramName = element.slice(1);
                params.push(paramsObj[paramName]);
            }
            return params;
        }, []);
        return params;
    }
716354
def path_data(self, variable_data, path):
        
        # NOTE: tcex does include the jmespath library as a dependencies since it is only
        # required for local testing.
        try:
            import jmespath
        except ImportError:
            print('Could not import jmespath module (try "pip install jmespath").')
            sys.exit(1)

        if isinstance(variable_data, string_types):
            # try to convert string into list/dict before using expression
            try:
                variable_data = json.loads(variable_data)
            except Exception:
                self.log.debug('String value ({}) could not JSON serialized.'.format(variable_data))
        if path is not None and isinstance(variable_data, (dict, list)):
            expression = jmespath.compile(path)
            variable_data = expression.search(
                variable_data, jmespath.Options(dict_cls=collections.OrderedDict)
            )
        return variable_data
937305
def internal_get_variable_json(py_db, request):
    '''
        
    '''
    arguments = request.arguments  # : :type arguments: VariablesArguments
    variables_reference = arguments.variablesReference
    fmt = arguments.format
    if hasattr(fmt, 'to_dict'):
        fmt = fmt.to_dict()

    variables = []
    try:
        variable = py_db.suspended_frames_manager.get_variable(variables_reference)
    except KeyError:
        pass
    else:
        for child_var in variable.get_children_variables(fmt=fmt):
            variables.append(child_var.get_var_data(fmt=fmt))

    body = VariablesResponseBody(variables)
    variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
    py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True))
1210750
function process_post(request, response, uri, body) {
	if (!authorised(request))
		return fail(401, "unauthorized", response);

	// be safe
	if (body === undefined)
		body = null;
		
	let path = URL.parse(request.url).pathname;

	// does path start with /things/thingID for some thingID?

	if (/^\/things\/.+/.test(path)) {
		path = path.substr(8);
		
		let i = path.indexOf('/');
		var thingID;
		
		if (i < 0) {
			thingID = path;
			path = "";
		} else {
			thingID = path.substr(0, i);
			path = path.substr(i);
		}
		
		if (thingID) {
			let thing = things[thingID];
			
			if (!thing)
				return fail(404, "unknown thing: " + thingID, response);
				
			// /things/thingID/properties to update all properties
			// /things/thingID/properties/propName to update given property
			
			if (path === "/properties") {
				// update properties from request body
				
				try {
					let values = JSON.parse(body);
					if (typeof values != 'object')
						return fail(555, "invalid data", response);
					
					// fail if any of the values are invalid or readonly
					for (var name in values) {
						if (values.hasOwnProperty(name)) {
							let value = values[name];
							let property = thing.properties[name];
							
							if (property === undefined)
								return fail(404, "unknown property name: " + name, response);

							if (property.meta) {
								if (property.meta.writable !== undefined  && !property.meta.writable)
									return fail(405, "read-only", response);
							
								if (invalid(value, property.meta, thing))
									return fail(400, "invalid data", response);
							}							
						}
					}
					
					// all values are good so update and notify
					for (var name in values) {
						if (values.hasOwnProperty(name)) {
							let value = values[name];
							let property = thing.properties[name];
							
							if (property != undefined) {
								property.value = value;
								
								// notify exposing app of external change
								if (property.handler)
									property.handler(value);
							}
						}
					}
					
					thing.emitState(values); // notify all clients
					// *** need to validate against model's data type ***
					// *** need to notify clients ***
					return succeed(204, "no data", response);
				} catch (err) {
					return fail(404, "invalid: " + body, response);
				}
			} else if (/^\/properties\/.+/.test(path)) {
				path = path.substr(12);
				console.log("property name: " + path);
				let property = thing.properties[path];
				
				if (property === undefined)
					return fail(404, "unknown property: " + path, response);
					
				console.log('parsing request body');
					
				// update named property from request body
				try {
					let value = JSON.parse(body);
					
					if (property.meta) {
						if (property.meta.writable !== undefined  && !property.meta.writable)
							return fail(405, "read-only", response);

						if (invalid(value, property.meta, thing)) {
							console.log('failed to set ' + path + ' to ' + value);
							return fail(400, "invalid data", response);
						}
					}

					property.value = value;
					
					// notify exposing app of external change
					if (property.handler)
						property.handler(value);
									
					console.log('setting ' + property.name + ' to ' + value);
					console.log('calling emitValue with path = ' + path + ' and value = ' + value);
					thing.emitValue(path, value);
					// *** need to validate against model's data type ***
					// *** need to notify clients ***
					console.log('succeeded in setting ' + property.name + ' to ' + property.value);
					return succeed(204, "no data", response);
				} catch (err) {
					console.log('failed to parse request body');
					return fail(404, "invalid: " + body, response);
				}
			}
			
			// /things/thingID/actions/actName to invoke given action (POST only)
			
			if (/^\/actions\/.+/.test(path)) {
				path = path.substr(9);
				//console.log("action name: " + path);
				
				let action = thing.actions[path];
				
				if (action === undefined)
					return fail(404, "unknown action: " + path, response);
					
				// *** need to validate input data against model's data type
				let input = null;
				
				//console.log(" input body is: " + JSON.stringify(body));
				
				if (body !== undefined) {
					try {
						input = JSON.parse(body);
					} catch (err) {
						return fail(404, "invalid: " + body, response);
					}
				}
				
				if (action.meta && action.meta.input && invalid(input, action.meta.input, thing))
					return fail(400, "invalid input", response);
					
				if (action.handler === undefined) {
					// succeed immediately as nothing to be done
					console.log('action ' + action.name + ' has no handler');
					return succeed(204, "no data", response);
				} else {
					//console.log('ready to invoke handler for action ' + action.name);
					// invoke handler and use promise to deliver response
					// after testing response against model's data type
					action.handler(input).then(output => {
						if (action.meta && action.meta.output && invalid(output, action.meta.output, thing)) {
							console.log(output + ' is invalid');
							return fail(400, "invalid output", response);
						}
						let body = JSON.stringify(output, null, 4);
						
						console.log('output body is ' + body);
						
						if (body === undefined) {
							console.log('body is undefined');
							response.writeHead(204, {
								'Content-Type': mime_types.json,
								'Pragma': 'no-cache',
								'Cache-Control': 'no-cache',
								'Access-Control-Allow-Origin': '*'
							});
						} else {
							response.writeHead(200, {
								'Content-Type': mime_types.json,
								'Pragma': 'no-cache',
								'Cache-Control': 'no-cache',
								'Access-Control-Allow-Origin': '*',
								'Content-Length': body.length
							});
							response.write(body);
						}
						
						response.end();
						return;
					}).catch(err => {
						console.log('handler failed: ' + err);
						return fail(500, "action failed: " + err, response);
					});
					
					return;  // deferred response
				}
			}
		}
		
		return fail(404, "missing thingID: " + uri.path, response);
	}
}
1209745
function getUrlParams(path) {
    if (!path) {
      return {};
    }
    var bits = path.split('?');
    var querystring = bits.length > 1 ? bits[1] : '';
    return toObject(querystring);
  }
60745
function convertPaths(path) {
  var pathTemplate = new URITemplate(path).parse(), // must call parse to populate parts
    expressPath = '';

  _.forEach(pathTemplate.parts, function (part) {
    switch (typeof part) {
      case 'string':
        if (part.length > 0) {
          expressPath += part;
        }
        break;
      case 'object':
        if (part.expression.length > 0 && part.expression.match(PATH_REGEX)) {
          expressPath += ':' + _.first(part.variables).name;
        }
        break;
      default:
      // TODO throw error
    }
  });

  return expressPath;
}
528083
def dict(self):
        
        post_dict = {
            'id': self.id,
            'link': self.link,
            'permalink': self.permalink,
            'content_type': self.content_type,
            'slug': self.slug,
            'updated': self.updated, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT),
            'published': self.published, #.strftime(conf.GOSCALE_ATOM_DATETIME_FORMAT),
            'title': self.title,
            'description': self.description,
            'author': self.author,
            'categories': self.categories[1:-1].split(',') if self.categories else None,
            'summary': self.summary,
            }
        if self.attributes:
            attributes = simplejson.loads(self.attributes)
            post_dict.update(attributes)
        return post_dict
1364324
def get_variables_path(export_dir):
  """"""
  return os.path.join(
      tf.compat.as_bytes(export_dir),
      tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_DIRECTORY),
      tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_FILENAME))
789779
async def post(self) -> 'MultiDictProxy[Union[str, bytes, FileField]]':
        """"""
        if self._post is not None:
            return self._post
        if self._method not in self.POST_METHODS:
            self._post = MultiDictProxy(MultiDict())
            return self._post

        content_type = self.content_type
        if (content_type not in ('',
                                 'application/x-www-form-urlencoded',
                                 'multipart/form-data')):
            self._post = MultiDictProxy(MultiDict())
            return self._post

        out = MultiDict()  # type: MultiDict[Union[str, bytes, FileField]]

        if content_type == 'multipart/form-data':
            multipart = await self.multipart()
            max_size = self._client_max_size

            field = await multipart.next()
            while field is not None:
                size = 0
                content_type = field.headers.get(hdrs.CONTENT_TYPE)

                if field.filename:
                    # store file in temp file
                    tmp = tempfile.TemporaryFile()
                    chunk = await field.read_chunk(size=2**16)
                    while chunk:
                        chunk = field.decode(chunk)
                        tmp.write(chunk)
                        size += len(chunk)
                        if 0 < max_size < size:
                            raise HTTPRequestEntityTooLarge(
                                max_size=max_size,
                                actual_size=size
                            )
                        chunk = await field.read_chunk(size=2**16)
                    tmp.seek(0)

                    ff = FileField(field.name, field.filename,
                                   cast(io.BufferedReader, tmp),
                                   content_type, field.headers)
                    out.add(field.name, ff)
                else:
                    value = await field.read(decode=True)
                    if content_type is None or \
                            content_type.startswith('text/'):
                        charset = field.get_charset(default='utf-8')
                        value = value.decode(charset)
                    out.add(field.name, value)
                    size += len(value)
                    if 0 < max_size < size:
                        raise HTTPRequestEntityTooLarge(
                            max_size=max_size,
                            actual_size=size
                        )

                field = await multipart.next()
        else:
            data = await self.read()
            if data:
                charset = self.charset or 'utf-8'
                out.extend(
                    parse_qsl(
                        data.rstrip().decode(charset),
                        keep_blank_values=True,
                        encoding=charset))

        self._post = MultiDictProxy(out)
        return self._post
417900
def json_post(methodname, rtype, key):
    """"""
    return compose(
        reusable,
        map_return(registry(rtype), itemgetter(key)),
        basic_interaction,
        map_yield(partial(_json_as_post, methodname)),
        oneyield,
    )
306998
def to_postdata(self):
        """"""
        items = []
        for k, v in sorted(self.items()):  # predictable for testing
            items.append((k.encode('utf-8'), to_utf8_optional_iterator(v)))

        # tell urlencode to deal with sequence values and map them correctly
        # to resulting querystring. for example self["k"] = ["v1", "v2"] will
        # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
        return urlencode(items, True).replace('+', '%20').encode('ascii')
924656
def dotopdict(self, dict_):
        
        mlookup = {'get':'GET', 'post':'POST'}
        def rearrange(path, method_dict, method):
            oid = method_dict['operationId']
            self._paths[oid] = path
            method_dict['nickname'] = oid
            method_dict['method'] = mlookup[method]

        paths = dict_['paths']
        for path, path_dict in paths.items():
            if self.path_prefix and self.path_prefix not in path:
                continue
            path_dict['operations'] = []
            for method, method_dict in sorted(path_dict.items()):
                if method == 'operations':
                    continue
                rearrange(path, method_dict, method)
                #print(self.operation(method_dict))
                path_dict['operations'].append(method_dict)
            path_dict['path'] = path

        def setp(v, lenp=len(self.path_prefix)):
            v['path'] = v['path'][lenp:]
            return v

        dict_['apis'] = []
        for tag_dict in dict_['tags']:
            path = '/' + tag_dict['name']
            d = {'path':path,
                 'description':tag_dict['description'],
                 'class_json':{
                     'docstring':tag_dict['description'],
                     'resourcePath':path,
                     'apis':[setp(v) for k, v in paths.items()
                             if k.startswith(self.path_prefix + path)]},
            }
            dict_['apis'].append(d)

        # make sure this is run first so we don't get key errors
        self._swagger(dict_['swagger'])
        self._info(dict_['info'])
        self._definitions(dict_['definitions'])

        return dict_
790054
def post_public_key(self, path, data, is_json=True):
        ''''''
        post_data = {
            'public_key': self.public_key
        }
        post_data.update(data)
        return self._post(path, post_data, is_json)