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 |
|---|---|---|---|---|
fixture.go | // Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crossdevice
import (
"context"
"encoding/json"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"time"
"chromiumos/tast/common/android/adb"
crossdevicecommo... | func (f *crossdeviceFixture) TearDown(ctx context.Context, s *testing.FixtState) {
if f.lockFixture {
chrome.Unlock()
if err := f.cr.Close(ctx); err != nil {
s.Log("Failed to close Chrome connection: ", err)
}
}
f.cr = nil
}
func (f *crossdeviceFixture) Reset(ctx context.Context) error {
if err := f.cr.Res... | random_line_split | |
fixture.go | // Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crossdevice
import (
"context"
"encoding/json"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"time"
"chromiumos/tast/common/android/adb"
crossdevicecommo... |
func (f *crossdeviceFixture) TearDown(ctx context.Context, s *testing.FixtState) {
if f.lockFixture {
chrome.Unlock()
if err := f.cr.Close(ctx); err != nil {
s.Log("Failed to close Chrome connection: ", err)
}
}
f.cr = nil
}
func (f *crossdeviceFixture) Reset(ctx context.Context) error {
if err := f.cr.R... | {
// Android device from parent fixture.
androidDevice := s.ParentValue().(*FixtData).AndroidDevice
f.androidDevice = androidDevice
// Credentials to use (same as Android).
crosUsername := s.ParentValue().(*FixtData).Username
crosPassword := s.ParentValue().(*FixtData).Password
// Allocate time for logging and... | identifier_body |
process.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocore
import (
"debug/dwarf"
"fmt"
"math/bits"
"strings"
"sync"
"golang.org/x/debug/internal/core"
)
// A Process represents the state of a G... | () []*Goroutine {
return p.goroutines
}
// Stats returns a breakdown of the program's memory use by category.
func (p *Process) Stats() *Stats {
return p.stats
}
// BuildVersion returns the Go version that was used to build the inferior binary.
func (p *Process) BuildVersion() string {
return p.buildVersion
}
fun... | Goroutines | identifier_name |
process.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocore
import (
"debug/dwarf"
"fmt"
"math/bits"
"strings"
"sync"
"golang.org/x/debug/internal/core"
)
// A Process represents the state of a G... |
}
p.readSpans(mheap, arenas)
}
func (p *Process) readSpans(mheap region, arenas []arena) {
var all int64
var text int64
var readOnly int64
var heap int64
var spanTable int64
var bitmap int64
var data int64
var bss int64 // also includes mmap'd regions
for _, m := range p.proc.Mappings() {
size := m.Size... | {
ptr := level1Table.ArrayIndex(level1)
if ptr.Address() == 0 {
continue
}
level2table := ptr.Deref()
level2size := level2table.ArrayLen()
for level2 := int64(0); level2 < level2size; level2++ {
ptr = level2table.ArrayIndex(level2)
if ptr.Address() == 0 {
continue
}
a := ptr.D... | conditional_block |
process.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocore
import (
"debug/dwarf"
"fmt"
"math/bits"
"strings"
"sync"
"golang.org/x/debug/internal/core"
)
// A Process represents the state of a G... | {
for _, c := range s.Children {
if c.Name == name {
return c
}
}
return nil
} | identifier_body | |
process.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocore
import (
"debug/dwarf"
"fmt"
"math/bits"
"strings"
"sync"
"golang.org/x/debug/internal/core"
)
// A Process represents the state of a G... |
// initialize heap info records for all inuse spans.
for a := min; a < max; a += heapInfoSize {
h := p.allocHeapInfo(a)
h.base = min
h.size = elemSize
}
// Process special records.
for sp := s.Field("specials"); sp.Address() != 0; sp = sp.Field("next") {
sp = sp.Deref() // *special to s... | }
spanRoundSize += spanSize - n*elemSize | random_line_split |
server.js | var mysql= require('mysql');
var express= require('express');
var http = require('http');
var app= express();
var morgan=require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt=require('bcrypt');
var setCookie = require('set-cookie');
var CookieParser = require('... |
var createSession = function(req, responce, newUser) {
return req.session.regenerate(function() {
//newuser>>>> { id: 2, username: 'hananmajali', password: 'hananmajali' }
bcrypt.hash(req.body.password,3,function (err,hash) {
console.log(hash)
// x={'info... | {
bcrypt.compare(req.body.password,results[0].password,function (err,match) {
if(err){
console.log(err)
}
if(match){
console.log('this user is correct')
flag = 'true';
console.log('flag now is true')
createSession(req,res,results[0]);
}else{
console.log('this ... | identifier_body |
server.js | var mysql= require('mysql');
var express= require('express');
var http = require('http');
var app= express();
var morgan=require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt=require('bcrypt');
var setCookie = require('set-cookie');
var CookieParser = require('... |
});
//---------languge-----------------------------
app.post('/translate',function(req,response){
var value=req.body;
translate(req.body.text, {from:req.body.languageFrom+'', to: req.body.languageTo+'' })
.then(res => {
console.log(res.text);
//=> I speak English
//console.log(res.from.languag... | random_line_split | |
server.js | var mysql= require('mysql');
var express= require('express');
var http = require('http');
var app= express();
var morgan=require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt=require('bcrypt');
var setCookie = require('set-cookie');
var CookieParser = require('... |
});
/////////////////////////////////////////////////////////////////////////////
// socket.on('stop speaking' || 'stop typing',function (data) {
// console.log('stop speaking ',data)
// translate(data.text, {from:'en', to: 'en'})
// .then(res => {
// console.log('stop skeaoking tranzlate console her... | {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
} | conditional_block |
server.js | var mysql= require('mysql');
var express= require('express');
var http = require('http');
var app= express();
var morgan=require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt=require('bcrypt');
var setCookie = require('set-cookie');
var CookieParser = require('... | () {
bcrypt.compare(req.body.password,results[0].password,function (err,match) {
if(err){
console.log(err)
}
if(match){
console.log('this user is correct')
flag = 'true';
console.log('flag now is true')
createSession(req,res,results[0]);
}else{
console.log('th... | compare | identifier_name |
msc_chart.py | from datetime import datetime, timedelta
from enum import Enum
from time import sleep
from typing import Dict, List, Optional, Tuple
from github import Github
from github.GithubException import RateLimitExceededException
from github.Issue import Issue
from github.IssueEvent import IssueEvent
from github.Label import L... | elif github_token:
g = Github(github_token)
else:
raise Exception(
"Either pygithub or github_token must be set when initializing MSCChart"
)
# Create a Github instance. The token only needs read:public_repo
self.repository = g.get_rep... | g = pygithub | random_line_split |
msc_chart.py | from datetime import datetime, timedelta
from enum import Enum
from time import sleep
from typing import Dict, List, Optional, Tuple
from github import Github
from github.GithubException import RateLimitExceededException
from github.Issue import Issue
from github.IssueEvent import IssueEvent
from github.Label import L... | (
self,
msc: Issue,
msc_events: List[Tuple[IssueEvent, Optional[Label]]],
dt: datetime,
) -> MSCState:
"""Given a datetime, get the state of an MSC at that time
Args:
msc: The MSC to target,
msc_events: A cached List of github issue events to ... | _get_msc_state_at_time | identifier_name |
msc_chart.py | from datetime import datetime, timedelta
from enum import Enum
from time import sleep
from typing import Dict, List, Optional, Tuple
from github import Github
from github.GithubException import RateLimitExceededException
from github.Issue import Issue
from github.IssueEvent import IssueEvent
from github.Label import L... |
fig = go.Figure(
data=[
go.Pie(
labels=labels,
values=values,
sort=False, # Use order of lists above instead of sorting by size
)
],
)
# Make a nice title
fig.update_lay... | labels[idx] = f"{label} ({values[idx]})" | conditional_block |
msc_chart.py | from datetime import datetime, timedelta
from enum import Enum
from time import sleep
from typing import Dict, List, Optional, Tuple
from github import Github
from github.GithubException import RateLimitExceededException
from github.Issue import Issue
from github.IssueEvent import IssueEvent
from github.Label import L... |
def _generate_stacked_area_chart(self, filepath: str):
"""Generates a historical stacked area chart of msc status"""
# Get time of the earliest issue
mscs = list(
self.repository.get_issues(
sort="created", state="all", direction="asc", labels=["proposal"],
... | """Generate the chart
Args:
type: The type of chart to generate
filepath: Where to place the generated chart
"""
# Choose which chart type to generate
if type == ChartType.PIE:
self._generate_msc_pie_chart(filepath)
elif type == ChartType.STAC... | identifier_body |
main.rs | extern crate dotenv;
extern crate iron;
extern crate handlebars;
extern crate handlebars_iron as hbs;
#[macro_use]
extern crate router;
#[cfg(not(feature = "serde_type"))]
extern crate rustc_serialize;
extern crate mount;
extern crate staticfile;
extern crate reqwest;
extern crate serde_json;
extern crate iron_sessions... | let mut resp = Response::new();
resp.set_mut(Template::new("index", data)).set_mut(status::Ok);
Ok(Response::with((status::Found, Redirect(
Url::parse(redirect_url.as_str()).expect("parse url failed")
))))
... | })
},
None => HashMap::<String, Json>::new(),
};
| random_line_split |
main.rs | extern crate dotenv;
extern crate iron;
extern crate handlebars;
extern crate handlebars_iron as hbs;
#[macro_use]
extern crate router;
#[cfg(not(feature = "serde_type"))]
extern crate rustc_serialize;
extern crate mount;
extern crate staticfile;
extern crate reqwest;
extern crate serde_json;
extern crate iron_sessions... |
#[derive(Debug)]
struct AccessToken(String);
impl iron_sessionstorage::Value for AccessToken {
fn get_key() -> &'static str { "access_token" }
fn into_raw(self) -> String { self.0 }
fn from_raw(value: String) -> Option<Self> {
Some(AccessToken(value))
}
}
fn main() {
dotenv().ok();
... | {
match x {
Value::Number(ref x) if x.is_i64() => Json::I64(x.as_i64().unwrap()),
Value::Number(ref x) if x.is_u64() => Json::U64(x.as_u64().unwrap()),
Value::Number(ref x) if x.is_f64() => Json::F64(x.as_f64().unwrap()),
Value::String(x) => Json::String(x),
Value::Array(x) =... | identifier_body |
main.rs | extern crate dotenv;
extern crate iron;
extern crate handlebars;
extern crate handlebars_iron as hbs;
#[macro_use]
extern crate router;
#[cfg(not(feature = "serde_type"))]
extern crate rustc_serialize;
extern crate mount;
extern crate staticfile;
extern crate reqwest;
extern crate serde_json;
extern crate iron_sessions... | (String);
impl iron_sessionstorage::Value for AccessToken {
fn get_key() -> &'static str { "access_token" }
fn into_raw(self) -> String { self.0 }
fn from_raw(value: String) -> Option<Self> {
Some(AccessToken(value))
}
}
fn main() {
dotenv().ok();
let port = match env::var("PORT") {
... | AccessToken | identifier_name |
MySVN.py | #!/usr/bin/env python
"""
svn2svn.py
Replicate changesets from one SVN repository to another,
includes diffs, comments, and Dates of each revision.
It's also possible to retain the Author info if the Target SVN URL
is in a local filesystem (ie, running svn2svn.py on Target SVN server),
or if Target SVN URL i... | (message, raise_exception = True):
"""
Display error message, then terminate.
"""
print "Error:", message
print
if raise_exception:
raise ExternalCommandFailed
else:
sys.exit(1)
# Windows compatibility code by Bill Baxter
if os.name == "nt":
def find_program... | display_error | identifier_name |
MySVN.py | #!/usr/bin/env python
"""
svn2svn.py
Replicate changesets from one SVN repository to another,
includes diffs, comments, and Dates of each revision.
It's also possible to retain the Author info if the Target SVN URL
is in a local filesystem (ie, running svn2svn.py on Target SVN server),
or if Target SVN URL i... |
except KeyboardInterrupt:
print "\nStopped by user."
run_svn(["cleanup"])
run_svn(["revert", "--recursive", "."])
except:
print "\nCommand failed with following error:\n"
traceback.print_exc()
run_svn(["cleanup"])
run_svn(["revert", "--recursiv... | pull_svn_rev(log_entry, svn_url, target_url, svn_path,
original_wc, keep_author) | conditional_block |
MySVN.py | #!/usr/bin/env python
"""
svn2svn.py
Replicate changesets from one SVN repository to another,
includes diffs, comments, and Dates of each revision.
It's also possible to retain the Author info if the Target SVN URL
is in a local filesystem (ie, running svn2svn.py on Target SVN server),
or if Target SVN URL i... |
locale_encoding = locale.getpreferredencoding()
def run_svn(args, fail_if_stderr=False, encoding="utf-8"):
"""
Run svn cmd in PIPE
exit if svn cmd failed
"""
def _transform_arg(a):
if isinstance(a, unicode):
a = a.encode(encoding or locale_encoding)
elif no... | if os.name == "nt":
q = '"'
else:
q = "'"
return q + s.replace('\\', '\\\\').replace("'", "'\"'\"'") + q | identifier_body |
MySVN.py | #!/usr/bin/env python
"""
svn2svn.py
Replicate changesets from one SVN repository to another,
includes diffs, comments, and Dates of each revision.
It's also possible to retain the Author info if the Target SVN URL
is in a local filesystem (ie, running svn2svn.py on Target SVN server),
or if Target SVN URL i... | print "*", unrelated_paths
## too many files
if len (commit_paths) > 99:
commit_paths = []
try:
commit_from_svn_log_entry(log_entry, commit_paths,
keep_author=keep_author)
except ExternalCommandFailed:
# try to ignore the Pro... | random_line_split | |
base.js | var user={
pid:GetQueryString("pid"),
sid:GetQueryString("sid")
};
var serverUrl01="https://www.member361.com";//84正式服务器
var serverUrl02="https://121.43.150.38";//38测试服务器
var serverUrl03="http://106.15.89.156";//156测试服务器
var serverHost="https://www.member361.com";
var path=serverUrl01; //更改服务器地址可设置此值
var httpUrl={... | identifier_body | ||
base.js | var user={
pid:GetQueryString("pid"),
sid:GetQueryString("sid")
};
var serverUrl01="https://www.member361.com";//84正式服务器
var serverUrl02="https://121.43.150.38";//38测试服务器
var serverUrl03="http://106.15.89.156";//156测试服务器
var serverHost="https://www.member361.com";
var path=serverUrl01; //更改服务器地址可设置此值
var httpUrl={... |
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": th... | }; | random_line_split |
base.js | var user={
pid:GetQueryString("pid"),
sid:GetQueryString("sid")
};
var serverUrl01="https://www.member361.com";//84正式服务器
var serverUrl02="https://121.43.150.38";//38测试服务器
var serverUrl03="http://106.15.89.156";//156测试服务器
var serverHost="https://www.member361.com";
var path=serverUrl01; //更改服务器地址可设置此值
var httpUrl={... | identifier_name | ||
base.js | var user={
pid:GetQueryString("pid"),
sid:GetQueryString("sid")
};
var serverUrl01="https://www.member361.com";//84正式服务器
var serverUrl02="https://121.43.150.38";//38测试服务器
var serverUrl03="http://106.15.89.156";//156测试服务器
var serverHost="https://www.member361.com";
var path=serverUrl01; //更改服务器地址可设置此值
var httpUrl={... | conditional_block | ||
pouch-db-singleton.ts | /**
* @license
* Copyright (c) 2017 Google Inc. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io... | (): Promise<{version: number; model: SerializedModelEntry[]}> {
await this.initialized;
const doc = await this.upsert(async doc => doc);
const value = doc.value;
let model: SerializedModelEntry[] = [];
if (value != null) {
model = [
{
id: value.id,
keys: [],
... | serializeContents | identifier_name |
pouch-db-singleton.ts | /**
* @license
* Copyright (c) 2017 Google Inc. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io... | }
await this._fire(new ChangeEvent({data: newvalue, version: this._version}));
}
}
/**
* Returns the model data in a format suitable for transport over
* the API channel (i.e. between execution host and context).
*/
async modelForSynchronization() {
await this.initialized;
const... | doc.referenceMode = this.referenceMode;
doc.version = Math.max(this._version, doc.version) + 1;
return doc;
}); | random_line_split |
pouch-db-singleton.ts | /**
* @license
* Copyright (c) 2017 Google Inc. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io... |
}
}
/**
* Get/Modify/Set the data stored for this singleton.
*/
private async upsert(mutatorFn: UpsertMutatorFn<SingletonStorage>): Promise<SingletonStorage> {
const defaultDoc: SingletonStorage = {
value: null,
version: 0,
referenceMode: this.referenceMode
};
const doc =... | {
await this._fire(new ChangeEvent({data: value, version: this._version}));
} | conditional_block |
world.py | #-*- coding:utf-8 -*-
import roslib
import rospy
import math
import time
import actionlib
from actionlib_msgs.msg import *
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from nav_msgs.msg import OccupancyGrid
from nav_msgs.msg import MapMetaData
from geometry_msgs.msg import Pose , Point ... | return (-1,self.targetReward)
elif state in self.traps :
return (-1,self.trapReward)
elif state in self.walls :
return (0,self.wallReward)
else:
return (0,self.norReward)
def isLegalState(self,state):
if state >= 0 and state <... | if state in self.targets :
| random_line_split |
world.py | #-*- coding:utf-8 -*-
import roslib
import rospy
import math
import time
import actionlib
from actionlib_msgs.msg import *
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from nav_msgs.msg import OccupancyGrid
from nav_msgs.msg import MapMetaData
from geometry_msgs.msg import Pose , Point ... | (self,state):
if state < 0 or state >= self.rows * self.cols:
return False
state = self.state_to_map[state]
row = state / self.cols
col = state - row * self.cols
if self.map[row][col] == 'g':
return True
return False
de... | isTarget | identifier_name |
world.py | #-*- coding:utf-8 -*-
import roslib
import rospy
import math
import time
import actionlib
from actionlib_msgs.msg import *
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from nav_msgs.msg import OccupancyGrid
from nav_msgs.msg import MapMetaData
from geometry_msgs.msg import Pose , Point ... | ll.Y ) > math.fabs(targetCell.Y - state.realCell.Y) :
addreward += 20
if math.fabs(targetCell.Y - state.realCell.Y) <= 1 :
addreward += 5
if math.fabs( targetCell.Y - state.curCell.Y ) < math.fabs(targetCell.Y - state.realCell.Y) :
addrewa... | d -= 50
if math.fabs( targetCell.Y - state.curCe | conditional_block |
world.py | #-*- coding:utf-8 -*-
import roslib
import rospy
import math
import time
import actionlib
from actionlib_msgs.msg import *
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from nav_msgs.msg import OccupancyGrid
from nav_msgs.msg import MapMetaData
from geometry_msgs.msg import Pose , Point ... | if self.Map != None :
print(self.getStateNum(self.Map.getCell(pos)))
# mapspace = Map()
# world = World()
# def getMap(data):
# global mapspace
# data = data.data
# mapspace.setMap(data)
# def getMapMetaData(data):
# global mapspace
# mapspace.setMapPar... | urn cell
def getPositionStateNum(self,pos):
| identifier_body |
sheetDocument.ts | import _ from "lodash";
import {CM_TO_PX} from "../constants";
import {roundNumber} from "./utils";
// eslint-disable-next-line
import StaffToken from "./staffToken";
// eslint-disable-next-line
import * as LilyNotation from "../lilyNotation";
interface SheetMarkingData {
id: string;
text: string;
x: number;
y... | const bottom = Math.max(...rects.map(rect => rect[3]), ...tokenYs);
const x = verticalCropOnly ? page.viewBox.x : left - margin;
const y = (verticalCropOnly && i === 0) ? page.viewBox.y : top - margin;
const width = verticalCropOnly ? page.viewBox.width : right - left + margin * 2;
const height = (verti... | const left = Math.min(...rects.map(rect => rect[0]), ...tokenXs);
const right = Math.max(...rects.map(rect => rect[1]), ...tokenXs);
const top = Math.min(...rects.map(rect => rect[2]), ...tokenYs); | random_line_split |
sheetDocument.ts |
import _ from "lodash";
import {CM_TO_PX} from "../constants";
import {roundNumber} from "./utils";
// eslint-disable-next-line
import StaffToken from "./staffToken";
// eslint-disable-next-line
import * as LilyNotation from "../lilyNotation";
interface SheetMarkingData {
id: string;
text: string;
x: number;
... | (): number{
return Math.max(...this.systems.map(system => system.staves.length), 0);
}
get pageSize (): {width: number, height: number} {
const page = this.pages && this.pages[0];
if (!page)
return null;
return {
width: parseUnitExp(page.width),
height: parseUnitExp(page.height),
};
}
updat... | trackCount | identifier_name |
sw_06_cv_functions.py | import cv2
import numpy as np
from numpy.lib.stride_tricks import as_strided
import traceback
import warnings
import numpy
# import rospy
## Software Exercise 6: Choose your category (1 or 2) and replace the cv2 code by your own!
## CATEGORY 1
def inRange(hsv_image, low_range, high_range):
return cv2.inRange(hsv_im... |
def indices_where(condition):
return np.concatenate(np.dstack(np.where(condition)))
def index_with(list_of_indices):
return list_of_indices[:, 0], list_of_indices[:, 1]
def neighbourhood(index, image_width, image_height):
"""Returns the coordinates of the neighbours of a given coordinate or list of coordinates.
... | return np.concatenate(np.dstack(list_of_indices)) | identifier_body |
sw_06_cv_functions.py | import cv2
import numpy as np
from numpy.lib.stride_tricks import as_strided
import traceback
import warnings
import numpy
# import rospy
## Software Exercise 6: Choose your category (1 or 2) and replace the cv2 code by your own!
## CATEGORY 1
def inRange(hsv_image, low_range, high_range):
return cv2.inRange(hsv_im... | (list_of_indices):
return np.concatenate(np.dstack(list_of_indices))
def indices_where(condition):
return np.concatenate(np.dstack(np.where(condition)))
def index_with(list_of_indices):
return list_of_indices[:, 0], list_of_indices[:, 1]
def neighbourhood(index, image_width, image_height):
"""Returns the coordin... | aggregate | identifier_name |
sw_06_cv_functions.py | import cv2
import numpy as np
from numpy.lib.stride_tricks import as_strided
import traceback
import warnings
import numpy
# import rospy
## Software Exercise 6: Choose your category (1 or 2) and replace the cv2 code by your own!
## CATEGORY 1
def inRange(hsv_image, low_range, high_range):
return cv2.inRange(hsv_im... |
x = np.pad(x, padding, mode=padding_mode)
# Window view of X
output_shape = ((x.shape[0] - kernel.shape[0])//stride + 1,
(x.shape[1] - kernel.shape[1])//stride + 1)
x_w = as_strided(
x,
shape=output_shape + kernel.shape,
strides = (
stride*x.strides[0],
stride*x.strides[1]
) + x.strides
)
# ... | padding = np.array(kernel.shape) // 2 | conditional_block |
sw_06_cv_functions.py | import cv2
import numpy as np
from numpy.lib.stride_tricks import as_strided
import traceback
import warnings
import numpy
# import rospy
## Software Exercise 6: Choose your category (1 or 2) and replace the cv2 code by your own!
## CATEGORY 1
def inRange(hsv_image, low_range, high_range):
return cv2.inRange(hsv_im... | NOTE: the pixels neighbours are clipped of (image_height-1, )
Returns:
np.ndarray -- ndarray of shape [?, 2], which contains the indices of the neighbouring pixels
"""
neighbourhoods = np.concatenate(np.dstack((np.indices([3,3]) - 1)))
if len(index.shape) == 2:
neighbourhoods = neighbourhoods[:, np.newaxis,... | random_line_split | |
apitest.go | package apitest
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/PaesslerAG/jsonpath"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"testing"
)
// APITest is the top level struct holding the test spec
type APITest struct {
handler http.Handler... | func (r *Response) CookieNotPresent(cookieName string) *Response {
r.cookiesNotPresent = append(r.cookiesNotPresent, cookieName)
return r
}
// Headers is the expected response headers
func (r *Response) Headers(headers map[string]string) *Response {
r.headers = headers
return r
}
// Status is the expected respons... | // CookieNotPresent is used to assert that a cookie is not present in the response | random_line_split |
apitest.go | package apitest
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/PaesslerAG/jsonpath"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"testing"
)
// APITest is the top level struct holding the test spec
type APITest struct {
handler http.Handler... | (url string) *Request {
r.method = http.MethodPost
r.url = url
return r
}
// Put is a convenience method for setting the request as http.MethodPut
func (r *Request) Put(url string) *Request {
r.method = http.MethodPut
r.url = url
return r
}
// Delete is a convenience method for setting the request as http.Metho... | Post | identifier_name |
apitest.go | package apitest
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/PaesslerAG/jsonpath"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"testing"
)
// APITest is the top level struct holding the test spec
type APITest struct {
handler http.Handler... |
a.response.jsonPathAssert(value.(interface{}))
}
}
func isJSON(s string) bool {
var js map[string]interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
| {
assert.Nil(a.t, err)
} | conditional_block |
apitest.go | package apitest
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/PaesslerAG/jsonpath"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"testing"
)
// APITest is the top level struct holding the test spec
type APITest struct {
handler http.Handler... |
func buildQueryCollection(params map[string][]string) []pair {
if len(params) == 0 {
return []pair{}
}
var pairs []pair
for k, v := range params {
for _, paramValue := range v {
pairs = append(pairs, pair{l: k, r: paramValue})
}
}
return pairs
}
func (a *APITest) assertResponse(res *httptest.Response... | {
req, _ := http.NewRequest(a.request.method, a.request.url, bytes.NewBufferString(a.request.body))
query := req.URL.Query()
if a.request.queryCollection != nil {
for _, param := range buildQueryCollection(a.request.queryCollection) {
query.Add(param.l, param.r)
}
}
if a.request.query != nil {
for k, v ... | identifier_body |
raft.go | package raft
import (
"flag"
"fmt"
"log"
"math"
"math/rand"
"strings"
"time"
)
var hostfile string
var duration int
var verbose bool
// returns true when an agent has a majority of votes for the proposed view
func (r *RaftNode) wonElection() bool {
return haveMajority(r.votes, "ELECTION", r.verbose)
}
func ... | (ae AppendEntriesStruct, response *RPCResponse) error {
r.Lock()
defer r.Unlock()
if r.verbose {
log.Printf("AppendEntries(). ae: %s", ae.String())
log.Printf("My log: %s", r.Log.String())
}
response.Term = r.CurrentTerm
if ae.LeaderID == r.currentLeader {
if r.verbose {
log.Println("AppendEntries from... | AppendEntries | identifier_name |
raft.go | package raft
import (
"flag"
"fmt"
"log"
"math"
"math/rand"
"strings"
"time"
)
var hostfile string
var duration int
var verbose bool
// returns true when an agent has a majority of votes for the proposed view
func (r *RaftNode) wonElection() bool {
return haveMajority(r.votes, "ELECTION", r.verbose)
}
func ... | log.Printf("commitIndex %d ineligible because of log entry %s", n, r.Log[n].String())
}
continue
}
peersAtThisLevel := make(map[HostID]bool)
for hostID := range r.hosts {
if hostID == r.id {
peersAtThisLevel[hostID] = true
} else {
peersAtThisLevel[hostID] = r.matchIndex[hostID] >= n
}
... | // Then:
// set commitIndex = N
for n := r.commitIndex + 1; n <= r.getLastLogIndex(); n++ {
if r.Log[n].Term != r.CurrentTerm {
if r.verbose { | random_line_split |
raft.go | package raft
import (
"flag"
"fmt"
"log"
"math"
"math/rand"
"strings"
"time"
)
var hostfile string
var duration int
var verbose bool
// returns true when an agent has a majority of votes for the proposed view
func (r *RaftNode) wonElection() bool {
return haveMajority(r.votes, "ELECTION", r.verbose)
}
func ... |
func (r *RaftNode) QuitChan() chan bool {
return r.quitChan
}
// Start is the entrypoint for a raft node (constructed here or in a test) to begin the protocol
func (r *RaftNode) Start() {
go r.recvDaemon()
go r.protocol()
go r.quitter(duration)
<-r.quitChan
log.Println("FINISH EXPERIMENT...")
r.printResults()... | {
if x < y {
return x
}
return y
} | identifier_body |
raft.go | package raft
import (
"flag"
"fmt"
"log"
"math"
"math/rand"
"strings"
"time"
)
var hostfile string
var duration int
var verbose bool
// returns true when an agent has a majority of votes for the proposed view
func (r *RaftNode) wonElection() bool {
return haveMajority(r.votes, "ELECTION", r.verbose)
}
func ... |
return y
}
func min(x LogIndex, y LogIndex) LogIndex {
if x < y {
return x
}
return y
}
func (r *RaftNode) QuitChan() chan bool {
return r.quitChan
}
// Start is the entrypoint for a raft node (constructed here or in a test) to begin the protocol
func (r *RaftNode) Start() {
go r.recvDaemon()
go r.protocol... | {
return x
} | conditional_block |
svgfrags.py | #!/usr/bin/python
# -*- coding: iso-8859-2 -*-
# $Id: svgfrags.py,v 1.9 2007-03-13 20:55:37 wojtek Exp $
#
# SVGfrags - main program
#
# license: BSD
#
# author: Wojciech Muła
# e-mail: wojciech_mula@poczta.onet.pl
# WWW : http://0x80.pl/
"""
13.03.2007
- syntax chenges:
* keyword "this" as source
- use frags.g... |
if __name__ == '__main__':
import traceback
try:
main(sys.argv)
except SystemExit, (code):
sys.exit(code)
except:
if setup.options.print_traceback:
traceback.print_exc(file=sys.stderr)
else:
exception, instance, _ = sys.exc_info()
print >> sys.stderr, "Unexpeced error - %s: %s" % (exception.__nam... | remove temporary files"
extensions = ['.aux', '.log']
if not setup.options.frags_keeptex:
extensions.append('.tex')
if not setup.options.frags_keepdvi:
extensions.append('.dvi')
for ext in extensions:
frags.remove_file(tmp_filename + ext)
| identifier_body |
svgfrags.py | #!/usr/bin/python
# -*- coding: iso-8859-2 -*-
# $Id: svgfrags.py,v 1.9 2007-03-13 20:55:37 wojtek Exp $
#
# SVGfrags - main program
#
# license: BSD
#
# author: Wojciech Muła
# e-mail: wojciech_mula@poczta.onet.pl
# WWW : http://0x80.pl/
"""
13.03.2007
- syntax chenges:
* keyword "this" as source
- use frags.g... | exitstatus = os.system("latex %s.tex > /dev/null" % tmp_filename)
if exitstatus:
log.error("LaTeX failed - error code %d; check log file '%s.log'", exitstatus, tmp_filename)
sys.exit(2)
else:
log.error("Program 'latex' isn't avaialable.")
sys.exit(3)
else:
log.info("File %s not changed, used ex... | tmp.write(line + "\n")
tmp.close()
if which('latex'): | random_line_split |
svgfrags.py | #!/usr/bin/python
# -*- coding: iso-8859-2 -*-
# $Id: svgfrags.py,v 1.9 2007-03-13 20:55:37 wojtek Exp $
#
# SVGfrags - main program
#
# license: BSD
#
# author: Wojciech Muła
# e-mail: wojciech_mula@poczta.onet.pl
# WWW : http://0x80.pl/
"""
13.03.2007
- syntax chenges:
* keyword "this" as source
- use frags.g... | self, filename):
defs = self.document.getElementsByTagName('defs')[0]
for element in self.flush_glyphs():
defs.appendChild(element)
# save file
f = open(filename, 'wb')
if setup.options.prettyXML:
f.write(self.document.toprettyxml())
else:
f.write(self.document.toxml())
f.close()
def main(args... | ave( | identifier_name |
svgfrags.py | #!/usr/bin/python
# -*- coding: iso-8859-2 -*-
# $Id: svgfrags.py,v 1.9 2007-03-13 20:55:37 wojtek Exp $
#
# SVGfrags - main program
#
# license: BSD
#
# author: Wojciech Muła
# e-mail: wojciech_mula@poczta.onet.pl
# WWW : http://0x80.pl/
"""
13.03.2007
- syntax chenges:
* keyword "this" as source
- use frags.g... | else: # XML id
sx = get_height(val[1][1:], dx)/dx
elif kind == "length":
sx = val/dx
if type(sy) is tuple:
kind, val = sy
sy = 1.0
if kind == 'width':
if val == 'this': pass # no scale
else: # XML id
sy = get_width(val[1][1:], dy)/dy
e... | ass # no scale
| conditional_block |
update_configuration_files.py | """A script for updating pre-existing V2 Pipette configurations."""
import os
import json
import argparse
from pathlib import Path
from typing import List, Dict, Tuple, Any, Iterator, Type
from pydantic import BaseModel
from pydantic.main import ModelMetaclass
from enum import Enum
from opentrons_shared_data import ... | (c: str) -> str:
# Tiny helper function to convert to camelCase.
config_name = c.split("_")
if len(config_name) == 1:
return config_name[0]
return f"{config_name[0]}" + "".join(s.capitalize() for s in config_name[1::])
def list_configuration_keys() -> Tuple[List[str], Dict[int, str]]:
"""L... | _change_to_camel_case | identifier_name |
update_configuration_files.py | """A script for updating pre-existing V2 Pipette configurations."""
import os
import json
import argparse
from pathlib import Path
from typing import List, Dict, Tuple, Any, Iterator, Type
from pydantic import BaseModel
from pydantic.main import ModelMetaclass
from enum import Enum
from opentrons_shared_data import ... |
def build_nozzle_map(
nozzle_offset: List[float], channels: PipetteChannelType
) -> Dict[str, List[float]]:
Y_OFFSET = 9
X_OFFSET = -9
breakpoint()
if channels == PipetteChannelType.SINGLE_CHANNEL:
return {"A1": nozzle_offset}
elif channels == PipetteChannelType.EIGHT_CHANNEL:
... | """
Recursively update the given dictionary to ensure no data is lost when updating.
"""
next_key = next(iter_of_configs, None)
if next_key and isinstance(dict_to_update[next_key], dict):
dict_to_update[next_key] = update(
dict_to_update.get(next_key, {}), iter_of_configs, value_to_u... | identifier_body |
update_configuration_files.py | """A script for updating pre-existing V2 Pipette configurations."""
import os
import json
import argparse
from pathlib import Path
from typing import List, Dict, Tuple, Any, Iterator, Type
from pydantic import BaseModel
from pydantic.main import ModelMetaclass
from enum import Enum
from opentrons_shared_data import ... |
channels = list(PipetteChannelType)[int(input("Please select from above\n"))]
version = PipetteVersionType.convert_from_float(
float(check_from_version(input("Please input the version of the model\n")))
)
built_model: PipetteModel = PipetteModel(
f"{model.name}_{str(channels)}_v{versi... | print(f"\t{row}") | conditional_block |
update_configuration_files.py | """A script for updating pre-existing V2 Pipette configurations."""
import os
import json
import argparse
from pathlib import Path
from typing import List, Dict, Tuple, Any, Iterator, Type
from pydantic import BaseModel
from pydantic.main import ModelMetaclass
from enum import Enum
from opentrons_shared_data import ... | print("Otherwise, please type 'null' on the next line.\n")
value_to_update = json.loads(
input(
f"Please select what you would like to update {configuration_to_update} to for {built_model}\n"
)
)
... | "You selected nozzle_map to edit. If you wish to update the nozzle offset, enter it on the next line.\n"
) | random_line_split |
adversarial_semantic_dis_trainer.py | import argparse
import os
import glob
import pprint
import pickle
import time
import torch
from torch.nn import functional as F
import torch.optim as optim
import pytorch3d.structures
from pytorch3d.io import load_objs_as_meshes
from pytorch3d.io import load_obj
from pytorch3d.structures import Meshes
from pytorch3d.r... |
def train(self):
# setting up dataloaders
# https://stackoverflow.com/questions/51444059/how-to-iterate-over-two-dataloaders-simultaneously-using-pytorch
generation_dataset = GenerationDataset(cfg, self.device)
generation_loader = torch.utils.data.DataLoader(generation_dataset, b... | self.cfg = utils.load_config(cfg_path, "configs/default.yaml")
self.device = torch.device("cuda:"+str(gpu_num))
self.batch_size = self.cfg["semantic_dis_training"]["batch_size"]
self.total_training_iters = 2
self.num_batches_dis_train = 5
self.num_batches_gen_train = 5
s... | identifier_body |
adversarial_semantic_dis_trainer.py | import argparse
import os
import glob
import pprint
import pickle
import time
import torch
from torch.nn import functional as F
import torch.optim as optim
import pytorch3d.structures
from pytorch3d.io import load_objs_as_meshes
from pytorch3d.io import load_obj
from pytorch3d.structures import Meshes
from pytorch3d.r... |
return loss_dict, deformed_mesh
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Adversarially train a SemanticDiscriminatorNetwork.')
parser.add_argument('cfg_path', type=str, help='Path to yaml configuration file.')
parser.add_argument('--gpu', type=int... | loss_dict["semantic_dis_loss"] = torch.tensor(0).to(self.device) | conditional_block |
adversarial_semantic_dis_trainer.py | import argparse
import os
import glob
import pprint
import pickle
import time
import torch
from torch.nn import functional as F
import torch.optim as optim
import pytorch3d.structures
from pytorch3d.io import load_objs_as_meshes
from pytorch3d.io import load_obj
from pytorch3d.structures import Meshes
from pytorch3d.r... |
dis_loss = F.binary_cross_entropy_with_logits(pred_logits_real, real_labels) + \
F.binary_cross_entropy_with_logits(pred_logits_fake, fake_labels)
dis_loss.backward()
dis_optimizer.step()
continue
... | fake_labels = fake_labels_dist.sample((batch_size,1)).squeeze(2).to(self.device) | random_line_split |
adversarial_semantic_dis_trainer.py | import argparse
import os
import glob
import pprint
import pickle
import time
import torch
from torch.nn import functional as F
import torch.optim as optim
import pytorch3d.structures
from pytorch3d.io import load_objs_as_meshes
from pytorch3d.io import load_obj
from pytorch3d.structures import Meshes
from pytorch3d.r... | (self):
# setting up dataloaders
# https://stackoverflow.com/questions/51444059/how-to-iterate-over-two-dataloaders-simultaneously-using-pytorch
generation_dataset = GenerationDataset(cfg, self.device)
generation_loader = torch.utils.data.DataLoader(generation_dataset, batch_size=self.b... | train | identifier_name |
endpoint.rs | use std::fmt;
use std::fs;
use std::io::{
self,
Read,
Write,
};
use std::num::ParseIntError;
use std::str;
use super::Driver;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SlotFunction(pub u8);
impl SlotFunction {
pub fn slot(&self) -> u8 {
self.0 >> 3
}
pub fn function(&self) -> u... | (mut self) -> crate::AResult<()> {
if let Some(ep) = self.ep.take() {
ep.disable()?;
}
Ok(())
}
}
impl Drop for ScopedEnable {
fn drop(&mut self) {
if let Some(ep) = self.ep.take() {
if let Err(e) = ep.disable() {
error!("PCI {}: Failed to disable temporarily enabled device: {}", ep, e);
}
}
... | close | identifier_name |
endpoint.rs | use std::fmt;
use std::fs;
use std::io::{
self,
Read,
Write,
};
use std::num::ParseIntError;
use std::str;
use super::Driver;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SlotFunction(pub u8);
impl SlotFunction {
pub fn slot(&self) -> u8 {
self.0 >> 3
}
pub fn function(&self) -> u... |
// short: 0.0, long: 1f.7
let (dev_s, fun_s) = if r.len() == 3 && r[1] == b'.' {
(&s[0..1], &s[2..3])
} else if r.len() == 4 && r[2] == b'.' {
(&s[0..2], &s[3..4])
} else {
bail!("Couldn't find '.' in valid place for PCI device.function: {:?}", s);
};
let dev = with_context!(("invalid PCI device:... | fn from_str(s: &str) -> Result<Self, Self::Err> {
let r = s.as_bytes();
ensure!(r.len() <= 4, "String too long for PCI device.function: {:?}", s); | random_line_split |
common.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
Some(peaks)
}
/// Calculates the positions of the (parent, sibling) of the node at the provided position.
/// Returns an error if the pos provided would result in an underflow or overflow.
pub fn family(pos: usize) -> Result<(usize, usize), MerkleMountainRangeError> {
let (peak_map, height) = peak_map_height(... | {
// This happens, whenever the MMR is not valid, that is, all nodes are not
// fully spawned. For example, in this case
// 2
// / \
// 0 1 3 4
// is invalid, as it can be completed to form
// 6
// / \
// 2 5
... | conditional_block |
common.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | () {
assert_eq!(peak_map_height(0), (0, 0));
assert_eq!(peak_map_height(4), (0b11, 0));
// 6
// 2 5
// 0 1 3 4 7 8
assert_eq!(peak_map_height(9), (0b101, 1));
// 6
// 2 5 9
// 0 1 3 4 7 8 *
assert_e... | peak_map_heights | identifier_name |
common.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | // A tree with over a million nodes in it find the "family path" back up the tree from a leaf node at 0.
// Note: the first two entries in the branch are consistent with a small 7 node tree.
// Note: each sibling is on the left branch, this is an example of the largest possible list of peaks
... | assert_eq!(family_branch(3, 6), [(5, 4), (6, 2)]);
| random_line_split |
common.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
/// Is the node at this pos the "left" sibling of its parent?
pub fn is_left_sibling(pos: usize) -> bool {
let (peak_map, height) = peak_map_height(pos);
let peak = 1 << height;
(peak_map & peak) == 0
}
pub fn hash_together<D: Digest + DomainDigest>(left: &[u8], right: &[u8]) -> Hash {
D::new().chain... | {
if pos == 0 {
return (0, 0);
}
let mut peak_size = ALL_ONES >> pos.leading_zeros();
let mut bitmap = 0;
while peak_size != 0 {
bitmap <<= 1;
if pos >= peak_size {
pos -= peak_size;
bitmap |= 1;
}
peak_size >>= 1;
}
(bitmap, po... | identifier_body |
search_log.go | // Copyright 2019 PingCAP, 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... | cursor -= size
_, err := file.Seek(cursor, io.SeekStart)
if err != nil {
return nil, 0, ctx.Err()
}
chars := make([]byte, size)
_, err = file.Read(chars)
if err != nil {
return nil, 0, ctx.Err()
}
lines = append(chars, lines...)
// find first '\n' or '\r'
for i := 0; i < len(chars)-1; i++ ... | } | random_line_split |
search_log.go | // Copyright 2019 PingCAP, 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... |
func isCtxDone(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}
func readFirstValidLog(ctx context.Context, reader *bufio.Reader, tryLines int64) (*pb.LogMessage, error) {
var tried int64
for {
line, err := readLine(reader)
if err != nil {
return nil, err... | {
if logFilePath == "" {
return nil, errors.New("empty log file location configuration")
}
var logFiles []logFile
var skipFiles []*os.File
logDir := filepath.Dir(logFilePath)
ext := filepath.Ext(logFilePath)
filePrefix := logFilePath[:len(logFilePath)-len(ext)]
files, err := ioutil.ReadDir(logDir)
if err !=... | identifier_body |
search_log.go | // Copyright 2019 PingCAP, 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... |
}
return string(line), nil
}
const maxReadCacheSize = 1024 * 1024 * 16
// Read lines from the end of a file
// endCursor initial value should be the file size
func readLastLines(ctx context.Context, file *os.File, endCursor int64) ([]string, int, error) {
var lines []byte
var firstNonNewlinePos int
var cursor =... | {
return "", err
} | conditional_block |
search_log.go | // Copyright 2019 PingCAP, 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.Context, file *os.File, endCursor int64) ([]string, int, error) {
var lines []byte
var firstNonNewlinePos int
var cursor = endCursor
var size int64 = 256
for {
// stop if we are at the begining
// check it in the start to avoid read beyond the size
if cursor <= 0 {
break
}
// enlarge the... | readLastLines | identifier_name |
lisp.go | // ---------------------------------------------------------------------------
//
// Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may o... |
//
// lisp_count
//
// Increment stats counters. Either do it for an RLOC/RLE entry or for the
// lisp_decap_stats map. Argument 'key-name' needs to be set if stats is nil.
//
func lisp_count(stats *Lisp_stats, key_name string, packet []byte) {
if (stats == nil) {
s, ok := lisp_decap_stats[key_name]
if (!ok) {
... | random_line_split | |
lisp.go | // ---------------------------------------------------------------------------
//
// Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may o... |
if (a.instance_id != addr.instance_id) {
return(false)
}
if (a.address.Equal(addr.address) == false) {
return(false)
}
return(true)
}
//
// lisp_more_specific
//
// Return true if the supplied address is more specific than the method
// address. If the mask-lengths are the same, a true is returned.
//
func (... | {
return(false)
} | conditional_block |
lisp.go | // ---------------------------------------------------------------------------
//
// Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may o... | (command string) string {
cmd := exec.Command(command)
out, err := cmd.CombinedOutput()
if (err != nil) {
return("")
}
output := string(out)
return(output[0:len(output)-1])
}
//
// lisp_read_file
//
// Read entire file into a string.
//
func lisp_read_file(filename string) string {
fd, err := os.Open(filename... | lisp_command_output | identifier_name |
lisp.go | // ---------------------------------------------------------------------------
//
// Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may o... |
//
// lisp_is_ipv6
//
// Return true if Lisp_address is IPv6.
//
func (a *Lisp_address) lisp_is_ipv6() bool {
return((len(a.address) == 16))
}
//
// lisp_is_multicast
//
// Return true if Lisp_address is an IPv4 or IPv6 multicast group address.
//
func (a *Lisp_address) lisp_is_multicast() bool {
if (a.lisp_is_ipv... | {
return((len(a.address) == 4))
} | identifier_body |
FastSlamV2.py | import rospy
import tf
from nav_msgs.msg import Odometry
from aruco_msgs.msg import MarkerArray
import numpy as np
import matplotlib.pyplot as plt
import time
#Ponto de partida (0,0) - Porta da sala
#Marker de id 0 tem coordenadas (x_map0,y_map0) em metros
x_map=[0.0]*41;
y_map=[0.0]*41;
x_map[0]=0.097+0.385;
y_map[... | (self):
return self.read_move
def get_movement(self):
msg = self.read_move
self.read_move = np.array([0, 0, 0], dtype='float64').transpose()
return msg
def get_total_movement(self):
return self.total_movement
def FastSlam():
odom_measurement = odom()
particles = [Particle() for i in range(NUMBER_... | actual_movement | identifier_name |
FastSlamV2.py | import rospy
import tf
from nav_msgs.msg import Odometry
from aruco_msgs.msg import MarkerArray
import numpy as np
import matplotlib.pyplot as plt
import time
#Ponto de partida (0,0) - Porta da sala
#Marker de id 0 tem coordenadas (x_map0,y_map0) em metros
x_map=[0.0]*41;
y_map=[0.0]*41;
x_map[0]=0.097+0.385;
y_map[... |
def callback_odom(self, data):
# robo_frame
frame_id = data.header.frame_id # odom
child_frame_id = data.child_frame_id # base_link
# pose
x = data.pose.pose.position.x # front-back
y = data.pose.pose.position.y # right-left
orientation_x = data.pose.pose.orientation.x
orientation_y = data... | self.read_move = np.array([0, 0, 0], dtype='float64').transpose()
self.first_read = True | identifier_body |
FastSlamV2.py | import rospy
import tf
from nav_msgs.msg import Odometry
from aruco_msgs.msg import MarkerArray
import numpy as np
import matplotlib.pyplot as plt
import time
#Ponto de partida (0,0) - Porta da sala
#Marker de id 0 tem coordenadas (x_map0,y_map0) em metros
x_map=[0.0]*41;
y_map=[0.0]*41;
x_map[0]=0.097+0.385;
y_map[... |
marker_line.set_xdata(x_f)
marker_line.set_ydata(y_f)
ax.draw_artist(ax.patch)
ax.draw_artist(marker_line)
fig.canvas.flush_events()
def resample_particles(particles, updated_marker):
# Returns a new set of particles obtained by performing stochastic universal sampling, according to the particle weights.
# d... | if marker == None:
x_f[i] = KEY_NUMBER + circle
y_f[i] = KEY_NUMBER + circle
i += 1
continue
pose_m = marker.get_marker_position()
x_m = pose_m[0]
y_m = pose_m[1]
std_m = marker.get_marker_covariance()
x_std_m = std_m[0][0]
y_std_m = std_m[1][1]
x_f[i] = x_m + x_std_m * np.cos(circle)
y_f[i]... | conditional_block |
FastSlamV2.py | import rospy
import tf
from nav_msgs.msg import Odometry
from aruco_msgs.msg import MarkerArray
import numpy as np
import matplotlib.pyplot as plt
import time
#Ponto de partida (0,0) - Porta da sala
#Marker de id 0 tem coordenadas (x_map0,y_map0) em metros
x_map=[0.0]*41;
y_map=[0.0]*41;
x_map[0]=0.097+0.385;
y_map[... | self.S = np.linalg.inv(self.G_o.dot(np.linalg.inv(self.R_t).dot(self.G_o.T)))
self.V = np.array([0, 0], dtype='float64').transpose()
self.L_t = np.identity(number_of_dimensions, dtype='float64')
else:
# Prediction
y = self.X_[y] - X_robot[y]
x = self.X_[x] - X_robot[x]
d = np.sqrt(x**2 + y**2)... |
self.X_ = np.array([X_robot[x] + Z[d]*np.cos(angle), X_robot[y] + Z[d]*np.sin(angle)], dtype='float64').transpose() # first landmark position
self.compute_G(X_robot) | random_line_split |
hellweg.py | # -*- coding: utf-8 -*-
u"""Hellweg execution template.
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcollections
from pykern import pkio
from pyker... | (models):
# BEAM SPH2D 0.564 -15 5 NORM2D 0.30 0.0000001 90 180
beam_def = models.beam.beamDefinition
if beam_def == 'transverse_longitude':
return 'BEAM {} {}'.format(_generate_transverse_dist(models), _generate_longitude_dist(models))
if beam_def == 'cst_pit':
return 'BEAM CST_PIT {} {... | _generate_beam | identifier_name |
hellweg.py | # -*- coding: utf-8 -*-
u"""Hellweg execution template.
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcollections
from pykern import pkio
from pyker... |
def lib_files(data, source_lib):
return template_common.filename_to_path(_simulation_files(data), source_lib)
def get_simulation_frame(run_dir, data, model_data):
frame_index = int(data['frameIndex'])
if data['modelName'] == 'beamAnimation':
args = template_common.parse_animation_args(
... | if data['method'] == 'compute_particle_ranges':
return template_common.compute_field_range(data, _compute_range_across_files)
assert False, 'unknown application data method: {}'.format(data['method']) | identifier_body |
hellweg.py | # -*- coding: utf-8 -*-
u"""Hellweg execution template.
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcollections
from pykern import pkio
from pyker... | def extract_beam_histrogram(report, run_dir, frame):
beam_info = hellweg_dump_reader.beam_info(_dump_file(run_dir), frame)
points = hellweg_dump_reader.get_points(beam_info, report.reportType)
hist, edges = np.histogram(points, template_common.histogram_bins(report.histogramBins))
return {
'titl... | 'error': _parse_error_message(run_dir)
}
| random_line_split |
hellweg.py | # -*- coding: utf-8 -*-
u"""Hellweg execution template.
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcollections
from pykern import pkio
from pyker... |
else:
v['latticeCommands'] = _DEFAULT_DRIFT_ELEMENT
return template_common.render_jinja(SIM_TYPE, v)
def _generate_solenoid(models):
solenoid = models.solenoid
if solenoid.sourceDefinition == 'none':
return ''
if solenoid.sourceDefinition == 'values':
#TODO(pjm): latest ve... | v['latticeCommands'] = _generate_lattice(data['models']) | conditional_block |
lib.rs | //! # python-config-rs
//!
//! Just like the `python3-config` script that's installed
//! with your Python distribution, `python-config-rs` helps you
//! find information about your Python distribution.
//!
//! ```no_run
//! use python_config::PythonConfig;
//!
//! let cfg = PythonConfig::new(); // Python 3
//!
//! // ... |
fn is_py3(&self) -> Result<(), Error> {
if self.ver != Version::Three {
Err(Error::Python3Only)
} else {
Ok(())
}
}
/// Create a `PythonConfig` that uses the interpreter at the path `interpreter`.
///
/// This fails if the path cannot be represented... | {
PythonConfig { cmdr, ver }
} | identifier_body |
lib.rs | //! # python-config-rs
//!
//! Just like the `python3-config` script that's installed
//! with your Python distribution, `python-config-rs` helps you
//! find information about your Python distribution.
//!
//! ```no_run
//! use python_config::PythonConfig;
//!
//! let cfg = PythonConfig::new(); // Python 3
//!
//! // ... | () {
let cfg = PythonConfig::new();
let include_str = cfg.includes().unwrap();
assert!(!include_str.is_empty());
let paths: Vec<PathBuf> = include_str
.split(" ")
.map(|include| {
// Drop the '-I' characters before each path
PathBuf... | include_paths_same | identifier_name |
lib.rs | //! # python-config-rs
//!
//! Just like the `python3-config` script that's installed
//! with your Python distribution, `python-config-rs` helps you
//! find information about your Python distribution.
//!
//! ```no_run
//! use python_config::PythonConfig;
//!
//! let cfg = PythonConfig::new(); // Python 3
//!
//! // ... | /// The result type denotes that this function
/// is only available when interfacing a Python 3
/// interpreter.
///
/// It's the same as the normal [`PyResult`](type.PyResult.html)
/// used throughout this module, but it's just a little
/// type hint.
pub type Py3Only<T> = Result<T, Error>;
#[inline]
fn other_err(wh... | /// an [`Error`](enum.Error.html).
pub type PyResult<T> = Result<T, Error>;
| random_line_split |
forward.go | package forward
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/coreos/go-iptables/iptables"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared" | type PortMappings struct {
// Name of the container - May be left empty in YAML config file
Name string `yaml:"name,omitempty"`
// Protocol should be "tcp" or "udp"
Protocol string `yaml:"protocol"`
// Ports is a mapping of host ports as keys to container ports as values
Ports map[string]int `yaml:",inline"`
}
/... | "gopkg.in/yaml.v2"
)
// PortMappings contains information for mapping ports from a host to a container | random_line_split |
forward.go | package forward
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/coreos/go-iptables/iptables"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
"gopkg.in/yaml.v2"
)
// PortMappings contains information for mapping ports from a host to a container
type PortMappings struct {
// Name of the co... | () {
handler := func(i interface{}) {
var container string
var message string
var context map[string]interface{}
data := i.(map[string]interface{})
metadata := data["metadata"].(map[string]interface{})
tmp, ok := metadata["context"]
if ok {
context = tmp.(map[string]interface{})
}
tmp, ok = cont... | Watch | identifier_name |
forward.go | package forward
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/coreos/go-iptables/iptables"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
"gopkg.in/yaml.v2"
)
// PortMappings contains information for mapping ports from a host to a container
type PortMappings struct {
// Name of the co... | {
handler := func(i interface{}) {
var container string
var message string
var context map[string]interface{}
data := i.(map[string]interface{})
metadata := data["metadata"].(map[string]interface{})
tmp, ok := metadata["context"]
if ok {
context = tmp.(map[string]interface{})
}
tmp, ok = context... | identifier_body | |
forward.go | package forward
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/coreos/go-iptables/iptables"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
"gopkg.in/yaml.v2"
)
// PortMappings contains information for mapping ports from a host to a container
type PortMappings struct {
// Name of the co... |
err = yaml.Unmarshal(yml, &config)
return config, err
}
// Validate checks a config for correctness. Currently provides the following checks:
// * For each container, makes sure an equal number of Host and Container Ports are provided
// * Makes sure no Host port is used more than once.
func (c Config) Validate() (... | {
return config, err
} | conditional_block |
login.py | """A module for handling the project login related tasks."""
import base64
import binascii
import re
import time
import typing
# aiohttp
import aiohttp.web
import aiohttp_session
from multidict import MultiDictProxy
from oidcrp.exception import OidcServiceError
from swift_browser_ui.ui._convenience import (
dis... | # The session is no longer tainted if it's been locked
session["taint"] = False
session.changed()
return aiohttp.web.Response(
status=303,
body=None,
headers={
"Location": "/browse",
},
)
async def handle_logout(request: aiohttp.web.Request) -> aiohttp.... | random_line_split | |
login.py | """A module for handling the project login related tasks."""
import base64
import binascii
import re
import time
import typing
# aiohttp
import aiohttp.web
import aiohttp_session
from multidict import MultiDictProxy
from oidcrp.exception import OidcServiceError
from swift_browser_ui.ui._convenience import (
dis... |
if not session["projects"]:
session.invalidate()
raise aiohttp.web.HTTPForbidden(reason="No untainted projects available.")
# The session is no longer tainted if it's been locked
session["taint"] = False
session.changed()
return aiohttp.web.Response(
status=303,
b... | session["projects"] = dict(
filter(lambda val: not val[1]["tainted"], session["projects"].items())
) | conditional_block |
login.py | """A module for handling the project login related tasks."""
import base64
import binascii
import re
import time
import typing
# aiohttp
import aiohttp.web
import aiohttp_session
from multidict import MultiDictProxy
from oidcrp.exception import OidcServiceError
from swift_browser_ui.ui._convenience import (
dis... |
def _get_projects_from_userinfo(
userinfo: typing.Dict[str, typing.Any],
) -> typing.List[typing.Any] | None:
"""Parse projects from userinfo.
:param userinfo: dict from userinfo containing user profile
:returns: None if userinfo doesn't contain csc-projects, or a list with "project_name"s
:rais... | """Properly kill the session for the user."""
log = request.app["Log"]
client = request.app["api_client"]
if not setd["set_session_devmode"]:
try:
session = await aiohttp_session.get_session(request)
log.info(f"Killing session {session.identity}")
for project in s... | identifier_body |
login.py | """A module for handling the project login related tasks."""
import base64
import binascii
import re
import time
import typing
# aiohttp
import aiohttp.web
import aiohttp_session
from multidict import MultiDictProxy
from oidcrp.exception import OidcServiceError
from swift_browser_ui.ui._convenience import (
dis... | (
request: aiohttp.web.Request,
) -> typing.Union[aiohttp.web.Response, aiohttp.web.FileResponse]:
"""Create new session cookie for the user."""
response: typing.Union[aiohttp.web.Response, aiohttp.web.FileResponse]
response = aiohttp.web.Response(status=302, reason="Redirection to login")
# Add a ... | handle_login | identifier_name |
docker.go | package gnomock
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docke... | }
return resp, err
}
func (d *docker) waitForContainerNetwork(ctx context.Context, id string, ports NamedPorts) (*Container, error) {
d.log.Infow("waiting for container network", "container", id)
tick := time.NewTicker(time.Millisecond * 250)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return n... |
resp, err := d.createContainer(ctx, image, ports, cfg)
if err != nil {
return nil, fmt.Errorf("can't create container: %w", err) | random_line_split |
docker.go | package gnomock
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docke... | (err error, id string) bool {
var e errdefs.ErrConflict
if errors.As(err, &e) {
if err.Error() == fmt.Sprintf("Error response from daemon: removal of container %s is already in progress", id) {
return true
}
}
return false
}
| isDeletionAlreadyInProgessError | identifier_name |
docker.go | package gnomock
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docke... |
func (d *docker) setupContainerCleanup(id string, cfg *Options) chan string {
sidecarChan := make(chan string)
go func() {
defer close(sidecarChan)
if cfg.DisableAutoCleanup || cfg.Reuse || cfg.Debug {
return
}
opts := []Option{
WithDisableAutoCleanup(),
WithHostMounts(dockerSockAddr, dockerSock... | {
if cfg.Reuse {
container, ok, err := d.findReusableContainer(ctx, image, ports, cfg)
if err != nil {
return nil, err
}
if ok {
d.log.Info("re-using container")
return container, nil
}
}
d.log.Info("starting container")
resp, err := d.prepareContainer(ctx, image, ports, cfg)
if err != nil {
... | identifier_body |
docker.go | package gnomock
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docke... |
matches := duplicateContainerRegexp.FindStringSubmatch(err.Error())
if len(matches) == 2 {
d.log.Infow("duplicate container found, stopping", "container", matches[1])
err = d.client.ContainerRemove(ctx, matches[1], types.ContainerRemoveOptions{
Force: true,
})
if err != nil {
return nil, fmt.Errorf("... | {
return &resp, nil
} | conditional_block |
amqp_transport.py | # -*- coding: utf-8 -*-
# Copyright (C) 2020 Panayiotou, Konstantinos <klpanagi@gmail.com>
# Author: Panayiotou, Konstantinos <klpanagi@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati... | self.connection_params.credentials = self.credentials
else:
self.credentials = self.connection_params.credentials
# So that connections do not go zombie
atexit.register(self._graceful_shutdown)
@property
def channel(self):
return self._channel
@prop... | random_line_split | |
amqp_transport.py | # -*- coding: utf-8 -*-
# Copyright (C) 2020 Panayiotou, Konstantinos <klpanagi@gmail.com>
# Author: Panayiotou, Konstantinos <klpanagi@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati... |
else:
self.logger.warning('Queue exists <{}>'.format(queue_name))
return True
def bind_queue(self, exchange_name, queue_name, bind_key):
"""
Bind a queue to and exchange using a bind-key.
@param exchange_name: The name of the exchange (e.g. com.... | return False | conditional_block |
amqp_transport.py | # -*- coding: utf-8 -*-
# Copyright (C) 2020 Panayiotou, Konstantinos <klpanagi@gmail.com>
# Author: Panayiotou, Konstantinos <klpanagi@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati... | CONNECTION_TIMEOUT_SEC = 5
def __init__(self, host='127.0.0.1', port='5672', exchange='amq.topic'):
self._connection = None
self._channel = None
self._closing = False
self.logger = create_logger(self.__class__.__name__)
self._exchange = 'amq.topic'
self._host = host
... | identifier_body | |
amqp_transport.py | # -*- coding: utf-8 -*-
# Copyright (C) 2020 Panayiotou, Konstantinos <klpanagi@gmail.com>
# Author: Panayiotou, Konstantinos <klpanagi@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati... | (pika.BasicProperties):
"""Message Properties/Attribures used for sending and receiving messages.
Args:
content_type (str):
content_encoding (str):
timestamp (str):
"""
def __init__(self, content_type=None, content_encoding=None,
timestamp=None, correlation_id=... | MessageProperties | identifier_name |
path.rs | //! This module contains code for abstracting object locations that work
//! across different backing implementations and platforms.
use itertools::Itertools;
use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS};
use std::path::PathBuf;
/// Universal interface for handling paths and location... | {}
impl FileConverter {
/// Creates a filesystem `PathBuf` location by using the standard library's
/// `PathBuf` building implementation appropriate for the current
/// platform.
pub fn convert(object_store_path: &ObjectStorePath) -> PathBuf {
object_store_path.parts.iter().map(|p| &p.0).coll... | FileConverter | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.