file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
render.py | import collections
import random
import pyglet
from entity import Component
from fov import InFOV
from generator import LayoutGenerator
from hud import HUD
from light import LightOverlay
from message import LastMessagesView
from position import Position
from temp import floor_tex, get_wall_tex, dungeon_te... |
else:
continue
# always add floor, because we wanna draw walls above floor
vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2))
tex_coords.extend(floor_tex.tex_coords)
if tile == LayoutGenerator.TILE_WALL:
... | renderable = entity.get(LayoutRenderable)
if renderable:
tile = renderable.tile
break | conditional_block |
render.py | import collections
import random
import pyglet
from entity import Component
from fov import InFOV
from generator import LayoutGenerator
from hud import HUD
from light import LightOverlay
from message import LastMessagesView
from position import Position
from temp import floor_tex, get_wall_tex, dungeon_te... | (Component):
COMPONENT_NAME = 'layout_renderable'
def __init__(self, tile):
self.tile = tile
class RenderSystem(object):
zoom = 3
GROUP_LEVEL = pyglet.graphics.OrderedGroup(0)
GROUP_DIGITS = pyglet.graphics.OrderedGroup(1)
GROUP_HUD = pyglet.graphics.OrderedGroup(2)
... | LayoutRenderable | identifier_name |
hashsplit.go | // Package hashsplit implements content-based splitting of byte streams.
package hashsplit
import (
"errors"
"io"
"math/bits"
"github.com/chmduquesne/rollinghash/buzhash32"
)
const (
defaultSplitBits = 13
windowSize = 64
defaultMinSize = windowSize
)
// Splitter hashsplits a byte sequence into chunks... | (r io.Reader, f func([]byte, uint) error) error {
s := NewSplitter(f)
_, err := io.Copy(s, r)
if err != nil {
return err
}
return s.Close()
}
// NewSplitter produces a new Splitter with the given callback.
// The Splitter is an io.WriteCloser.
// As bytes are written to it,
// it finds chunk boundaries and call... | Split | identifier_name |
hashsplit.go | // Package hashsplit implements content-based splitting of byte streams.
package hashsplit
import (
"errors"
"io"
"math/bits"
"github.com/chmduquesne/rollinghash/buzhash32"
)
const (
defaultSplitBits = 13
windowSize = 64
defaultMinSize = windowSize
)
// Splitter hashsplits a byte sequence into chunks... |
num := n.NumChildren()
if num == 0 {
return n, nil
}
// TODO: if a Node kept track of its children's offsets,
// this loop could be replaced with a sort.Search call.
for i := 0; i < num; i++ {
child, err := n.Child(i)
if err != nil {
return nil, err
}
if pos >= (child.Offset() + child.Size()) {
... | {
return nil, ErrNotFound
} | conditional_block |
hashsplit.go | // Package hashsplit implements content-based splitting of byte streams.
package hashsplit
import (
"errors"
"io"
"math/bits"
"github.com/chmduquesne/rollinghash/buzhash32"
)
const (
defaultSplitBits = 13
windowSize = 64
defaultMinSize = windowSize
)
// Splitter hashsplits a byte sequence into chunks... |
// Root produces the root of the tree after all nodes have been added with calls to Add.
// Root may only be called one time.
// If the tree is empty,
// Root returns a nil Node.
// It is an error to call Add after a call to Root.
//
// The return value of Root is the interface type Node.
// If tb.F is nil, the concr... | {
if len(tb.levels) == 0 {
tb.levels = []*TreeBuilderNode{new(TreeBuilderNode)}
}
tb.levels[0].Chunks = append(tb.levels[0].Chunks, bytes)
for _, n := range tb.levels {
n.size += uint64(len(bytes))
}
for i := uint(0); i < level; i++ {
if i == uint(len(tb.levels))-1 {
tb.levels = append(tb.levels, &TreeBu... | identifier_body |
hashsplit.go | // Package hashsplit implements content-based splitting of byte streams.
package hashsplit
import (
"errors"
"io"
"math/bits"
"github.com/chmduquesne/rollinghash/buzhash32"
)
const (
defaultSplitBits = 13
windowSize = 64
defaultMinSize = windowSize
)
// Splitter hashsplits a byte sequence into chunks... | var n Node = tb.levels[i]
if tb.F != nil {
var err error
n, err = tb.F(tb.levels[i])
if err != nil {
return nil, err
}
}
tb.levels[i+1].Nodes = append(tb.levels[i+1].Nodes, n)
tb.levels[i] = nil // help the gc reclaim memory sooner, maybe
}
}
// Don't necessarily return the high... | return nil, nil
}
if len(tb.levels[0].Chunks) > 0 {
for i := 0; i < len(tb.levels)-1; i++ { | random_line_split |
bigrand.rs | //! Randomization of big integers
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use rand::Rng;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::big_digit::BigDigit;
use crate::bigint::{into_magnitude, magnitude};
use crate::integer::Intege... | <R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
&self.base + BigInt::from(rng.gen_biguint_below(&self.len))
}
#[inline]
fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> ... | sample | identifier_name |
bigrand.rs | //! Randomization of big integers
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use rand::Rng;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::big_digit::BigDigit;
use crate::bigint::{into_magnitude, magnitude};
use crate::integer::Intege... |
}
| {
if bit_size < 2 {
panic!("prime size must be at least 2-bit");
}
let mut b = bit_size % 8;
if b == 0 {
b = 8;
}
let bytes_len = (bit_size + 7) / 8;
let mut bytes = vec![0u8; bytes_len];
loop {
self.fill_bytes(&mut b... | identifier_body |
bigrand.rs | //! Randomization of big integers
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use rand::Rng;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::big_digit::BigDigit;
use crate::bigint::{into_magnitude, magnitude};
use crate::integer::Intege... | lazy_static! {
/// The product of the values in SMALL_PRIMES and allows us
/// to reduce a candidate prime by this number and then determine whether it's
/// coprime to all the elements of SMALL_PRIMES without further BigUint
/// operations.
static ref SMALL_PRIMES_PRODUCT: BigUint = BigUint::from_u... | /// odd by construction.
#[cfg(feature = "prime")]
const SMALL_PRIMES: [u8; 15] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
#[cfg(feature = "prime")] | random_line_split |
bigrand.rs | //! Randomization of big integers
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use rand::Rng;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::big_digit::BigDigit;
use crate::bigint::{into_magnitude, magnitude};
use crate::integer::Intege... | else {
// Here b==1, because b cannot be zero.
bytes[0] |= 1;
if bytes_len > 1 {
bytes[1] |= 0x80;
}
}
// Make the value odd since an even number this large certainly isn't prime.
bytes[bytes_len - ... | {
bytes[0] |= 3u8.wrapping_shl(b as u32 - 2);
} | conditional_block |
cartracker.py | import numpy as np
import cv2
import time
from matplotlib import pyplot as plt
import imutils
from collections import deque
import argparse
import pandas as pd
import random
cap = cv2.VideoCapture('cardi.MP4')
ap = argparse.ArgumentParser()
| # create background subtractor
fgbg = cv2.createBackgroundSubtractorMOG2()
# where the centroids will be stored
pts = deque(maxlen=args["buffer"])
counter = 0
(dX, dY) = (0, 0)
direction = ""
#setting variables before the image processing
frames_count, fps, width, height = cap.get(cv2.CAP_PROP_FRAME_COUNT), cap.get... | #arguments to start with
ap.add_argument("-b", "--buffer", type=int, default=5000,
help="max buffer size")
args = vars(ap.parse_args())
| random_line_split |
cartracker.py | import numpy as np
import cv2
import time
from matplotlib import pyplot as plt
import imutils
from collections import deque
import argparse
import pandas as pd
import random
cap = cv2.VideoCapture('cardi.MP4')
ap = argparse.ArgumentParser()
#arguments to start with
ap.add_argument("-b", "--buffer", type=int, defaul... |
#drawing hte current centroid
cxx = cxx[cxx != 0]
cyy = cyy[cyy != 0]
minx_index2 = []
miny_index2 = []
maxrad = 30
# if there are centroids in the specified area
if len(cxx):
if not carids: # if carids is empty
# loops through all cent... | if pts[i - 1] is None or pts[i] is None:
continue
# draw the centroid tracker
cv2.circle(image, (pts[i - 1]), 2, (0,0,255), -1) | conditional_block |
util.go | package cloudformation
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/lambda"
gocf "github.com/crewjam/go-cloudformation"
sparta "... |
// TODO - fetch the template and look up the resources
existingVersions, existingVersionsErr := existingLambdaResourceVersions(serviceName,
lambdaResourceName,
session,
logger)
if nil != existingVersionsErr {
return nil, existingVersionsErr
}
// Initialize the auto incrementing version struct
autoIncre... | {
return nil, existingStackDefinitionErr
} | conditional_block |
util.go | package cloudformation
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/lambda"
gocf "github.com/crewjam/go-cloudformation"
sparta "... | (data map[string]interface{}) (*gocf.StringExpr, error) {
if len(data) <= 0 {
return nil, fmt.Errorf("FnJoinExpr data is empty")
}
for eachKey, eachValue := range data {
switch eachKey {
case "Ref":
return gocf.Ref(eachValue.(string)).String(), nil
case "Fn::GetAtt":
attrValues, attrValuesErr := toExpr... | parseFnJoinExpr | identifier_name |
util.go | package cloudformation
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/lambda"
gocf "github.com/crewjam/go-cloudformation"
sparta "... |
// MapToResourceTags transforms a go map[string]string to a CloudFormation-compliant
// Tags representation. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html
func MapToResourceTags(tagMap map[string]string) []interface{} {
var tags []interface{}
for eachKey, eachV... | {
arnParts := []gocf.Stringable{gocf.String("arn:aws:s3:::")}
switch bucket.(type) {
case string:
// Don't be smart if the Arn value is a user supplied literal
arnParts = append(arnParts, gocf.String(bucket.(string)))
case *gocf.StringExpr:
arnParts = append(arnParts, bucket.(*gocf.StringExpr))
case gocf.Re... | identifier_body |
util.go | package cloudformation
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/lambda"
gocf "github.com/crewjam/go-cloudformation"
sparta "... | }
// Get the current template - for each version we find in the version listing
// we look up the actual CF resource and copy it into this template
existingStackDefinition, existingStackDefinitionErr := existingStackTemplate(serviceName,
session,
logger)
if nil != existingStackDefinitionErr {
return nil, ex... | session, sessionErr := session.NewSession()
if sessionErr != nil {
return nil, sessionErr | random_line_split |
gravity.js | // Gravity.js
// Responsive framework for intuitive and easy web design
/*
The semi-colon before the function invocation is a safety net against
concatenated scripts and/or other plugins which may not be closed properly.
"undefined" is used because the undefined global variable in ECMAScript 3
is mut... | ( element, options ) {
/*
Provide local access to the DOM node(s) that called the plugin,
as well local access to the plugin name and default options.
*/
this.element = element;
this._name = pluginName;
this._defaults = $.fn.gravity.defaults;
/*
... | Plugin | identifier_name |
gravity.js | // Gravity.js
// Responsive framework for intuitive and easy web design
/*
The semi-colon before the function invocation is a safety net against
concatenated scripts and/or other plugins which may not be closed properly.
"undefined" is used because the undefined global variable in ECMAScript 3
is mut... |
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
// Initialization logic
init: function () {
/*
Create additional methods below and call them via
"this.myFunction(arg1, arg2)", ie: "this.buildCache();".
Note, you can... | {
/*
Provide local access to the DOM node(s) that called the plugin,
as well local access to the plugin name and default options.
*/
this.element = element;
this._name = pluginName;
this._defaults = $.fn.gravity.defaults;
/*
The "$.exte... | identifier_body |
gravity.js | // Gravity.js
// Responsive framework for intuitive and easy web design
/*
The semi-colon before the function invocation is a safety net against
concatenated scripts and/or other plugins which may not be closed properly.
"undefined" is used because the undefined global variable in ECMAScript 3
is mut... | else{
group.data.padding = {
top: group.data.aHeight - group.data.gHeight
};
}
$(group.parent).css({
'padding-top': group.data.padding.top
});
// apply to DOM
... | {
group.data.padding = {
top: delta.top - group.data.offset.top
};
} | conditional_block |
gravity.js | // Gravity.js
// Responsive framework for intuitive and easy web design
/*
The semi-colon before the function invocation is a safety net against
concatenated scripts and/or other plugins which may not be closed properly.
"undefined" is used because the undefined global variable in ECMAScript 3
is mut... | instances of the plugin.
More: http://api.jquery.com/jquery.extend/
*/
this.options = $.extend( {}, this._defaults, options );
/*
The "init" method is the starting point for all plugin logic.
Calling the init method here in the "Plugin" construct... | empty so that we don't alter the default options for future | random_line_split |
lsfiles.go | package git
import (
"fmt"
"io/ioutil"
"log"
"path"
"path/filepath"
"sort"
"strings"
)
// Finds things that aren't tracked, and creates fake IndexEntrys for them to be merged into
// the output if --others is passed.
func findUntrackedFilesFromDir(c *Client, opts LsFilesOptions, root, parent, dir File, tracked... |
}
fs = append(fs, LsFilesResult{file, '?'})
}
}
sort.Sort(lsByPath(fs))
return fs, nil
}
// Implement the sort interface on *GitIndexEntry, so that
// it's easy to sort by name.
type lsByPath []LsFilesResult
func (g lsByPath) Len() int { return len(g) }
func (g lsByPath) Swap(i, j int) { g[i], g[j] ... | {
continue
} | conditional_block |
lsfiles.go | package git
import (
"fmt"
"io/ioutil"
"log"
"path"
"path/filepath"
"sort"
"strings"
)
// Finds things that aren't tracked, and creates fake IndexEntrys for them to be merged into
// the output if --others is passed.
func findUntrackedFilesFromDir(c *Client, opts LsFilesOptions, root, parent, dir File, tracked... | () int { return len(g) }
func (g lsByPath) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
func (g lsByPath) Less(i, j int) bool {
if g[i].PathName == g[j].PathName {
return g[i].Stage() < g[j].Stage()
}
ibytes := []byte(g[i].PathName)
jbytes := []byte(g[j].PathName)
for k := range ibytes {
if k >= len(jbytes)... | Len | identifier_name |
lsfiles.go | package git
import (
"fmt"
"io/ioutil"
"log"
"path"
"path/filepath"
"sort"
"strings"
)
// Finds things that aren't tracked, and creates fake IndexEntrys for them to be merged into
// the output if --others is passed.
func findUntrackedFilesFromDir(c *Client, opts LsFilesOptions, root, parent, dir File, tracked... |
// Describes the options that may be specified on the command line for
// "git diff-index". Note that only raw mode is currently supported, even
// though all the other options are parsed/set in this struct.
type LsFilesOptions struct {
// Types of files to show
Cached, Deleted, Modified, Others bool
// Invert ex... | {
files, err := ioutil.ReadDir(dir.String())
if err != nil {
return nil
}
for _, ignorefile := range opts.ExcludePerDirectory {
ignoreInDir := ignorefile
if dir != "" {
ignoreInDir = dir + "/" + ignorefile
}
if ignoreInDir.Exists() {
log.Println("Adding excludes from", ignoreInDir)
patterns, er... | identifier_body |
lsfiles.go | package git
import (
"fmt"
"io/ioutil"
"log"
"path"
"path/filepath"
"sort"
"strings"
)
// Finds things that aren't tracked, and creates fake IndexEntrys for them to be merged into
// the output if --others is passed.
func findUntrackedFilesFromDir(c *Client, opts LsFilesOptions, root, parent, dir File, tracked... | return nil
}
for _, ignorefile := range opts.ExcludePerDirectory {
ignoreInDir := ignorefile
if dir != "" {
ignoreInDir = dir + "/" + ignorefile
}
if ignoreInDir.Exists() {
log.Println("Adding excludes from", ignoreInDir)
patterns, err := ParseIgnorePatterns(c, ignoreInDir, dir)
if err != nil ... | files, err := ioutil.ReadDir(dir.String())
if err != nil { | random_line_split |
plot_all_sampled_days.py | # with centroid and angle displayed
import mpl_toolkits.basemap as bm
from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset as NetCDFFile
import numpy as np
import matplotlib.pyplot as plt
import sys,os
cwd=os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd+'/../../MetBot')
sys.path.append(cwd+'/.... | # To plot a maps for flagged CB days
# after selection based on angle and centroid
#
# plotted over a larger domain | random_line_split | |
plot_all_sampled_days.py | # To plot a maps for flagged CB days
# after selection based on angle and centroid
#
# plotted over a larger domain
# with centroid and angle displayed
import mpl_toolkits.basemap as bm
from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset as NetCDFFile
import numpy as np
import matplotlib.pyplot as... |
elif dsets=='spec': # edit for the dset you want
#ndset=1
#dsetnames=['ncep']
ndset=1
dsetnames=['cmip5']
ndstr=str(ndset)
for d in range(ndset):
dset=dsetnames[d]
dcnt=str(d+1)
print 'Running on '+dset
print 'This is dset '+dcnt+' of '+ndstr+' in list'
outdir=thisdir+'/'+dset+'/'... | ndset=len(dset_mp.dset_deets)
dsetnames=list(dset_mp.dset_deets) | conditional_block |
lib.rs | //!
//! Dynamic, plugin-based [Symbol](https://en.wikipedia.org/wiki/Symbol_(programming)) abstraction.
//!
//! A [Symbol] can be used as an _identifier_ in place of the more primitive workhorse [String].
//! There could be multiple reasons to do so:
//!
//! 1. Mixing of different domains in the same runtime code
//! 2... | f,
"{}::{}",
instance.namespace_name(),
instance.symbol_name()
)
}
}
}
}
impl PartialEq for Symbol {
fn eq(&self, rhs: &Symbol) -> bool {
match (self, rhs) {
(Self::Static(thi... | Self::Static(ns, id) => {
write!(f, "{}::{}", ns.namespace_name(), ns.symbol_name(*id))
}
Self::Dynamic(instance) => {
write!( | random_line_split |
lib.rs | //!
//! Dynamic, plugin-based [Symbol](https://en.wikipedia.org/wiki/Symbol_(programming)) abstraction.
//!
//! A [Symbol] can be used as an _identifier_ in place of the more primitive workhorse [String].
//! There could be multiple reasons to do so:
//!
//! 1. Mixing of different domains in the same runtime code
//! 2... |
#[test]
fn test_inequality() {
let test_state = TestState::new();
test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1);
test_state.assert_full_ne(&STATIC_A_0, &STATIC_B_0);
test_state.assert_full_ne(&dynamic::sym0("foo"), &dynamic::sym0("bar"));
test_state.assert_full_... | {
let test_state = TestState::new();
test_state.assert_full_eq(&STATIC_A_0, &STATIC_A_0);
test_state.assert_full_eq(&STATIC_A_1, &STATIC_A_1);
test_state.assert_full_eq(&STATIC_B_0, &STATIC_B_0);
test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1);
test_state.assert_ful... | identifier_body |
lib.rs | //!
//! Dynamic, plugin-based [Symbol](https://en.wikipedia.org/wiki/Symbol_(programming)) abstraction.
//!
//! A [Symbol] can be used as an _identifier_ in place of the more primitive workhorse [String].
//! There could be multiple reasons to do so:
//!
//! 1. Mixing of different domains in the same runtime code
//! 2... | () {
let test_state = TestState::new();
test_state.assert_full_eq(&STATIC_A_0, &STATIC_A_0);
test_state.assert_full_eq(&STATIC_A_1, &STATIC_A_1);
test_state.assert_full_eq(&STATIC_B_0, &STATIC_B_0);
test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1);
test_state.assert_... | test_equality | identifier_name |
xapian_backend.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import copy
import xapian
import cPickle as pickle
import simplejson as json
import pymongo
import scws
import datetime
import calendar
from itertools import product
from argparse import ArgumentParser
SCWS_ENCODING = 'utf-8'
SCWS_RULES = '/usr/local... | start_time = self.folders_with_date[0][0]
end_time = start_time + datetime.timedelta(days=50)
weibos = self.db.statuses.find({
self.schema['posted_at_key']: {
'$gte': calendar.timegm(start_time.timetuple()),
'$lt': calendar.timegm(end_ti... | n self.databases[folder]
#@profile
def load_and_index_weibos(self, start_time=None):
if not debug and start_time:
| identifier_body |
xapian_backend.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import copy
import xapian
import cPickle as pickle
import simplejson as json
import pymongo
import scws
import datetime
import calendar
from itertools import product
from argparse import ArgumentParser
SCWS_ENCODING = 'utf-8'
SCWS_RULES = '/usr/local... | return QCombination(operation, [self, other])
@property
def empty(self):
return False
def __or__(self, other):
return self._combine(other, self.OR)
def __and__(self, other):
return self._combine(other, self.AND)
def __xor__(self, other):
return self._combi... | if self.empty:
return other
| random_line_split |
xapian_backend.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import copy
import xapian
import cPickle as pickle
import simplejson as json
import pymongo
import scws
import datetime
import calendar
from itertools import product
from argparse import ArgumentParser
SCWS_ENCODING = 'utf-8'
SCWS_RULES = '/usr/local... | (self):
self.emotion_words = [line.strip('\r\n') for line in file(EXTRA_EMOTIONWORD_PATH)]
def load_scws(self):
s = scws.Scws()
s.set_charset(SCWS_ENCODING)
s.set_dict(CHS_DICT_PATH, scws.XDICT_MEM)
s.add_dict(CHT_DICT_PATH, scws.XDICT_MEM)
s.add_dict(CUSTOM_DICT_PA... | load_extra_dic | identifier_name |
xapian_backend.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import copy
import xapian
import cPickle as pickle
import simplejson as json
import pymongo
import scws
import datetime
import calendar
from itertools import product
from argparse import ArgumentParser
SCWS_ENCODING = 'utf-8'
SCWS_RULES = '/usr/local... | dd_argument('-p', '--print_folders', action='store_true', help='PRINT FOLDER THEN EXIT')
parser.add_argument('-s', '--start_time', nargs=1, help='DATETIME')
parser.add_argument('dbpath', help='PATH_TO_DATABASE')
args = parser.parse_args(sys.argv[1:])
debug = args.debug
dbpath = args.dbpath
if a... | conditional_block | |
y.go | //line numbers.y:2
package main
import __yyfmt__ "fmt"
//line numbers.y:2
//line numbers.y:5
type yySymType struct {
yys int
expr *Expr
exprlist []*Expr
stmt *Stmt
stmtlist []*Stmt
tok int
op Op
line Line
}
const _LE = 57346
const _GE = 57347
const _EQ = 57348
const _NE = 57349
co... | {
var yyn int
var yylval yySymType
var yyVAL yySymType
yyS := make([]yySymType, yyMaxDepth)
Nerrs := 0 /* number of errors */
Errflag := 0 /* error recovery flag */
yystate := 0
yychar := -1
yyp := -1
goto yystack
ret0:
return 0
ret1:
return 1
yystack:
/* put a state and value onto the stack */
if y... | identifier_body | |
y.go | //line numbers.y:2
package main
import __yyfmt__ "fmt"
//line numbers.y:2
//line numbers.y:5
type yySymType struct {
yys int
expr *Expr
exprlist []*Expr
stmt *Stmt
stmtlist []*Stmt
tok int
op Op
line Line
}
const _LE = 57346
const _GE = 57347
const _EQ = 57348
const _NE = 57349
co... |
2, -2, 1, 3, 4, 5, 0, 0, 0, 0,
0, 10, 11, 0, 0, 0, 0, 12, 0, 0,
0, 0, 0, 0, 28, 0, 0, 6, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 24,
0, 0, 0, 0, 0, 0, 0, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 13, 0, 0,
0, 7, 29, 8, 9, 25, 26, 0, 0, 0,
0, 27,
}
var yyTok1 = []int{
1, 3, 3, 3, 3, 3, 3, 3, 3, 3,
25, 3, 3, 3, 3, 3, ... | }
var yyDef = []int{ | random_line_split |
y.go | //line numbers.y:2
package main
import __yyfmt__ "fmt"
//line numbers.y:2
//line numbers.y:5
type yySymType struct {
yys int
expr *Expr
exprlist []*Expr
stmt *Stmt
stmtlist []*Stmt
tok int
op Op
line Line
}
const _LE = 57346
const _GE = 57347
const _EQ = 57348
const _NE = 57349
co... | (lex yyLexer, lval *yySymType) int {
c := 0
char := lex.Lex(lval)
if char <= 0 {
c = yyTok1[0]
goto out
}
if char < len(yyTok1) {
c = yyTok1[char]
goto out
}
if char >= yyPrivate {
if char < yyPrivate+len(yyTok2) {
c = yyTok2[char-yyPrivate]
goto out
}
}
for i := 0; i < len(yyTok3); i += 2 {
... | yylex1 | identifier_name |
y.go | //line numbers.y:2
package main
import __yyfmt__ "fmt"
//line numbers.y:2
//line numbers.y:5
type yySymType struct {
yys int
expr *Expr
exprlist []*Expr
stmt *Stmt
stmtlist []*Stmt
tok int
op Op
line Line
}
const _LE = 57346
const _GE = 57347
const _EQ = 57348
const _NE = 57349
co... |
/* look through exception table */
xi := 0
for {
if yyExca[xi+0] == -1 && yyExca[xi+1] == yystate {
break
}
xi += 2
}
for xi += 2; ; xi += 2 {
yyn = yyExca[xi+0]
if yyn < 0 || yyn == yychar {
break
}
}
yyn = yyExca[xi+1]
if yyn < 0 {
goto ret0
}
}
if yyn == 0 {
/* er... | {
yychar = yylex1(yylex, &yylval)
} | conditional_block |
mod.rs | use futures::{select, StreamExt};
use log::{debug, error, info, warn};
use std::collections::HashMap;
use std::sync::RwLock;
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::mpsc::{self, UnboundedSender};
mod trace;
use crate::protocol::{Message, MessageBody, TryIntoMessage};
use crate::{Broker, Error,... | },
};
}
if pending_tasks > 0 {
// Warm shutdown loop. When there are still pendings tasks we wait for them
// to finish. We get updates about pending tasks through the `event_rx` channel.
// We also watch for a second SIGINT, in which case... | TaskStatus::Pending => pending_tasks += 1,
TaskStatus::Finished => pending_tasks -= 1,
};
} | random_line_split |
mod.rs | use futures::{select, StreamExt};
use log::{debug, error, info, warn};
use std::collections::HashMap;
use std::sync::RwLock;
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::mpsc::{self, UnboundedSender};
mod trace;
use crate::protocol::{Message, MessageBody, TryIntoMessage};
use crate::{Broker, Error,... |
Ok(())
}
/// Wraps `try_handle_delivery` to catch any and all errors that might occur.
async fn handle_delivery(
&self,
delivery_result: Result<B::Delivery, B::DeliveryError>,
event_tx: UnboundedSender<TaskEvent>,
) {
if let Err(e) = self.try_handle_delivery(de... | {
self.broker.decrease_prefetch_count().await?;
} | conditional_block |
mod.rs | use futures::{select, StreamExt};
use log::{debug, error, info, warn};
use std::collections::HashMap;
use std::sync::RwLock;
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::mpsc::{self, UnboundedSender};
mod trace;
use crate::protocol::{Message, MessageBody, TryIntoMessage};
use crate::{Broker, Error,... | <T: Task>(&self, task: &T) -> Self {
Self {
timeout: task.timeout().or(self.timeout),
max_retries: task.max_retries().or(self.max_retries),
min_retry_delay: task.min_retry_delay().unwrap_or(self.min_retry_delay),
max_retry_delay: task.max_retry_delay().unwrap_or(s... | overrides | identifier_name |
ddpg.py | #!/usr/bin/env python
import os
import tensorflow as tf
import numpy as np
from collections import OrderedDict
from model_states_client import set_states
import random
import rospy
from bot_utils.utils import Csv, Plot
RANDOM_SEED = 1234
BUFFER_SIZE = 100
MINIBATCH_SIZE = 25
EPISODES = 1000
STEPS = 10
ACTOR_LEARNIN... | (object):
def __init__(self, sess, state_dim, action_dim, learning_rate, tau):
self.sess = sess
self.s_dim = state_dim
self.a_dim = action_dim
self.learning_rate = learning_rate
self.tau = tau
self.actor_inputs_dirt, self.actor_weights, self.actor_out = self.create_actor_network('actor_network')
sel... | ActorNetwork | identifier_name |
ddpg.py | #!/usr/bin/env python
import os
import tensorflow as tf
import numpy as np
from collections import OrderedDict
from model_states_client import set_states
import random
import rospy
from bot_utils.utils import Csv, Plot
RANDOM_SEED = 1234
BUFFER_SIZE = 100
MINIBATCH_SIZE = 25
EPISODES = 1000
STEPS = 10
ACTOR_LEARNIN... |
def predict(self, inputs):
return self.sess.run(self.actor_out, feed_dict = {
self.actor_inputs_dirt: inputs
})
def predict_target(self, inputs):
return self.sess.run(self.target_actor_out, feed_dict = {self.target_actor_inputs_dirt: inputs})
def update_target_network(self):
self.sess.run(self.upda... | self.sess.run(self.optimize, feed_dict = {self.actor_inputs_dirt: inputs,
self.action_gradient: a_gradient}) | identifier_body |
ddpg.py | #!/usr/bin/env python
import os
import tensorflow as tf
import numpy as np
from collections import OrderedDict
from model_states_client import set_states
import random
import rospy
from bot_utils.utils import Csv, Plot
RANDOM_SEED = 1234
BUFFER_SIZE = 100
MINIBATCH_SIZE = 25
EPISODES = 1000
STEPS = 10
ACTOR_LEARNIN... |
def conv2d(input, weight_shape, bias_shape):
stdev = weight_shape[0] * weight_shape[1] * weight_shape[2]
W = tf.get_variable("W", initializer = tf.truncated_normal(shape = weight_shape, stddev = 2 / np.sqrt(stdev)))
bias_init = tf.constant_initializer(value = 0)
b = tf.get_variable("b", bias_shape, initializer =... | delete_models_name = [names for names in gazebo_client.get_model_states().name if
names.startswith('cube')]
delete_models_path = [names[:-2] for names in delete_models_name]
env.gazebo_client.delete_gazebo_sdf_models(delete_models_name)
env.gazebo_client.shuffle_models(delete_model... | conditional_block |
ddpg.py | #!/usr/bin/env python
import os
import tensorflow as tf
import numpy as np
from collections import OrderedDict
from model_states_client import set_states
import random
import rospy
from bot_utils.utils import Csv, Plot
RANDOM_SEED = 1234
BUFFER_SIZE = 100
MINIBATCH_SIZE = 25
EPISODES = 1000
STEPS = 10
ACTOR_LEARNIN... |
TAU = 0.01
cube_map_pose = OrderedDict([('cube_blue_1', [1.5, -0.3, 0.80]), ('cube_blue_2', [1.5, -0.05, 0.80]),
('cube_red_1', [1.5, 0.2, 0.80]), ('cube_red_2', [1.7, -0.15, 0.80]),
('cube_green_1', [1.65, 0.05, 0.80]), ('cube_green_2', [1.6, 0.32, 0.80])
... |
PARAM_FILE = '../param/training_parameters_2018_06_20.csv'
SUM_FILE = '../SUM_DIR/summary_2018_06_20.csv' | random_line_split |
core.ts | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | f (conclusion === 'success') {
text = `successfully ran ${build.steps.length} steps 🎉!`;
}
return {
conclusion,
summary,
text,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function buildFailureFrom(error: any, detailsUrl: string): BuildResponse {
if (typeof error.name ==... | conclusion = 'failure';
summary = `${++failures} steps failed 🙁`;
text += `❌ step ${step.name} failed with status ${step.status}\n`;
}
}
i | conditional_block |
core.ts | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | getCloudBuildInstance() {
return new CloudBuildClient();
}
/*
* Load OwlBot lock file from .github/.OwlBot.lock.yaml.
* TODO(bcoe): abstract into common helper that supports .yml.
*
* @param {string} repoFull - repo in org/repo format.
* @param {number} pullNumber - pull request to base branch on.
* @param {Oc... | he && cachedOctokit) return cachedOctokit;
let tokenString: string;
if (auth instanceof Object) {
const token = await getGitHubShortLivedAccessToken(
auth.privateKey,
auth.appId,
auth.installation
);
tokenString = token.token;
} else {
tokenString = auth;
}
const octokit = ne... | identifier_body |
core.ts | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | const build = await waitForBuild(project, buildId, cb);
return {detailsURL, ...summarizeBuild(build)};
} catch (e) {
const err = e as Error;
logger.error(`triggerPostProcessBuild: ${err.message}`, {
stack: err.stack,
});
return buildFailureFrom(err, detailsURL);
}
}
function summarize... | const detailsURL = detailsUrlFrom(buildId, project);
try {
// TODO(bcoe): work with fenster@ to figure out why awaiting a long
// running operation does not behave as expected:
// const [build] = await resp.promise(); | random_line_split |
core.ts | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | Key: string,
appId: number,
installation: number
): Promise<Token> {
const payload = {
// issued at time
// Note: upstream API seems to fail if decimals are included
// in unixtime, this is why parseInt is run:
iat: parseInt('' + Date.now() / 1000),
// JWT expiration time (10 minute maximum)
... | ortLivedAccessToken(
private | identifier_name |
main.py | import spacy
import get_input as gi
import csv
import os
import visualisierung as vi
from xml.etree import ElementTree
from matplotlib import pyplot as plt
from collections import Counter
spacy.cli.download("en_core_web_sm")
#Die obige Zeile downloaded "en_core_web_sm", nachdem man das gedownloaded hat, kann man es aus... | ist_with_qs_and_os_counted_trigger_lists = [praeposition_triggers_for_qs_links, praeposition_triggers_for_os_links]
if read_all == 0:
break
return_list = [sub_tag_dict, sub_tag_QS_link_types, double_list_with_qs_and_os_counted_trigger_lists, count_motion_verb]
return return_list
def write_... | ers_for_os_links[potential_match[1]] = 1
double_l | conditional_block |
main.py | import spacy
import get_input as gi
import csv
import os
import visualisierung as vi
from xml.etree import ElementTree
from matplotlib import pyplot as plt
from collections import Counter
spacy.cli.download("en_core_web_sm")
#Die obige Zeile downloaded "en_core_web_sm", nachdem man das gedownloaded hat, kann man es aus... | plt.savefig('Verteilung_der_satzlaenge.png', dpi=300, bbox_inches='tight')
#plt.show()
def do_part_2_2_vorverarbeitung(all_texts):
#Eine kleine Sub-funktione, welche den Output-Ordner erstellt und
#dafür sorgt, dass das die PoS-Tags gezählt und geschrieben werden und dabei
#zählen wir die Satzläng... | plt.title("Anzahl der Wörter pro Satz")
plt.xlabel("Satzlänge")
plt.ylabel("Häufigkeit") | random_line_split |
main.py | import spacy
import get_input as gi
import csv
import os
import visualisierung as vi
from xml.etree import ElementTree
from matplotlib import pyplot as plt
from collections import Counter
spacy.cli.download("en_core_web_sm")
#Die obige Zeile downloaded "en_core_web_sm", nachdem man das gedownloaded hat, kann man es aus... | ut_data()
all_texts = input_data[0]
dict_with_sentence_lengths = do_part_2_2_vorverarbeitung(all_texts)
abs_paths_to_xml_files = input_data[1]
#count the different tags for 2.3.b)
get_location_amount = count_locations(all_texts)
xml_tags = get_tags_from_xml(abs_paths_to_xml_files)
write_cou... | _inp | identifier_name |
main.py | import spacy
import get_input as gi
import csv
import os
import visualisierung as vi
from xml.etree import ElementTree
from matplotlib import pyplot as plt
from collections import Counter
spacy.cli.download("en_core_web_sm")
#Die obige Zeile downloaded "en_core_web_sm", nachdem man das gedownloaded hat, kann man es aus... | motion_verb_into_csv(dict_with_motion_text):
# Hier schreiben wir die in anderen Funktionen gezählten Motion Verben in eine .csv-Datei
csv_name = "output_counted_motion_verbs.csv"
with open(csv_name, 'w', newline='') as myfile:
thewriter = csv.writer(myfile)
thewriter.writerow(['Name:', 'Anz... | unted_qs_and_os_link_praep_triggers.csv"
with open(csv_name, 'w', newline='') as myfile:
thewriter = csv.writer(myfile)
thewriter.writerow(['Linktyp:', 'QsLink'])
thewriter.writerow(['Triggerwort:', 'Anzahl der Triggerungen:'])
for entry in list_with_dicts_for_qs_and_os_link_triggers... | identifier_body |
conn.go | package rudp
import (
"errors"
"io"
"math/rand"
"net"
"time"
)
const (
maxWaitSegmentCntWhileConn = 3
)
var rander = rand.New(rand.NewSource(time.Now().Unix()))
type connStatus int8
const (
connStatusConnecting connStatus = iota
connStatusOpen
connStatusClose
connStatusErr
)
type connType int8
const (
... | else if c.rudpConnType == connTypeServer {
c.serverRecv()
}
}
func (c *RUDPConn) clientRecv() {
for {
select {
case <-c.recvStop:
return
default:
buf := make([]byte, rawUDPPacketLenLimit)
n, err := c.rawUDPConn.Read(buf)
if err != nil {
c.errBus <- err
return
}
buf = buf[:n]
apa... | {
c.clientRecv()
} | conditional_block |
conn.go | package rudp
import (
"errors"
"io"
"math/rand"
"net"
"time"
)
const (
maxWaitSegmentCntWhileConn = 3
)
var rander = rand.New(rand.NewSource(time.Now().Unix()))
type connStatus int8
const (
connStatusConnecting connStatus = iota
connStatusOpen
connStatusClose
connStatusErr
)
type connType int8
const (
... | c := &RUDPConn{}
c.localAddr = localAddr
c.remoteAddr = remoteAddr
c.rudpConnType = connTypeClient
c.sendSeqNumber = 0
c.recvPacketChannel = make(chan *packet, 1<<5)
c.rudpConnStatus = connStatusConnecting
if err := c.clientBuildConn(); err != nil {
return nil, err
}
c.sendPacketChannel = make(chan *packe... |
// DialRUDP client dial server, building a relieable connection
func DialRUDP(localAddr, remoteAddr *net.UDPAddr) (*RUDPConn, error) { | random_line_split |
conn.go | package rudp
import (
"errors"
"io"
"math/rand"
"net"
"time"
)
const (
maxWaitSegmentCntWhileConn = 3
)
var rander = rand.New(rand.NewSource(time.Now().Unix()))
type connStatus int8
const (
connStatusConnecting connStatus = iota
connStatusOpen
connStatusClose
connStatusErr
)
type connType int8
const (
... | c *RUDPConn) Write(b []byte) (int, error) {
if c.err != nil {
return 0, errors.New("rudp write error: " + c.err.Error())
}
n := len(b)
for {
if len(b) <= rudpPayloadLenLimit {
c.sendPacketChannel <- newNormalPacket(b, c.sendSeqNumber)
c.sendSeqNumber++
return n, nil
} else {
c.sendPacketChannel <-... | {
readCnt := len(b)
n := len(b)
if n == 0 {
return 0, nil
}
curWrite := 0
if len(c.outputDataTmpBuffer) != 0 {
if n <= len(c.outputDataTmpBuffer) {
copy(b, c.outputDataTmpBuffer[:n])
c.outputDataTmpBuffer = c.outputDataTmpBuffer[n:]
return readCnt, nil
} else {
n -= len(c.outputDataTmpBuffer)
... | identifier_body |
conn.go | package rudp
import (
"errors"
"io"
"math/rand"
"net"
"time"
)
const (
maxWaitSegmentCntWhileConn = 3
)
var rander = rand.New(rand.NewSource(time.Now().Unix()))
type connStatus int8
const (
connStatusConnecting connStatus = iota
connStatusOpen
connStatusClose
connStatusErr
)
type connType int8
const (
... | () {
ticker := time.NewTicker(time.Duration(c.sendTickNano) * time.Nanosecond)
defer ticker.Stop()
for {
select {
case c.sendTickNano = <-c.sendTickModifyEvent:
ticker.Stop()
ticker = time.NewTicker(time.Duration(c.sendTickNano) * time.Nanosecond)
case <-c.sendStop:
return
case <-ticker.C:
c.send... | send | identifier_name |
plotXsectLimitComparison.py | #!/usr/bin/env python
import time
import os
import csv
import PlotUtils
import sys
#----------------------------------------------------------------------
# parameters
#----------------------------------------------------------------------
colorsToAvoid = [ 5, # yellow
]
#----------------------... | )
parser.add_option(
"--relative",
help="instead of plotting the absolute cross section exclusions, plot the relative (w.r.t. to the input signal)",
default=False,
action="store_true",
)
parser.add_option(
"--isabs",
help="specify that a given file contains ABSOLUTE rather than RELATIV... | "--ymax",
type=float,
help="manually sepcify the y scale",
default=None, | random_line_split |
plotXsectLimitComparison.py | #!/usr/bin/env python
import time
import os
import csv
import PlotUtils
import sys
#----------------------------------------------------------------------
# parameters
#----------------------------------------------------------------------
colorsToAvoid = [ 5, # yellow
]
#----------------------... |
else:
typeName = "SM"
# convert to absolute cross sections
for line, fname in zip(data, csvFnames):
if fname in inputIsAbs:
# already absolute
continue
line['observedValues'] = PlotUtils.multiplyArrayByXsectAndBR(line['masses... | typeName = "FP" | conditional_block |
plotXsectLimitComparison.py | #!/usr/bin/env python
import time
import os
import csv
import PlotUtils
import sys
#----------------------------------------------------------------------
# parameters
#----------------------------------------------------------------------
colorsToAvoid = [ 5, # yellow
]
#----------------------... |
#----------------------------------------------------------------------
# main
#----------------------------------------------------------------------
from optparse import OptionParser
parser = OptionParser("""
%prog [options] csv_file1 csv_file2 [ ... ]
compares two or more cross sectio... | """ @param relative if true, the exclusion of the ratios
(relative to the inputs given) are plotted. If False,
these ratios are multiplied by the SM cross sections
and branching ratios into gamma gamma
@param inputIsAbs is a list (set) of file names which
should be treated as i... | identifier_body |
plotXsectLimitComparison.py | #!/usr/bin/env python
import time
import os
import csv
import PlotUtils
import sys
#----------------------------------------------------------------------
# parameters
#----------------------------------------------------------------------
colorsToAvoid = [ 5, # yellow
]
#----------------------... | (csvFnames, relative, includeExpected = True, fermiophobic = None, ymax = None, inputIsAbs = None, drawXsectBR = False,
minMass = None,
maxMass = None,
plotLog = False
):
""" @param relative if true, the exclusion of the ratios
(relative to the inputs give... | makePlot | identifier_name |
test.rs | //! Contains helpers for Gotham applications to use during testing.
//!
//! See the [`TestServer`] and [`AsyncTestServer`] types for example usage.
use std::convert::TryFrom;
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::... |
#[test]
fn test_server_supports_multiple_servers() {
test::common_tests::supports_multiple_servers(TestServer::new, TestServer::client)
}
#[test]
fn test_server_spawns_and_runs_futures() {
let server = TestServer::new(TestHandler::default()).unwrap();
let (sender, spawn_r... | {
test::common_tests::async_echo(TestServer::new, TestServer::client)
} | identifier_body |
test.rs | //! Contains helpers for Gotham applications to use during testing.
//!
//! See the [`TestServer`] and [`AsyncTestServer`] types for example usage.
use std::convert::TryFrom;
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::... | () {
async_test::common_tests::adds_client_address_to_state(
AsyncTestServer::new,
AsyncTestServer::client,
)
.await;
}
}
| async_test_server_adds_client_address_to_state | identifier_name |
test.rs | //! Contains helpers for Gotham applications to use during testing.
//!
//! See the [`TestServer`] and [`AsyncTestServer`] types for example usage.
use std::convert::TryFrom;
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::... | else {
tcp.connected()
}
}
}
impl<IO> AsyncRead for TlsConnectionStream<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf,
) -> Poll<Result<(), io::Error>> {
self.pro... | {
tcp.connected().negotiated_h2()
} | conditional_block |
test.rs | //! Contains helpers for Gotham applications to use during testing.
//!
//! See the [`TestServer`] and [`AsyncTestServer`] types for example usage.
use std::convert::TryFrom;
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::... | Ok(stream) => {
let domain = ServerName::try_from(req.host().unwrap()).unwrap();
match tls.connect(domain, stream).await {
Ok(tls_stream) => {
info!("Client TcpStream connected: {:?}", tls_stream);
... |
async move {
match TcpStream::connect(address).await { | random_line_split |
databases.go | // Copyright 2022 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
// DBTableIter iterates over all tables returned by db.GetTableNames() calling cb for each one until all tables have
// been processed, or an error is returned from the callback, or the cont flag is false when returned from the callback.
func DBTableIter(ctx *Context, db Database, cb func(Table) (cont bool, err error... | {
for _, name := range tableNames {
if tblName == name {
return name, true
}
}
lwrName := strings.ToLower(tblName)
for _, name := range tableNames {
if lwrName == strings.ToLower(name) {
return name, true
}
}
return "", false
} | identifier_body |
databases.go | // Copyright 2022 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | else if !ok {
return ErrTableNotFound.New(name)
}
cont, err := cb(tbl)
if err != nil {
return err
}
if !cont {
break
}
}
return nil
}
// UnresolvedDatabase is a database which has not been resolved yet.
type UnresolvedDatabase string
var _ Database = UnresolvedDatabase("")
// Name returns... | {
return err
} | conditional_block |
databases.go | // Copyright 2022 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (ctx *Context, tblName string) (Table, bool, error) {
return nil, false, nil
}
func (UnresolvedDatabase) GetTableNames(ctx *Context) ([]string, error) {
return []string{}, nil
}
| GetTableInsensitive | identifier_name |
databases.go | // Copyright 2022 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | GetEvent(ctx *Context, name string) (EventDefinition, bool, error)
// GetEvents returns all EventDetails for the database.
GetEvents(ctx *Context) ([]EventDefinition, error)
// SaveEvent stores the given EventDetails to the database. The integrator should verify that
// the name of the new event is unique amongst ... | // handle execution logic for events. Integrators only need to store and retrieve EventDetails.
type EventDatabase interface {
Database
// GetEvent returns the desired EventDetails and if it exists in the database. | random_line_split |
funcs.py | from __future__ import print_function
class DataError(Exception):
def __init__(self, string=None):
if string != None:
self.message = string
def __str__(self):
return self.message
def get3DEllipse(t,y,x):
import numpy as np
at=np.arange(-t,t+1)
ax=np.arange(-x,x+1)
... | (slab,newaxis=None,axis=0,verbose=False):
"""Adds an extra axis to a data slab.
<slab>: variable to which the axis is to insert.
<newaxis>: axis object, could be of any length. If None, create a dummy
singleton axis.
<axis>: index of axis to be inserted, e.g. 0 if <newaxis> is inserted
... | addExtraAxis | identifier_name |
funcs.py | from __future__ import print_function
class DataError(Exception):
def __init__(self, string=None):
if string != None:
self.message = string
def __str__(self):
return self.message
def get3DEllipse(t,y,x):
import numpy as np
at=np.arange(-t,t+1)
ax=np.arange(-x,x+1)
... | return quantiles
#-------Copies selected attributes from source object to dict--
def attribute_obj2dict(source_object,dictionary=None,verbose=False):
'''Copies selected attributes from source object to dict
to <dictionary>.
<source_object>: object from which attributes are copied.
<dictionary>: N... | print('# <getQuantiles>: %0.3f left quantile: %f. %0.3f right quantile: %f.'\
%(pii,ql[ii],1-pii,qr[ii]))
| random_line_split |
funcs.py | from __future__ import print_function
class DataError(Exception):
def __init__(self, string=None):
if string != None:
self.message = string
def __str__(self):
return self.message
def get3DEllipse(t,y,x):
import numpy as np
at=np.arange(-t,t+1)
ax=np.arange(-x,x+1)
... |
# interpret string dimension
#elif type(axis)==type('t'):
elif isinstance(axis,str if sys.version_info[0]>=3 else basestring):
axis=axis.lower()
if axis in ['time', 'tim', 't']:
dim_id = 'time'
elif axis in ['level', 'lev','z']:
dim_id = 'level'
eli... | return axis | conditional_block |
funcs.py | from __future__ import print_function
class DataError(Exception):
def __init__(self, string=None):
if string != None:
self.message = string
def __str__(self):
return self.message
def get3DEllipse(t,y,x):
import numpy as np
at=np.arange(-t,t+1)
ax=np.arange(-x,x+1)
... |
#------Interpret and convert an axis id to index----------
def interpretAxis(axis,ref_var,verbose=True):
'''Interpret and convert an axis id to index
<axis>: axis option, integer or string.
<ref_var>: reference variable.
Return <axis_index>: the index of required axis in <ref_var>.
E.g. index=... | '''Concatenate 2 variables along axis.
<var1>,<var2>: Variables to be concatenated, in the order of \
<var1>, <var2>;
<axis>: int, index of axis to be concatenated along.
Return <result>
'''
import MV2 as MV
import numpy
try:
order=var1.getAxisListIndex()
except:
... | identifier_body |
aat_common_test.go | // SPDX-License-Identifier: Unlicense OR BSD-3-Clause
package tables
import (
"reflect"
"strings"
"testing"
td "github.com/go-text/typesetting-utils/opentype"
tu "github.com/go-text/typesetting/opentype/testutils"
)
func | (t *testing.T) {
// adapted from fontttools
src := deHexStr(
"0004 0006 0003 000C 0001 0006 " +
"0002 0001 001E " + // glyph 1..2: mapping at offset 0x1E
"0005 0004 001E " + // glyph 4..5: mapping at offset 0x1E
"FFFF FFFF FFFF " + // end of search table
"0007 0008")
class, _, err := ParseAATLookup(src... | TestAATLookup4 | identifier_name |
aat_common_test.go | // SPDX-License-Identifier: Unlicense OR BSD-3-Clause
package tables
import (
"reflect"
"strings"
"testing"
td "github.com/go-text/typesetting-utils/opentype"
tu "github.com/go-text/typesetting/opentype/testutils"
)
func TestAATLookup4(t *testing.T) |
func TestParseTrak(t *testing.T) {
fp := readFontFile(t, "toys/Trak.ttf")
trak, _, err := ParseTrak(readTable(t, fp, "trak"))
tu.AssertNoErr(t, err)
tu.Assert(t, len(trak.Horiz.SizeTable) == 4)
tu.Assert(t, len(trak.Vert.SizeTable) == 0)
tu.Assert(t, reflect.DeepEqual(trak.Horiz.SizeTable, []float32{1, 2, 12, ... | {
// adapted from fontttools
src := deHexStr(
"0004 0006 0003 000C 0001 0006 " +
"0002 0001 001E " + // glyph 1..2: mapping at offset 0x1E
"0005 0004 001E " + // glyph 4..5: mapping at offset 0x1E
"FFFF FFFF FFFF " + // end of search table
"0007 0008")
class, _, err := ParseAATLookup(src, 4)
tu.Assert... | identifier_body |
aat_common_test.go | // SPDX-License-Identifier: Unlicense OR BSD-3-Clause
package tables
import (
"reflect"
"strings"
"testing"
td "github.com/go-text/typesetting-utils/opentype"
tu "github.com/go-text/typesetting/opentype/testutils"
)
func TestAATLookup4(t *testing.T) {
// adapted from fontttools
src := deHexStr(
"0004 0006 ... | sting.T) {
// this is an invalid feat table, comming from a real font table (huh...)
table, err := td.Files.ReadFile("toys/tables/featInvalid.bin")
tu.AssertNoErr(t, err)
_, _, err = ParseFeat(table)
tu.Assert(t, err != nil)
}
func TestParseLtag(t *testing.T) {
table, err := td.Files.ReadFile("toys/tables/ltag.... | dFile(filepath)
tu.AssertNoErr(t, err)
kerx, _, err := ParseKerx(table, 0xFF)
tu.AssertNoErr(t, err)
tu.Assert(t, len(kerx.Tables) > 0)
for _, subtable := range kerx.Tables {
tu.Assert(t, subtable.TupleCount > 0 == strings.Contains(filepath, "VF"))
switch data := subtable.Data.(type) {
case KerxDat... | conditional_block |
aat_common_test.go | // SPDX-License-Identifier: Unlicense OR BSD-3-Clause
package tables
import (
"reflect"
"strings"
"testing"
td "github.com/go-text/typesetting-utils/opentype"
tu "github.com/go-text/typesetting/opentype/testutils"
)
func TestAATLookup4(t *testing.T) {
// adapted from fontttools
src := deHexStr(
"0004 0006 ... | {FirstGlyph: 26, LastGlyph: 28, Value: 6},
}
tu.Assert(t, reflect.DeepEqual(class.Records, expMachineClassRecords))
expMachineStates := [][]uint16{
{0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000}, // State[0][0..6]
{0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000}, // State[1][0..6]
{0x0000,... | random_line_split | |
args.go | // Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Argument parsing for Go functions called by python
//
// These functions are useful when creating your own extensions
// functions and methods. Addit... | sults ...*Object) error {
return ParseTupleAndKeywords(args, nil, format, nil, results...)
}
type formatOp struct {
code byte
modifier byte
}
// Parse the format
func parseFormat(format string, in []formatOp) (min int, name string, kwOnly_i int, ops []formatOp) {
name = "function"
min = -1
kwOnly_i = 0xFFFF... | string, re | identifier_name |
args.go | // Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Argument parsing for Go functions called by python
//
// These functions are useful when creating your own extensions
// functions and methods. Addit... | // This format converts a bytes-like object to a C pointer to a
// character string; it does not accept Unicode objects. The bytes
// buffer must not contain embedded NUL bytes; if it does, a TypeError
// exception is raised.
//
// y* (bytes, bytearray or bytes-like object) [Py_buffer]
//
// This variant on s* doesn’t ... | random_line_split | |
args.go | // Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Argument parsing for Go functions called by python
//
// These functions are useful when creating your own extensions
// functions and methods. Addit... | tch op.code {
case 'O':
*result = arg
case 'Z':
switch op.modifier {
default:
return ExceptionNewf(TypeError, "%s() argument %d must be str or None, not %s", name, i+1, arg.Type().Name)
case '#', 0:
switch arg := arg.(type) {
case String, NoneType:
default:
return ExceptionNewf(Type... | results[i]
swi | conditional_block |
args.go | // Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Argument parsing for Go functions called by python
//
// These functions are useful when creating your own extensions
// functions and methods. Addit... | passed in
func checkNumberOfArgs(name string, nargs, nresults, min, max int) error {
if min == max {
if nargs != max {
return ExceptionNewf(TypeError, "%s() takes exactly %d arguments (%d given)", name, max, nargs)
}
} else {
if nargs > max {
return ExceptionNewf(TypeError, "%s() takes at most %d argumen... |
kwOnly_i = 0xFFFF
ops = in[:0]
N := len(format)
for i := 0; i < N; {
op := formatOp{code: format[i]}
i++
if i < N {
if mod := format[i]; mod == '*' || mod == '#' {
op.modifier = mod
i++
}
}
switch op.code {
case ':', ';':
name = format[i:]
i = N
case '$':
kwOnly_i = len(ops)
... | identifier_body |
sudo.py | #Video sequence is just a collection of frames or collection of images that runs with respect to time.
#Make code stare at background without hand
#Bring hand in foreground with background
#Apply background-subtraction
#Thresholding is the assigment of pixel intensities to 0’s and 1’s based a particular threshold level... | eight for running average
alphaWeight = 0.5 #if we set lower value, running average will be performed over larger amt of previous frames and vice-a-versa
stream = 'http://192.168.0.4:8080/video'
#get the reference to the webcam
camera = cv2.VideoCapture(stream)
top, right, bottom, left = 10, 350, ... | alize w | identifier_name |
sudo.py | #Video sequence is just a collection of frames or collection of images that runs with respect to time.
#Make code stare at background without hand
#Bring hand in foreground with background
#Apply background-subtraction
#Thresholding is the assigment of pixel intensities to 0’s and 1’s based a particular threshold level... | #print(extreme_top + " " + extreme_bottom + " " + extreme_left + " " + extreme_right)
#palm center
cX = (extreme_left[0] + extreme_right[0]) / 2
cY = (extreme_top[1] + extreme_bottom[1]) / 2
cX = np.round(cX).astype("int") #convert to int
cY = np.round(cY).astype("int")
#maximum euclidean ... | extreme_top = tuple(convex_hull[convex_hull[:, :, 1].argmin()][0])
extreme_bottom = tuple(convex_hull[convex_hull[:, :, 1].argmax()][0])
extreme_left = tuple(convex_hull[convex_hull[:, :, 0].argmin()][0])
extreme_right = tuple(convex_hull[convex_hull[:, :, 0].argmax()][0]) | random_line_split |
sudo.py | #Video sequence is just a collection of frames or collection of images that runs with respect to time.
#Make code stare at background without hand
#Bring hand in foreground with background
#Apply background-subtraction
#Thresholding is the assigment of pixel intensities to 0’s and 1’s based a particular threshold level... | in__":
compute() | we set lower value, running average will be performed over larger amt of previous frames and vice-a-versa
stream = 'http://192.168.0.4:8080/video'
#get the reference to the webcam
camera = cv2.VideoCapture(stream)
top, right, bottom, left = 10, 350, 225, 590 #ROI Co-ords
num_frames = 0 #initi... | identifier_body |
sudo.py | #Video sequence is just a collection of frames or collection of images that runs with respect to time.
#Make code stare at background without hand
#Bring hand in foreground with background
#Apply background-subtraction
#Thresholding is the assigment of pixel intensities to 0’s and 1’s based a particular threshold level... | se()
cv2.destroyAllWindows()
if __name__ == "__main__":
compute() | ad()
frame = imutils.resize(frame, width=700) #resize frame
frame = cv2.flip(frame, 1) #flip around x-axis -- dest(i,j) = src(i,cols-j-1)
clone = frame.copy()
(height, width) = frame.shape[:2] #get height and width of frame
#print(str(height) +" "+ str(width))
r... | conditional_block |
cloudFoundryDeploy.go | package cmd
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/SAP/jenkins-library/pkg/cloudfoundry"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperutils"
"githu... |
func getAppName(config *cloudFoundryDeployOptions) (string, error) {
if len(config.AppName) > 0 {
return config.AppName, nil
}
if config.DeployType == "blue-green" {
return "", fmt.Errorf("Blue-green plugin requires app name to be passed (see https://github.com/bluemixgaragelondon/cf-blue-green-deploy/issues/... | {
manifestFileName := config.Manifest
if len(manifestFileName) == 0 {
manifestFileName = "manifest.yml"
}
return manifestFileName, nil
} | identifier_body |
cloudFoundryDeploy.go | package cmd
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/SAP/jenkins-library/pkg/cloudfoundry"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperutils"
"githu... | (keyValue []string, separator string) (map[string]string, error) {
result := map[string]string{}
for _, entry := range keyValue {
kv := strings.Split(entry, separator)
if len(kv) < 2 {
return map[string]string{}, fmt.Errorf("Cannot convert to map: separator '%s' not found in entry '%s'", separator, entry)
}
... | toMap | identifier_name |
cloudFoundryDeploy.go | package cmd
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/SAP/jenkins-library/pkg/cloudfoundry"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperutils"
"githu... |
}
cfDeployParams = append(cfDeployParams, extFileParams...)
err := cfDeploy(config, cfDeployParams, nil, nil, command)
for _, extFile := range extFiles {
renameError := fileUtils.FileRename(extFile+".original", extFile)
if err == nil && renameError != nil {
return renameError
}
}
return err
}
func ... | {
return fmt.Errorf("Cannot handle credentials inside mta extension files: %w", err)
} | conditional_block |
cloudFoundryDeploy.go | package cmd
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/SAP/jenkins-library/pkg/cloudfoundry"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperutils"
"githu... | }
if config.DeployType == "bg-deploy" || config.DeployType == "blue-green" {
deployCommand = "bg-deploy"
const noConfirmFlag = "--no-confirm"
if !piperutils.ContainsString(deployParams, noConfirmFlag) {
deployParams = append(deployParams, noConfirmFlag)
}
}
cfDeployParams := []string{
deployCommand... | if len(config.MtaDeployParameters) > 0 {
deployParams = append(deployParams, strings.Split(config.MtaDeployParameters, " ")...) | random_line_split |
viewer.rs | use std::f32::consts::PI;
use std::os::raw::c_void;
use std::path::Path;
use std::process;
use std::time::Instant;
use cgmath::{ Deg, Point3 };
use collision::Aabb;
use gl;
use gltf;
use glutin;
use glutin::{
Api,
MouseScrollDelta,
MouseButton,
GlContext,
GlRequest,
GlProfile,
VirtualKeyCod... | },
WindowEvent::MouseInput { button, state: Released, ..} => {
match (button, orbit_controls.state.clone()) {
(MouseButton::Left, NavState::Rotating) | (MouseButton::Right, NavState::Panning) => {
orbit_controls.stat... | _ => ()
} | random_line_split |
viewer.rs | use std::f32::consts::PI;
use std::os::raw::c_void;
use std::path::Path;
use std::process;
use std::time::Instant;
use cgmath::{ Deg, Point3 };
use collision::Aabb;
use gl;
use gltf;
use glutin;
use glutin::{
Api,
MouseScrollDelta,
MouseButton,
GlContext,
GlRequest,
GlProfile,
VirtualKeyCod... | (source: &str, scene_index: usize) -> (Root, Scene) {
let mut start_time = Instant::now();
// TODO!: http source
// let gltf =
if source.starts_with("http") {
panic!("not implemented: HTTP support temporarily removed.")
// let http_source = HttpSource::new(source)... | load | identifier_name |
viewer.rs | use std::f32::consts::PI;
use std::os::raw::c_void;
use std::path::Path;
use std::process;
use std::time::Instant;
use cgmath::{ Deg, Point3 };
use collision::Aabb;
use gl;
use gltf;
use glutin;
use glutin::{
Api,
MouseScrollDelta,
MouseButton,
GlContext,
GlRequest,
GlProfile,
VirtualKeyCod... | ;
self.orbit_controls.position = cam_pos;
self.orbit_controls.target = center;
self.orbit_controls.camera.znear = size / 100.0;
self.orbit_controls.camera.zfar = Some(size * 20.0);
self.orbit_controls.camera.update_projection_matrix();
}
pub fn start_render_loop(&mut se... | {
Point3::new(
center.x + size / 2.0,
center.y + size / 5.0,
center.z + size / 2.0,
)
} | conditional_block |
viewer.rs | use std::f32::consts::PI;
use std::os::raw::c_void;
use std::path::Path;
use std::process;
use std::time::Instant;
use cgmath::{ Deg, Point3 };
use collision::Aabb;
use gl;
use gltf;
use glutin;
use glutin::{
Api,
MouseScrollDelta,
MouseButton,
GlContext,
GlRequest,
GlProfile,
VirtualKeyCod... |
fn process_input(input: glutin::KeyboardInput, controls: &mut OrbitControls) -> bool {
let pressed = match input.state {
Pressed => true,
Released => false
};
if let Some(code) = input.virtual_keycode {
match code {
VirtualKeyCode::Escape if pressed => return false,
... | {
let mut keep_running = true;
#[allow(single_match)]
events_loop.poll_events(|event| {
match event {
glutin::Event::WindowEvent{ event, .. } => match event {
WindowEvent::CloseRequested => {
keep_running = false;
},
Win... | identifier_body |
cq_reactor.rs | //! The Completion Queue Reactor. Functions like any other async/await reactor, but is driven by
//! IRQs triggering wakeups in order to poll NVME completion queues (see `CompletionFuture`).
//!
//! While the reactor is primarily intended to wait for IRQs and then poll completion queues, it
//! can also be used for not... | use super::{CmdId, CqId, InterruptSources, Nvme, NvmeComp, NvmeCmd, SqId};
/// A notification request, sent by the future in order to tell the completion thread that the
/// current task wants a notification when a matching completion queue entry has been seen.
#[derive(Debug)]
pub enum NotifReq {
RequestCompletio... | random_line_split | |
cq_reactor.rs | //! The Completion Queue Reactor. Functions like any other async/await reactor, but is driven by
//! IRQs triggering wakeups in order to poll NVME completion queues (see `CompletionFuture`).
//!
//! While the reactor is primarily intended to wait for IRQs and then poll completion queues, it
//! can also be used for not... | (
nvme: Arc<Nvme>,
interrupt_sources: InterruptSources,
receiver: Receiver<NotifReq>,
) -> thread::JoinHandle<()> {
// Actually, nothing prevents us from spawning additional threads. the channel is MPMC and
// everything is properly synchronized. I'm not saying this is strictly required, but with
... | start_cq_reactor_thread | identifier_name |
cq_reactor.rs | //! The Completion Queue Reactor. Functions like any other async/await reactor, but is driven by
//! IRQs triggering wakeups in order to poll NVME completion queues (see `CompletionFuture`).
//!
//! While the reactor is primarily intended to wait for IRQs and then poll completion queues, it
//! can also be used for not... |
fn new(
nvme: Arc<Nvme>,
mut int_sources: InterruptSources,
receiver: Receiver<NotifReq>,
) -> Result<Self> {
Ok(Self {
event_queue: Self::create_event_queue(&mut int_sources)?,
int_sources,
nvme,
pending_reqs: Vec::new(),
... | {
use syscall::flag::*;
let fd = syscall::open("event:", O_CLOEXEC | O_RDWR)?;
let mut file = unsafe { File::from_raw_fd(fd as RawFd) };
for (num, irq_handle) in int_sources.iter_mut() {
if file
.write(&Event {
id: irq_handle.as_raw_fd() a... | identifier_body |
xcbwin.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Drop;
use std::thread;
use window::Dock;
use cairo;
use cairo::XCBSurface;
use cairo_sys;
use xcb;
use xcb::*;
fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) {
for d in scr.allowed_depths() {
if depth == d.depth() |
}
// If no depth matches return root visual
return (scr.root_visual(), scr.root_depth());
}
pub struct XCB {
conn: Arc<Connection>,
scr_num: i32,
win: Window,
root: Window,
bufpix: Pixmap,
gc: Gcontext,
colour: Colormap,
visual: Visualid,
de... | {
for v in d.visuals() {
return (v.visual_id(), depth);
}
} | conditional_block |
xcbwin.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Drop;
use std::thread;
use window::Dock;
use cairo;
use cairo::XCBSurface;
use cairo_sys;
use xcb;
use xcb::*;
fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) {
for d in scr.allowed_depths() {
if depth == d.depth() {
... | impl Dock for XCB {
fn create_surface(&self) -> cairo::Surface {
// Prepare cairo variables
let cr_conn = unsafe {
cairo::XCBConnection::from_raw_none(
self.conn.get_raw_conn() as *mut cairo_sys::xcb_connection_t)
};
let cr_draw = cairo::XCBDrawable(self... | self.pos = (x as i16, y as i16);
}
}
| random_line_split |
xcbwin.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Drop;
use std::thread;
use window::Dock;
use cairo;
use cairo::XCBSurface;
use cairo_sys;
use xcb;
use xcb::*;
fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) {
for d in scr.allowed_depths() {
if depth == d.depth() {
... | (&self, name: &str) -> Atom {
let atom = intern_atom(&self.conn, false, name);
atom.get_reply().unwrap().atom()
}
fn get_screen(&self) -> Screen {
let setup = self.conn.get_setup();
let screen = setup.roots().nth(self.scr_num as usize).unwrap();
return screen;
}
... | get_atom | identifier_name |
xcbwin.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Drop;
use std::thread;
use window::Dock;
use cairo;
use cairo::XCBSurface;
use cairo_sys;
use xcb;
use xcb::*;
fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) {
for d in scr.allowed_depths() {
if depth == d.depth() {
... |
}
| {
free_pixmap(&*self.conn, self.win);
free_pixmap(&*self.conn, self.bufpix);
free_gc(&*self.conn, self.gc);
free_colormap(&*self.conn, self.colour);
} | identifier_body |
lib.rs | //! jlrs is a crate that provides access to most of the Julia C API, it can be used to embed Julia
//! in Rust applications and to use functionality from the Julia C API when writing `ccall`able
//! functions in Rust. Currently this crate is only tested on Linux in combination with Julia 1.6
//! and is not compatible w... | <T, F>(&mut self, func: F) -> JlrsResult<T>
where
for<'base> F: FnOnce(Global<'base>, &mut GcFrame<'base, Sync>) -> JlrsResult<T>,
{
unsafe {
let page = self.get_init_page();
let global = Global::new();
let mut frame = GcFrame::new(page.as_mut(), 0, Sync);
... | scope | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.