file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
start-webserver.py | 191%20ribs^0.6186%20pork^0.5991%22}%20%2B{!geofilt%20d=50%20sfield=location_p%20pt=34.9362399,-80.8379247}"
q = urllib.parse.quote(text)
print(q)
#q=text.replace("+", "%2B") #so it doesn't get interpreted as space
qf="text_t"
defType="lucene"
return requests.get(SOLR_URL + "/reviews/select... |
if ("category" in categoryAndTermVector):
if (len(queryString) > 0):
queryString += " "
queryString += "+doc_type:\"" + categoryAndTermVector["category"] + "\""
... | queryString = categoryAndTermVector["term_vector"] | conditional_block |
start-webserver.py | item['command_function']
if (command):
query = {"query_tree": query_tree} #pass by-ref
commandIsResolved = eval(item['command_function']); #Careful... there is code in the docs that is being eval'd.
#MUST ENSURE THESE DOCS ARE SECURE, OTHERWISE THIS WILL IN... | _POST(s | identifier_name | |
start-webserver.py | 1); #remove next element since we're inserting into command's position
quickHack = None
if (nextEntity['canonical_form'] == "activate conference"):
quickHack = "activate"
if (nextEntity['canonical_form'] == "haystack conference"):
... | "Start a browser after waiting for half a second."""
def _open_browser():
if AIPS_WEBSERVER_HOST == "localhost":
webbrowser.open(WEBSERVER_URL + '/%s' % FILE)
thread = threading.Timer(0.5, _open_browser)
thread.start()
| identifier_body | |
start-webserver.py | #q = "%2B{!edismax%20v=%22bbq^0.9191%20ribs^0.6186%20pork^0.5991%22}%20%2B{!geofilt%20d=50%20sfield=location_p%20pt=34.9362399,-80.8379247}"
q = urllib.parse.quote(text)
print(q)
#q=text.replace("+", "%2B") #so it doesn't get interpreted as space
qf="text_t"
defType="lucene"
return re... | random_line_split | ||
stream_animation.rs | new(core));
// Anything published to the editor is piped into the core
pipe_in(Arc::clone(&core), edit_publisher.subscribe(), |core, edits: Arc<Vec<AnimationEdit>>| {
async move {
// Edits require some pre-processing: assign the IDs, perform undo actions and write to the log... | assign_element_id | identifier_name | |
stream_animation.rs | connect_stream(commands);
let mut edit_publisher = Publisher::new(10);
let storage_connection = StorageConnection::new(requests, storage_responses);
// The core is used to actually execute the requests
let core = StreamAnimationCore {
storage_connection: st... |
if let Some(next) = fetched.pop() {
// Just returning the batch we've already fetched
return Poll::Ready(Some(next));
} else if let Some(mut waiting) = next_response.take() {
// Try to retrieve the next item from the batch
... | {
// Fetch up to per_request items for each request
let num_to_fetch = remaining.len();
let num_to_fetch = if num_to_fetch > per_request { per_request } else { num_to_fetch };
let fetch_range = (remaining.start)..(remaining.start ... | conditional_block |
stream_animation.rs | connect_stream(commands);
let mut edit_publisher = Publisher::new(10);
let storage_connection = StorageConnection::new(requests, storage_responses);
// The core is used to actually execute the requests
let core = StreamAnimationCore {
storage_connection: st... |
///
/// Retrieves the IDs of the layers in this object
///
fn get_layer_ids(&self) -> Vec<u64> {
self.wait_for_edits();
let layer_responses = self.request_sync(vec![StorageCommand::ReadLayers]).unwrap_or_else(|| vec![]);
layer_responses
.into_iter()
.fl... | self.file_properties().frame_length
} | random_line_split |
stream_animation.rs | let core = Arc::new(Desync::new(core));
// Anything published to the editor is piped into the core
pipe_in(Arc::clone(&core), edit_publisher.subscribe(), |core, edits: Arc<Vec<AnimationEdit>>| {
async move {
// Edits require some pre-processing: assign the... | {
// Create the storage requests. When the storage layer is running behind, we'll buffer up to 10 of these
let mut requests = Publisher::new(10);
let commands = requests.subscribe().boxed();
let storage_responses = connect_stream(commands);
let mut edit_publis... | identifier_body | |
config.rs |
#[derive(Debug)]
pub struct ConfigEntry {
/// A unique string to identify this config value
pub key: String,
/// The value if any
pub value: Option<String>,
/// A description of this configuration entry
pub description: &'static str,
}
/// Configuration options struct, able to store both bui... | {
self.0.get(T::PREFIX)?.0.as_any().downcast_ref()
} | identifier_body | |
config.rs | ,
})
}
fn none(&mut self, key: &str, description: &'static str) {
self.0.push(ConfigEntry {
key: key.to_string(),
value: None,
description,
})
}
}
let mut v =... | )*
_ => Err($crate::DataFusionError::Internal(
format!(concat!("Config value \"{}\" not found on ", stringify!($struct_name)), key)
))
} | random_line_split | |
config.rs | , LeftAnti, LeftSemi, Right,
/// RightAnti, and RightSemi - being produced only at the end of the execution.
/// This is not typical in stream processing. Additionally, without proper design for
/// long runner execution, all types of joins may encounter out-of-memory errors.
pub allow_s... | none | identifier_name | |
hdm.py | slotvalueStr + ' * (' + chunkStr + ' + ' + sumStr + ')'
sum = valVec
#sumStr = slotvalueStr
else: # i > p, i > 0
leftOperand = chunk + sum
chunk = chunk + leftOperand.convolve(valVec)
#chunkStr = chunkStr + ' + ' + slotval... | slot,value = attribute.split(':')
slot = slot + ':' | conditional_block | |
hdm.py | (self):
self.mem.clear()
def add(self,chunk,record=None,**keys):
# if error flag is true, set to false for production system
if self.error: self.error=False
# add noise to memory
if (self.noise != 0):
self.addNoise()
# convert chunk to string (if it isn't already a string... | (self,chunk):
# convert chunk to a list of values
chunkList = chunk.split()
# define random Gaussian vectors for any undefined values
self.defineVectors(chunkList)
# update the memory vectors with the information from the chunk
for p in range(0,len(chunkList)):
# create a copy of ... | addJustValues | identifier_name |
hdm.py | ? values are present
# if logodds=True, the convert from mean cosine to logodds and return logodds
def get_activation(self,chunk,logodds=False):
# if this function has been called directly, we need to convert
if not self.busy:
# convert chunk to string (if it isn't already a string)
... | if self.threshold == None:
time=self.maximum_time
else:
logodds = self.cosine_to_logodds(self.threshold)
time=self.latency*math.exp(-logodds)
if time>self.maximum_time: time=self.maximum_time
yield time
if request_number!=self._request_count: return
... | identifier_body | |
hdm.py | (self):
self.mem.clear()
def add(self,chunk,record=None,**keys):
# if error flag is true, set to false for production system
if self.error: self.error=False
# add noise to memory
if (self.noise != 0):
self.addNoise()
# convert chunk to string (if it isn't already a string... | query[p][1] = '?'
print(chunkList[p][1])
print(query)
# compute chunk vector
chunkVector = self.getUOGwithSlots(query)
# update memory
self.updateMemory(chunkList[p][1],chunkVector)
# add a chunk to memory
# when the chunk is just a list of values
... | for p in range(0,len(chunkList)):
# create a copy of chunkList
query = copy.deepcopy(chunkList)
# replace p's value with ? in query, but leave slot as is
| random_line_split |
glium_backend.rs | 0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0f32]
],
tex: glium::uniforms::Sampler::new(&self.textures[batch.texture])
.magnify_filter(glium::uniforms::MagnifySamplerFilter::Nearest),
};
let vertex_buffe... | size | identifier_name | |
glium_backend.rs | (Back) => Some(Keycode::Backspace),
Some(Delete) => Some(Keycode::Del),
Some(Numpad8) | Some(Up) => Some(Keycode::Up),
Some(Numpad2) | Some(Down) => Some(Keycode::Down),
Some(Numpad4) | Some(L... | pos: [sx + sw, sy],
tex_coord: [1.0, 0.0],
}, | random_line_split | |
glium_backend.rs |
&& dim.height + height <= monitor_size.height - BUFFER
{
dim.width += width;
dim.height += height;
}
display
.gl_window()
.set_inner_size(LogicalSize::new(dim.width as f64, dim.height as f64));
... |
/// Make a new internal texture using image data.
pub fn make_texture(&mut self, img: ImageBuffer) -> TextureIndex {
let mut raw = glium::texture::RawImage2d::from_raw_rgba(
img.pixels,
(img.size.width, img.size.height),
);
raw.format = glium::texture::ClientFor... | {
assert!(
texture < self.textures.len(),
"Trying to write nonexistent texture"
);
let rect = glium::Rect {
left: 0,
bottom: 0,
width: img.size.width,
height: img.size.height,
};
let mut raw = glium::texture:... | identifier_body |
project_util.go | sep = string(filepath.Separator)
mainFile = "main.go"
managerMainFile = "cmd" + fsep + "manager" + fsep + mainFile
buildDockerfile = "build" + fsep + "Dockerfile"
rolesDir = "roles"
requirementsFile = "requirements.yml"
moleculeDir = "molecule"
helmChartsDir = "helm-... |
func MustGetwd() string {
wd, err := os.Getwd()
if err != nil {
log.Fatalf("Failed to get working directory: (%v)", err)
}
return wd
}
func getHomeDir() (string, error) {
hd, err := homedir.Dir()
if err != nil {
return "", err
}
return homedir.Expand(hd)
}
// TODO(hasbro17): If this function is called i... | {
if IsOperatorGo() {
return nil
}
return fmt.Errorf("'%s' can only be run for Go operators; %s or %s do not exist",
cmd.CommandPath(), managerMainFile, mainFile)
} | identifier_body |
project_util.go | sep = string(filepath.Separator)
mainFile = "main.go"
managerMainFile = "cmd" + fsep + "manager" + fsep + mainFile
buildDockerfile = "build" + fsep + "Dockerfile"
rolesDir = "roles"
requirementsFile = "requirements.yml"
moleculeDir = "molecule"
helmChartsDir = "helm-... | newGopath string
cwdInGopath bool
wd = MustGetwd()
)
for _, newGopath = range filepath.SplitList(currentGopath) {
if strings.HasPrefix(filepath.Dir(wd), newGopath) {
cwdInGopath = true
break
}
}
if !cwdInGopath {
log.Fatalf("Project not in $GOPATH")
}
if err := os.Setenv(GoPathEnv, ne... | // If GOPATH cannot be set, MustSetWdGopath exits.
func MustSetWdGopath(currentGopath string) string {
var ( | random_line_split |
project_util.go | return fmt.Errorf("must run command in project root dir: project structure requires %s",
buildDockerfile)
}
return fmt.Errorf("error while checking if current directory is the project root: %v", err)
}
return nil
}
func CheckGoProjectCmd(cmd *cobra.Command) error {
if IsOperatorGo() {
return nil
}
re... | {
return fmt.Errorf("error writing modified contents to file, %v", err)
} | conditional_block | |
project_util.go | sep = string(filepath.Separator)
mainFile = "main.go"
managerMainFile = "cmd" + fsep + "manager" + fsep + mainFile
buildDockerfile = "build" + fsep + "Dockerfile"
rolesDir = "roles"
requirementsFile = "requirements.yml"
moleculeDir = "molecule"
helmChartsDir = "helm-... | () (string, error) {
hd, err := homedir.Dir()
if err != nil {
return "", err
}
return homedir.Expand(hd)
}
// TODO(hasbro17): If this function is called in the subdir of
// a module project it will fail to parse go.mod and return
// the correct import path.
// This needs to be fixed to return the pkg import path... | getHomeDir | identifier_name |
sdk-ui.ts | -sdk-ui',
templateUrl: 'sdk-ui.html'
})
export class SdkUiPage {
public pages: Page[] = [];
public selectedPage: Page;
constructor(
private changeDetector: ChangeDetectorRef,
private alertCtrl: AlertController,
sdkInitializer: SdkInitializer,
private camera: Camera,
private platform: Platf... |
public normalizeImageFileUri(imageFileUri: string) {
// normalizeURL - see https://ionicframework.com/docs/wkwebview/
return normalizeURL(imageFileUri);
}
public onImagePreviewTapped(page: Page) {
this.selectedPage = page;
this.changeDetector.detectChanges();
}
private updatePage(page: Pag... | {
await SBSDK.cleanup();
this.pages = [];
this.selectedPage = null;
this.changeDetector.detectChanges();
} | identifier_body |
sdk-ui.ts | -sdk-ui',
templateUrl: 'sdk-ui.html'
})
export class SdkUiPage {
public pages: Page[] = [];
public selectedPage: Page;
constructor(
private changeDetector: ChangeDetectorRef,
private alertCtrl: AlertController,
sdkInitializer: SdkInitializer,
private camera: Camera,
private platform: Platf... | () {
if (!(await this.checkLicense())) { return; }
if (!this.checkSelectedPage()) { return; }
const actionSheet = this.actionSheetCtrl.create({
title: 'Edit selected Page',
buttons: [
{
| presentPageEditActionsSheet | identifier_name |
sdk-ui.ts | page-sdk-ui',
templateUrl: 'sdk-ui.html'
})
export class SdkUiPage {
public pages: Page[] = [];
public selectedPage: Page;
constructor(
private changeDetector: ChangeDetectorRef,
private alertCtrl: AlertController,
sdkInitializer: SdkInitializer,
private camera: Camera,
private platform: P... | });
}
public async pickImageFromGallery() {
let options = {
quality: IMAGE_QUALITY,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
};
const originalImageFileUri: string = await this.camera.getPicture(options);
if ... | return this.loadingCtrl.create({
content: message | random_line_split |
sdk-ui.ts | -sdk-ui',
templateUrl: 'sdk-ui.html'
})
export class SdkUiPage {
public pages: Page[] = [];
public selectedPage: Page;
constructor(
private changeDetector: ChangeDetectorRef,
private alertCtrl: AlertController,
sdkInitializer: SdkInitializer,
private camera: Camera,
private platform: Platf... |
await SBSDK.removePage({page: this.selectedPage});
let pageIndexToRemove = null;
this.pages.forEach((p, index) => {
if (this.selectedPage.pageId === p.pageId) {
pageIndexToRemove = index;
}
});
this.pages.splice(pageIndexToRemove, 1);
this.selectedPage = null;
this.cha... | { return; } | conditional_block |
main.go | err)
}
valueSchema, err := createSchema(registry, flags.valueSchema, flags.topic, false)
if err != nil {
log.Fatalln("invalid value schema:", err)
}
config := sarama.NewConfig()
config.Producer.Return.Errors = true
config.Producer.Return.Successes = true
config.Producer.Retry.Max = 5
config.Producer.Requi... | encode | identifier_name | |
main.go | } else if flags.offset == "end" {
offset = sarama.OffsetNewest
} else if t, err := dateparse.ParseLocal(flags.offset); err == nil {
offsetIsTime = true
offset = t.UnixNano() / 1e6
} else if offset, err = strconv.ParseInt(flags.offset, 10, 64); err != nil || offset < 0 {
log.Fatalln("`offset` must be `begin`, ... | {
consumer, err := sarama.NewConsumerFromClient(client)
if err != nil {
return nil, err
}
defer consumer.Close()
partitionConsumer, err := consumer.ConsumePartition(topic, partition, offset)
if err != nil {
return nil, err
}
defer partitionConsumer.Close()
select {
case msg := <-partitionConsumer.Messag... | identifier_body | |
main.go |
if flags.list {
listTopic(&flags)
return
}
if flags.topic == "" {
fmt.Fprintln(os.Stderr, "ERROR: `topic` isn't specified!")
usage()
os.Exit(1)
}
if flag.NArg() > 0 {
runProducer(&flags)
} else {
runConsumer(&flags)
}
}
type Flags struct {
brokers string
topic string
partition ... | {
usage()
os.Exit(1)
} | conditional_block | |
main.go | [--partition=N] [--key-schema=SCHEMA] [--value-schema=SCHEMA] key value
kafkabat KAFKA_OPTS REGISTRY_OPTS --topic=TOPIC [--partition=N] [--key-schema=SCHEMA] [--value-schema=SCHEMA] file
If "file" is "-", read line-by-line JSON objects from stdin, the object must contain keys "key" and "value".
... |
consumer, err := sarama.NewConsumerFromClient(client)
if err != nil {
log.Fatalln("failed to create consumer:", err)
}
defer consumer.Close()
partitions, err := client.Partitions(flags.topic)
if err != nil {
log.Fatalf("failed to list partitions for topic %s: %s\n", flags.topic, err)
}
wg := sync.WaitGro... | client, err := sarama.NewClient(strings.Split(flags.brokers, ","), config)
if err != nil {
log.Fatalln("failed to create create:", err)
}
defer client.Close() | random_line_split |
server.rs | for each server, index of the next log entry to send to that
// server, initialized to last log index + 1
nextIndex: ~[int],
// for each server, index of highest log entry known to be
// replicated on server, initialized to 0
matchIndex: ~[int],
// current set of servers
servers: ~[ServerId],
// server... | if rpc.term >= self.currentTerm {
// we lost the election... D:
self.convertToFollower();
}
// pretend we didn't hear them whether or not they won, the resend will occur anyway
}
// Update the server when it is a Follower
// Paper:
// Respond to RPCs from candidates and leaders
// ... | }
}
fn candidateAppendEntries(&mut self, rpc: AppendEntriesRpc) { | random_line_split |
server.rs | for each server, index of the next log entry to send to that
// server, initialized to last log index + 1
nextIndex: ~[int],
// for each server, index of highest log entry known to be
// replicated on server, initialized to 0
matchIndex: ~[int],
// current set of servers
servers: ~[ServerId],
// server... |
// 3. If an existing entry conflicts with a new one delete the
// existing entry and all that follow it
let startLogIndex = rpc.prevLogIndex+1;
for logOffset in range(0, rpc.entries.len()) {
let logIndex = startLogIndex + logOffset as int;
let entry = rpc.entries[logOffset].clone();
... | {
return fail;
} | conditional_block |
server.rs | for each server, index of the next log entry to send to that
// server, initialized to last log index + 1
nextIndex: ~[int],
// for each server, index of highest log entry known to be
// replicated on server, initialized to 0
matchIndex: ~[int],
// current set of servers
servers: ~[ServerId],
// server... |
fn followerVote(&mut self, rpc: &RequestVoteRpc) -> RaftRpc {
// if the candidate's log is at least as up-to-date as ours vote for them
let mut voteGranted = false;
let lastLogIndex = (self.log.len() - 1) as int;
if self.log.len() == 0 || (rpc.lastLogIndex >= lastLogIndex &&
... | {
let fail = RequestVoteResponse(RequestVoteResponseRpc {sender: self.serverId, term: self.currentTerm, voteGranted: false});
if rpc.term < self.currentTerm {
return fail;
}
// if we haven't voted for anything or we voted for candidate
match self.votedFor {
None => {
return self.... | identifier_body |
server.rs | {
currentTerm: int,
votedFor: Option<ServerId>,
log: ~[LogEntry],
commitIndex: int,
lastApplied: int,
serverType: ServerType,
electionTimeout: int,
receivedVotes: int,
// Leader state:
// for each server, index of the next log entry to send to that
// server, initialized to last log index + 1
n... | RaftServer | identifier_name | |
WXmain.js | = document.querySelector('.sideBarBtn');
sideBarBtn.state = 'closed';
var sidebarWrap = document.querySelector('.sidebarWrap');
var $sidebarWrap = $('.sidebarWrap');
var $Btn_lines = $('.Btn_line');
var mask = document.querySelector('.mask');
var sidebarWrapHeight = sidebarWrap.offsetHeight;
$sidebarWrap.css('d... | }
}
}
}
/***********************************save and share end**************************************/
| conditional_block | |
WXmain.js | moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/*************************Hamburger Btn******************************************/
var sideBarBtn = document.quer... | pe : "json",
success : function (data) {
clickGetFile.style.display = "none";
fileWrap.style.display = "block";
var saveFileLen = data.length;
for (var i = 0; i < saveFileLen; i++) {
var newList = filelist.cloneNode(true);
newList.style.display = "block";
newList.querySelector(".fileName").inn... |
dataTy | identifier_name |
WXmain.js | moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/*************************Hamburger Btn******************************************/
var sideBarBtn = document.quer... | ;
var contentWrap = document.querySelector(".contentWrap");
var sidebarContent = document.querySelectorAll(".sidebarContent");
var contentLogo = document.querySelector(".contentLogo");
var navList = document.querySelectorAll(".navList");
var contentIndex = 0;
var touchX
var disX;
contentWrap.addEventListener(st... | {
if (sideBarBtn.state == 'closed') {
$Btn_lines[0].classList.add('Btn_top_clockwise');
$Btn_lines[1].classList.add('Btn_mid_hide');
$Btn_lines[2].classList.add('Btn_bottom_anticlockwise');
sideBarBtn.state = 'opened';
contentMove('up', $sidebarWrap);
} else {
... | identifier_body |
WXmain.js | ';
moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/*************************Hamburger Btn******************************************/
var sideBarBtn = document.... | e.preventDefault();
e.stopPropagation();
delOrshareFile();
var confirmDelete = confirm("确定要删除" + "(" + this.parentNode.parentNode.firstElementChild.firstElementChild.innerHTML + ")");
/*deleteTimestamp*/
if (confirmDelete) {
v... | for (var i = 0; i < deleteFile.length; i++) {
deleteFile[i].index = i;
deleteFile[i].onclick = function (e) {
| random_line_split |
ether.service.ts | '../models/astroNFT.enum';
import { environment } from 'src/environments/environment';
declare let require: any;
declare let window: any;
// const Web3 = require('web3');
const daiAbi = [
// Some details about the token
'function name() view returns (string)',
'function symbol() view returns (string)',
// G... |
// 16-bit - 1000
get astroTier2() {
return (
(this.astroAmount >= 250 || this.secondTokenAmount >= 0.1) &&
this.astroAmount < 1000
);
}
// 32-bit - 1000
get astroTier3() {
return (
(this.astroAmount >= 1000 && this.astroAmount < 20000) ||
(this.hasLvl2 && !this.hasLvl3)
... | {
return this.astroAmount >= 1 && this.astroAmount < 250;
} | identifier_body |
ether.service.ts | '../models/astroNFT.enum';
import { environment } from 'src/environments/environment';
declare let require: any;
declare let window: any;
// const Web3 = require('web3');
const daiAbi = [
// Some details about the token
'function name() view returns (string)',
'function symbol() view returns (string)',
// G... |
this.connectedAddress$.subscribe(async (res) => {
if (!res) return;
this.idAccount = res;
// this.hasLvl1 = await this.getHasNFT(astroNFT.Lvl_1_NoobCanon, res.toLowerCase());
this.hasLvl2 = await this.getHasNFT(
astroNFT.Lvl_2_PipeCleaner,
res.toLowerCase()
);
t... | {
if (typeof window.web3 !== 'undefined') {
// this.web3 = window.web3.currentProvider;
} else {
// this.web3 = new Web3.providers.HttpProvider('http://localhost:8545');
}
// console.log('transfer.service :: constructor :: window.ethereum');
// this.web3 = new Web3(window.e... | conditional_block |
ether.service.ts | '../models/astroNFT.enum';
import { environment } from 'src/environments/environment';
declare let require: any;
declare let window: any;
// const Web3 = require('web3');
const daiAbi = [
// Some details about the token
'function name() view returns (string)',
'function symbol() view returns (string)',
// G... | (): Promise<any> {
// console.log('transfer.service :: getAccount :: start');
if (this.account == null) {
this.account = (await new Promise((resolve, reject) => {
// console.log(' | getAccount | identifier_name |
ether.service.ts | '../models/astroNFT.enum';
import { environment } from 'src/environments/environment';
declare let require: any;
declare let window: any;
// const Web3 = require('web3');
const daiAbi = [
// Some details about the token
'function name() view returns (string)',
'function symbol() view returns (string)',
// G... | astroAddress = '0xcbd55d4ffc43467142761a764763652b48b969ff';
secondTokenAddress = '0x62359ed7505efc61ff1d56fef82158ccaffa23d7';
powerUpAddress = '0xd8cd8cb7f468ef175bc01c48497d3f7fa27b4653';
connectedAddress = '';
astroAmount = 0;
secondTokenAmount = 0;
idAccount: string;
connectedAddress$ = new Behav... | private wallet: Wallet;
// web3;
enable;
account; | random_line_split |
app.py | = 'prod'
def get_config(fname):
'''
Creates connection to yaml file which holds the DB user and pass
'''
with open(fname) as f:
cfg = yaml.load(f, Loader=yaml.SafeLoader)
return cfg
if ENV == 'dev':
cfg = get_config('config.yml')
connection = cfg['connection'][ENV]
app.config... |
class ResetPasswordForm(FlaskForm):
password = PasswordField('Password', validators = [DataRequired()])
confirm_password = PasswordField('Confirm Password', validators = [DataRequired(), EqualTo('password')])
submit = SubmitField('Reset Password')
@app.route('/',methods=['GET', 'POST'])
def home():
... | '''
Raises a validation error if a user tries to register using an existing email
'''
if email.data != current_user.email:
user = User.query.filter_by(email = email.data).first()
if user is None:
raise ValidationError('There is no accouunt with that email.... | identifier_body |
app.py | = 'prod'
def get_config(fname):
'''
Creates connection to yaml file which holds the DB user and pass
'''
with open(fname) as f:
cfg = yaml.load(f, Loader=yaml.SafeLoader)
return cfg
if ENV == 'dev':
cfg = get_config('config.yml')
connection = cfg['connection'][ENV]
app.config... | (FlaskForm):
email = StringField('email', validators = [InputRequired(), Email(message = 'Invalid Email'), Length(max = 50)])
username = StringField('UserName', validators = [InputRequired(), Length(min = 4, max = 15)])
submit = SubmitField('Update')
def validate_username(self, username):
'''
... | UpdateAccountForm | identifier_name |
app.py | ENV = 'prod'
def get_config(fname):
'''
Creates connection to yaml file which holds the DB user and pass
'''
with open(fname) as f:
cfg = yaml.load(f, Loader=yaml.SafeLoader)
return cfg
if ENV == 'dev':
cfg = get_config('config.yml')
connection = cfg['connection'][ENV]
app.con... | db.session.commit()
flash('Your account has been updated', 'success')
return redirect(url_for('account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
return render_template('account.html', title = 'Accoun... | form = UpdateAccountForm()
if form.validate_on_submit():
current_user.username = form.username.data
current_user.email = form.email.data | random_line_split |
app.py | = 'prod'
def get_config(fname):
'''
Creates connection to yaml file which holds the DB user and pass
'''
with open(fname) as f:
cfg = yaml.load(f, Loader=yaml.SafeLoader)
return cfg
if ENV == 'dev':
cfg = get_config('config.yml')
connection = cfg['connection'][ENV]
app.config... |
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
mail = Mail(app)
Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String... | app.debug = False
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
app.config['MAIL_SERVER'] = os.environ['MAIL_SERVER']
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = False
app.config['MAIL__USE_SSL'] = False
app.config['MAIL_USERNAME'] = os.environ['MAIL_USERNAME']
app.config... | conditional_block |
main.go | , B)
case RAND: // Add random bits to A
mem, _ = Coords(x, y, REGISTER_A)
r := rand.Uint32()
if data != 0 {
r = r % data
}
Write24Bit(mem, A+r)
case SHIFT: // Shift A by data (signed)
mem, _ = Coords(x, y, REGISTER_A)
Write24Bit(mem, A<<Signed20Bit(data))
case LOCAL: // Set A to x,y
me... | DrawImage | identifier_name | |
main.go | = Coords(x, y, REGISTER_A)
r := rand.Uint32()
if data != 0 {
r = r % data
}
Write24Bit(mem, A+r)
case SHIFT: // Shift A by data (signed)
mem, _ = Coords(x, y, REGISTER_A)
Write24Bit(mem, A<<Signed20Bit(data))
case LOCAL: // Set A to x,y
mem, _ = Coords(x, y, REGISTER_A)
Write12Bit(mem, ... | func DrawImage(img *xgraphics.Image) {
img.XDraw()
img.XPaint(DisplayWindow.Id)
} | random_line_split | |
main.go | ; i != 0; i-- {
WriteInstruction(x, y, &r, SETA, 4096)
loop := r
{ // Push random red to stack
WriteInstruction(x, y, &r, SWAP, 0)
WriteInstruction(x, y, &r, RAND, 255)
WriteInstruction(x, y, &r, SHIFT, 16)
WriteInstruction(x, y, &r, PUSH, 0)
WriteInstruction(x, y, &r, SWAP, 0)
}
WriteInstructi... |
// Create a window
DisplayWindow, err = xwindow.Generate(X)
if err != nil {
log.Fatalf("Could not generate a new window X id: %s", err)
}
DisplayWindow.Create(X.RootWin(), 0, 0, 1024, 1024, xproto.CwBackPixel, 0)
DisplayWindow.Map()
WindowImage = xgraphics.New(X, image.Rect(0, 0, 1024, 1024))
err = Window... | {
log.Fatal(err)
} | conditional_block |
main.go | 6; i != 0; i-- {
WriteInstruction(x, y, &r, SETA, 4096)
loop := r
{ // Push random red to stack
WriteInstruction(x, y, &r, SWAP, 0)
WriteInstruction(x, y, &r, RAND, 255)
WriteInstruction(x, y, &r, SHIFT, 16)
WriteInstruction(x, y, &r, PUSH, 0)
WriteInstruction(x, y, &r, SWAP, 0)
}
WriteInstruct... | for {
// Read Program Counter
mem, ok := Coords(x, y, PROGRAM_COUNTER)
if !ok {
// fmt.Println("Program", x, y, "invalid")
return
}
PC := Read24Bit(mem)
// Read Stack Pointer
mem, ok = Coords(x, y, STACK_POINTER)
if !ok {
// fmt.Println("Program", x, y, "has invalid stack pointer")
return
... | {
// Limit executions to 100 concurrent programs
count := atomic.AddInt64(&execCount, 1)
atomic.AddInt64(&forkCount, 1)
defer atomic.AddInt64(&execCount, -1)
if count > 100 {
return
}
// De-duplicate programs running at the same location
if int(x) >= WindowImage.Rect.Max.X || int(y) >= WindowImage.Rect.Max.Y... | identifier_body |
product_structs.go | `json:"outer_shop_auction_template_id"`
PaimaiInfo *PaimaiInfo `json:"paimai_info"`
PicUrl string `json:"pic_url"`
PostFee float64 `json:"post_fee,string"`
PostageId int `json:"postage_id"`
Price ... | Tsc string `json:"tsc"` | random_line_split | |
server-utils.ts | ?: boolean,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined
) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url!, true)
d... | paramValue = encodeURIComponent(value)
} else {
paramValue = ''
}
pathname =
pathname.slice(0, paramIdx) +
paramValue +
pathname.slice(paramIdx + builtParam.length)
}
}
return pathname
}
export function getUtils({
page,
i18n,
basePath,
rewrit... | {
if (!defaultRouteRegex) return pathname
for (const param of Object.keys(defaultRouteRegex.groups)) {
const { optional, repeat } = defaultRouteRegex.groups[param]
let builtParam = `[${repeat ? '...' : ''}${param}]`
if (optional) {
builtParam = `[${builtParam}]`
}
const paramIdx = pathn... | identifier_body |
server-utils.ts | ?: boolean,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined
) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url!, true)
d... | (
req: BaseNextRequest | IncomingMessage,
renderOpts?: any,
detectedLocale?: string
) {
return getRouteMatcher(
(function () {
const { groups, routeKeys } = defaultRouteRegex!
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
... | getParamsFromRouteMatches | identifier_name |
server-utils.ts | ?: boolean,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined
) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url!, true)
d... |
Object.assign(rewriteParams, destQuery, params)
Object.assign(parsedUrl.query, parsedDestination.query)
delete (parsedDestination as any).query
Object.assign(parsedUrl, parsedDestination)
fsPathname = parsedUrl.pathname
if (basePath) {
fsPathname =
... | {
return true
} | conditional_block |
server-utils.ts | ?: boolean,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined
) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url!, true)
d... | rewrite.has,
rewrite.missing
)
if (hasParams) {
Object.assign(params, hasParams)
} else {
params = false
}
}
if (params) {
const { parsedDestination, destQuery } = prepareDestination({
appendParamsToQuery: true,
... |
if ((rewrite.has || rewrite.missing) && params) {
const hasParams = matchHas(
req,
parsedUrl.query, | random_line_split |
main.rs |
}
new
}
}
fn git(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed t... | {
new.map.insert(author.clone(), set.clone());
} | conditional_block | |
main.rs | ?;
if repo.revparse_single(to).is_err() {
// If a commit is not found, try fetching it.
git(&[
"--git-dir",
repo.path().to_str().unwrap(),
"fetch",
"origin",
to,
])?;
}
if from == "" {
let to = repo.revparse_single... | modules_file | identifier_name | |
main.rs | .or_insert_with(HashSet::new)
.insert(commit);
}
fn iter(&self) -> impl Iterator<Item = (&Author, usize)> {
self.map.iter().map(|(k, v)| (k, v.len()))
}
fn extend(&mut self, other: Self) {
for (author, set) in other.map {
self.map
.en... | self.map
.entry(author) | random_line_split | |
main.rs | out.stdout.unwrap().read_to_end(&mut stdout).unwrap();
Ok(String::from_utf8_lossy(&stdout).into_owned())
}
lazy_static::lazy_static! {
static ref UPDATED: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}
fn update_repo(url: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
let mut slug = u... | {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed to spawn command `{:?}`: {:?}", cmd, err);
}
};
let status = out.wait().expect("wait... | identifier_body | |
graph_layers.rs | self, point_id: PointOffsetType, level: usize, f: F)
where
F: FnMut(PointOffsetType);
/// Get M based on current level
fn get_m(&self, level: usize) -> usize;
/// Greedy search for closest points within a single graph layer
fn _search_on_level(
&self,
searcher: &mut SearchC... |
}
impl GraphLayers<GraphLinksMmap> {
pub fn prefault_mmap_pages(&self, path: &Path) -> Option<mmap_ops::PrefaultMmapPages> {
self.links.prefault_mmap_pages(path)
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Write;
use itertools::Itertools;
use rand::rngs::StdRng;
... | {
Ok(atomic_save_bin(path, self)?)
} | identifier_body |
graph_layers.rs | >(&self, point_id: PointOffsetType, level: usize, f: F)
where
F: FnMut(PointOffsetType);
/// Get M based on current level
fn get_m(&self, level: usize) -> usize;
/// Greedy search for closest points within a single graph layer
fn _search_on_level(
&self,
searcher: &mut Sear... | (&self, point_id: PointOffsetType) -> usize {
self.links.point_level(point_id)
}
pub fn search(
&self,
top: usize,
ef: usize,
mut points_scorer: FilteredScorer,
) -> Vec<ScoredPointOffset> {
let entry_point = match self
.entry_points
.... | point_level | identifier_name |
graph_layers.rs | >(&self, point_id: PointOffsetType, level: usize, f: F)
where
F: FnMut(PointOffsetType);
/// Get M based on current level
fn get_m(&self, level: usize) -> usize;
/// Greedy search for closest points within a single graph layer
fn _search_on_level(
&self,
searcher: &mut Sear... | Err(err)?
}
}
}
}
pub fn save(&self, path: &Path) -> OperationResult<()> {
Ok(atomic_save_bin(path, self)?)
}
}
impl GraphLayers<GraphLinksMmap> {
pub fn prefault_mmap_pages(&self, path: &Path) -> Option<mmap_ops::PrefaultMmapPages> {
... | {
let try_legacy: Result<GraphLayersBackwardCompatibility, _> = read_bin(graph_path);
if let Ok(legacy) = try_legacy {
log::debug!("Converting legacy graph to new format");
let mut converter = GraphLinksConverter::new(legacy.links_layers);
... | conditional_block |
graph_layers.rs | >(&self, point_id: PointOffsetType, level: usize, f: F)
where
F: FnMut(PointOffsetType);
/// Get M based on current level
fn get_m(&self, level: usize) -> usize;
/// Greedy search for closest points within a single graph layer
fn _search_on_level(
&self,
searcher: &mut Sear... | vector_storage: &TestRawScorerProducer<CosineMetric>,
graph: &GraphLayers<TGraphLinks>,
) -> Vec<ScoredPointOffset> {
let fake_filter_context = FakeFilterContext {};
let raw_scorer = vector_storage.get_raw_scorer(query.to_owned());
let scorer = FilteredScorer::new(raw_scorer.... | top: usize, | random_line_split |
Modules.py | :return: read_image(), inputs the filename and directory of an
image and then puts out the image and its numpy array.
other options are also available to extract image info.
NOTE: be careful about the number of rows and columns.
"""
try:
data = gdal.Open(pathname ... | plt.scatter(range(x.shape[1]), x[b, :], marker='.', color='k',
s=0.3, alpha=0.6)
plt.tick_params(axis='y', length=3.0, pad=1.0, labelsize=7)
plt.tick_params(axis='x', length=0, labelsize=0) | conditional_block | |
Modules.py | , True)
if stats is None:
continue
print(" Scale", srcband.GetScale(), end="")
print(" NDV", srcband.GetNoDataValue())
print(" Min = %.3f, Max = %.3f, Mean = %.3f, Std = %.3f \n" %
(stats[0], stats[1], stats[2], stats[3]))
f... | pca_transform | identifier_name | |
Modules.py | .
:return: read_image(), inputs the filename and directory of an
image and then puts out the image and its numpy array.
other options are also available to extract image info.
NOTE: be careful about the number of rows and columns.
"""
try:
data = gdal.Open(path... | projection = src_file.GetProjectionRef() # Projection
# Need a driver object. By default, we use GeoTIFF
driver = gdal.GetDriverByName('GTiff')
outfile = driver.Create(dst_filename, xsize=cols, ysize=rows,
bands=num_bands, eType=gdal.GDT_Float32)
... | if src_file:
geo_transform = src_file.GetGeoTransform() | random_line_split |
Modules.py | output destination of the system
# from console to the text file.
# actually, we are writing directly in the file.
orig_stdout = sys.stdout
f = open(pathname + 'statistics.txt', 'w')
sys.stdout = f
print(' Rows: {row} \n'.format(row=data.RasterXSize),
'Col... | """
:param time1: image of time 1, which is pre-phenomena;
:param time2: image of time 2, which is post-phenomena; sizes must
agree each other.
:param channel: the default value is 0, which means all the bands;
but the user can specify to perform the application only on
... | identifier_body | |
train_utils.py | iaa.Crop(percent=(0, 0.2)), # random crops
# Small gaussian blur with random sigma between 0 and 0.5.
# But we only blur about 50% of all images.
iaa.Sometimes(0.5,
iaa.GaussianBlur(sigma=(0, 0.5))
),
# Stre... | epochs=EPOCHS, ):
callbacks = create_callbacks(dataset, model_filename)
dataset.model = model
answers = [data_unit.answer for data_unit in dataset.data_list]
sample_num = len(answers)
# sample_num = len(answers)
train_num = int(sample_num * TRAIN_RATIO)
validate_num = int(sam... |
def train_model(model: Model, dataset, model_filename: str,
batch_size=BATCH_SIZE, | random_line_split |
train_utils.py | iaa.Crop(percent=(0, 0.2)), # random crops
# Small gaussian blur with random sigma between 0 and 0.5.
# But we only blur about 50% of all images.
iaa.Sometimes(0.5,
iaa.GaussianBlur(sigma=(0, 0.5))
),
# Stre... |
x_batch, y_batch = np.array(x_batch), np.array(y_batch)
if datatype != DataType.test:
x_batch = SEQ_CVXTZ.augment_images(x_batch).astype("float32")
x_batch = np.array([normalize(x) for x in x_batch])
# org_shape = x_batch.shape
# org_width = x_batch.shape[1]
... | try:
x, y, data_unit, index = create_xy(dataset, datatype)
# x = normalize(x)
x_batch.append(x)
y_batch.append(y)
except StopIteration:
break | conditional_block |
train_utils.py | iaa.Crop(percent=(0, 0.2)), # random crops
# Small gaussian blur with random sigma between 0 and 0.5.
# But we only blur about 50% of all images.
iaa.Sometimes(0.5,
iaa.GaussianBlur(sigma=(0, 0.5))
),
# Stre... | ():
# https://www.kaggle.com/CVxTz/cnn-starter-nasnet-mobile-0-9709-lb
def sometimes(aug):
return iaa.Sometimes(0.5, aug)
seq = iaa.Sequential(
[
# apply the following augmenters to most images
iaa.Fliplr(0.5), # horizontally flip 50% of all images
iaa.Fl... | create_sequential_cvxtz | identifier_name |
train_utils.py | # which can end up changing the color of the images.
iaa.Multiply((0.8, 1.2), per_channel=True),
# Apply affine transformations to each image.
# Scale/zoom them, translate/move them, rotate them and shear them.
iaa.Affine(
scale={"x": (1.0 - AU... | SEQ = iaa.Sequential([
iaa.OneOf([
iaa.Fliplr(0.5), # horizontal flips
iaa.Flipud(0.5), # vertically flips
iaa.Crop(percent=(0, 0.2)), # random crops
# Small gaussian blur with random sigma between 0 and 0.5.
# But we only blur about 50% of all imag... | identifier_body | |
kubectl.go |
continue
}
break
}
// exit with the kubectl exit code to keep compatibility.
if errors.As(err, &exitErr) {
os.Exit(exitErr.ExitCode())
}
return nil
}
// createKubeAccessRequest creates an access request to the denied resources
// if the user's roles allow search_as_role.
func createKubeAccessRequest(cf ... | {
if find.Name() == "config" {
return true
}
} | conditional_block | |
kubectl.go | KubectlReexecEnvVar) == "" {
err := runKubectlAndCollectRun(cf, fullArgs, args)
return trace.Wrap(err)
}
runKubectlCode(cf, args)
return nil
}
const (
// tshKubectlReexecEnvVar is the name of the environment variable used to control if
// tsh should re-exec or execute a kubectl command.
tshKubectlReexecEnvVa... | if err := cli.RunNoErrOutput(command); err != nil {
closeSpanAndTracer()
// Pretty-print the error and exit with an error.
cmdutil.CheckErr(err)
}
closeSpanAndTracer()
os.Exit(0)
}
func runKubectlAndCollectRun(cf *CLIConf, fullArgs, args []string) error {
var (
alreadyRequestedAccess bool
err ... | command.SetArgs(args[1:])
// run command until it finishes. | random_line_split |
kubectl.go | (cf *CLIConf, fullArgs []string, args []string) error {
if os.Getenv(tshKubectlReexecEnvVar) == "" {
err := runKubectlAndCollectRun(cf, fullArgs, args)
return trace.Wrap(err)
}
runKubectlCode(cf, args)
return nil
}
const (
// tshKubectlReexecEnvVar is the name of the environment variable used to control if
/... | onKubectlCommand | identifier_name | |
kubectl.go | alreadyRequestedAccess bool
err error
exitErr *exec.ExitError
)
for {
// missingKubeResources will include the Kubernetes Resources whose access
// was rejected in this kubectl call.
missingKubeResources := make([]resourceKind, 0, 50)
reader, writer := io.Pipe()
group, ... | {
opts := newKubeLocalProxyOpts(applyOpts...)
config, clusters, useLocalProxy := shouldUseKubeLocalProxy(cf, opts.kubectlArgs)
if !useLocalProxy {
return func() {}, "", nil
}
closeFn, newKubeConfigLocation, err := opts.makeAndStartKubeLocalProxyFunc(cf, config, clusters)
return closeFn, newKubeConfigLocation,... | identifier_body | |
colocalization_snps.py | pos, 'genes': set([])} for pos in region[chr]] for chr in region.keys()}
for gene_data in genes_data:
pos_obj = __is_in_region(assoc, gene_data.chr, gene_data.start, gene_data.end, wsize)
if pos_obj is not None:
pos_obj['genes'].add(gene_data)
else:
print 'warning: g... | for wsize in wsizes:
wsize_str = human_format(wsize)
print '--- Window size = %s ---' % wsize_str
table, match_genes = calc_genes_in_region_table(regions.get('GRCh38'), genes_db, gene_ids, wsize)
oddsratio, pvalue = stats.fisher_exact(table)
assoc = as... | file_pattern = '(.+)\.txt'
ll_ids_pattern = '"([\w\s;]+)"'
prog = re.compile(file_pattern)
ll_prog = re.compile(ll_ids_pattern)
genes_db = create_gene_db('9606', os.path.join(input_path, 'GRCh38/mart_export.txt.gz'))
snp_files = [f for f in os.listdir(input_path) if os.path.isfile(os.path.join(inp... | identifier_body |
colocalization_snps.py | pos, 'genes': set([])} for pos in region[chr]] for chr in region.keys()}
for gene_data in genes_data:
pos_obj = __is_in_region(assoc, gene_data.chr, gene_data.start, gene_data.end, wsize)
if pos_obj is not None:
pos_obj['genes'].add(gene_data)
else:
|
return assoc
def calc_regions_by_gene_count(assoc):
"""
calculates data table for graph: num_genes vs num_regions (how many regions have 1, 2, 3, ... genes)
:param assoc:
:return: an array of tuples (x, y) sorted by x
"""
counts = {}
max_count = -1
for pos_list in assoc.values():
... | print 'warning: gene %s [%s] should be in a region' % (gene_data.name, gene_data.id) | conditional_block |
colocalization_snps.py | pos, 'genes': set([])} for pos in region[chr]] for chr in region.keys()}
for gene_data in genes_data:
pos_obj = __is_in_region(assoc, gene_data.chr, gene_data.start, gene_data.end, wsize)
if pos_obj is not None:
pos_obj['genes'].add(gene_data)
else:
print 'warning: g... | (gene_ids, input_path, output_path):
file_pattern = '(.+)\.txt'
ll_ids_pattern = '"([\w\s;]+)"'
prog = re.compile(file_pattern)
ll_prog = re.compile(ll_ids_pattern)
genes_db = create_gene_db('9606', os.path.join(input_path, 'GRCh38/mart_export.txt.gz'))
snp_files = [f for f in os.listdir(input... | test_genes_vs_multiple_snps | identifier_name |
colocalization_snps.py | pos, 'genes': set([])} for pos in region[chr]] for chr in region.keys()}
for gene_data in genes_data:
pos_obj = __is_in_region(assoc, gene_data.chr, gene_data.start, gene_data.end, wsize)
if pos_obj is not None:
pos_obj['genes'].add(gene_data)
else:
print 'warning: g... | magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%i%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
def test1():
base_path = '/home/victor/Escritorio/Genotipado_Alternativo/colocalizacion'
snps_ids = load_lines(os.path.join(base_path, 'MS.txt'))
r... |
def human_format(num):
# returns an amount in a human readable format
magnitude = 0
while abs(num) >= 1000: | random_line_split |
image.rs | , color: &Color) {
set_pixel(image, &pos, &blend(&color, &get_pixel(image, &pos)));
}
fn for_two_images<F: Fn(&mut u32, &u32)>(dst: &mut Image, src: &Image, pos: &Vec2i, f: F) {
let dst_y_range = intersect_range(
&dst.range_y(),
&offset_range(&src.range_y(), pos.y)
);
let dst_x_range = intersect_range(
... | random_line_split | ||
image.rs | f64, f64, f64, f64) {
(
self.r as f64 / 255.0,
self.g as f64 / 255.0,
self.b as f64 / 255.0,
self.a as f64 / 255.0,
)
}
#[inline]
pub fn rgb(r: u8, g: u8, b: u8) -> Color {
Color::rgba(r, g, b, 255)
}
#[inline]
pub fn gray(rgb: u8) -> Color {
Color::rgb(rgb, rgb, rgb)
}
#[inline]
pub fn ... | {
Color::rgba(0, 0, 0, 0)
} | conditional_block | |
image.rs | if self.buffer.len() < needed_size {
self.buffer.resize(needed_size, 0);
}
self.width = width;
self.height = height;
}
#[inline]
pub fn clear(&mut self, color: &Color) {
let color = color.to_u32();
for pix in self.get_u32_mut_buffer() {
*pix = color;
}
}
#[inline]
pub fn get_rect(&self) -> R... |
pub fn save_png(&self, path: &Path) -> Result<(), std::io::Error> {
use std::fs::File;
use std::io::BufWriter;
let file = File::create(path)?;
let w = &mut BufWriter::new(file);
let mut encoder = png::Encoder::new(w, self.width as u32, self.height as u32);
encoder.set_color(png::ColorType::RGBA);
enc... | {
0..(self.height as i32)
} | identifier_body |
image.rs | , 255)
}
#[inline]
pub fn gray(rgb: u8) -> Color {
Color::rgb(rgb, rgb, rgb)
}
#[inline]
pub fn from_u32(v: u32) -> Self {
let res = u32::to_le_bytes(v);
Color::rgba(res[0], res[1], res[2], res[3])
}
#[inline]
pub fn to_u32(&self) -> u32 {
u32::from_le_bytes([self.r, self.g, self.b, self.a])
}
}
... | ideal_blend | identifier_name | |
fish-eye-chart.ts | Value: (chartItem: ChartData) => string
getRadiusValue: (chartItem: ChartData) => number
getXValue: (chartItem: ChartData) => number
getYValue: (chartItem: ChartData) => number
rootElId: string
titles: {
long: string
short: string
}
xAxisLabel: string
yAxisLabel: string
}>
class FishEyeChart<Ch... |
public refresh() {
this.updateDimensions(1000)
}
private setupRootEl() {
const rootEl = document.getElementById(this.config.rootElId) as HTMLElement
rootEl.classList.add(styles.fishEyeChart)
this.width =
rootEl.getBoundingClientRect().width - margin.left - margin.right
}
private is... | {
return (
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
(navigator as any).msMaxTouchPoints > 0 // eslint-disable-line @typescript-eslint/no-explicit-any
)
} | identifier_body |
fish-eye-chart.ts | Value: (chartItem: ChartData) => string
getRadiusValue: (chartItem: ChartData) => number
getXValue: (chartItem: ChartData) => number
getYValue: (chartItem: ChartData) => number
rootElId: string
titles: {
long: string
short: string
}
xAxisLabel: string
yAxisLabel: string
}>
class FishEyeChart<Ch... | () {
const rootEl = document.getElementById(this.config.rootElId) as HTMLElement
rootEl.classList.add(styles.fishEyeChart)
this.width =
rootEl.getBoundingClientRect().width - margin.left - margin.right
}
private isSmallDevice() {
return this.width < 500
}
private setDom() {
const s... | setupRootEl | identifier_name |
fish-eye-chart.ts | getColorValue: (chartItem: ChartData) => string
getRadiusValue: (chartItem: ChartData) => number
getXValue: (chartItem: ChartData) => number
getYValue: (chartItem: ChartData) => number
rootElId: string
titles: {
long: string
short: string
}
xAxisLabel: string
yAxisLabel: string
}>
class FishEy... | yScale,
}
}
private setAxis() {
const formatFn = format(",d")
this.dom.xAxis = axisBottom(this.vars.xScale as AxisScale<number>)
.tickFormat((tickNumber) => {
if (tickNumber < 1000) {
return formatFn(tickNumber)
}
const reducedNum = Math.round(tickNumber ... | xScale, | random_line_split |
fish-eye-chart.ts | Value: (chartItem: ChartData) => string
getRadiusValue: (chartItem: ChartData) => number
getXValue: (chartItem: ChartData) => number
getYValue: (chartItem: ChartData) => number
rootElId: string
titles: {
long: string
short: string
}
xAxisLabel: string
yAxisLabel: string
}>
class FishEyeChart<Ch... |
if (!this.vars.focused) {
this.zoom({
animationDuration: 0,
interactionEvent,
})
}
})
}
private bindMouseLeave() {
return this.dom.svgG.on | {
return
} | conditional_block |
modular.rs | {
pub fn new(
service_registry: Arc<dyn ServiceRegistry + Send + Sync + 'static>,
tunnel_registry: Arc<dyn TunnelRegistry + Send + Sync + 'static>,
router: Arc<dyn Router + Send + Sync + 'static>,
authentication_handler: Arc<dyn AuthenticationHandler + Send + Sync + 'static>,
tunnel_id_generator: ... |
};
// Tunnel naming - The tunnel registry is notified of the authenticator-provided tunnel name
{
let tunnel_registry = Arc::clone(&serialized_tunnel_registry);
Self::name_tunnel(id, tunnel_name.clone(), tunnel_registry).instrument(tracing::span!(
tracing::Level::DEBUG,
"naming... | {
let _ = serialized_tunnel_registry.deregister_tunnel(id).await;
return Ok(());
} | conditional_block |
modular.rs | _request_listener.clone();
async move { shutdown_request_listener.cancelled().await }
})
.scan(
(this, shutdown_request_listener),
|(this, shutdown_request_listener), tunnel| {
let id = this.tunnel_id_generator.next();
let tunnel: TTunnel = tunnel.into();
... | {
match link {
tunnel::TunnelIncomingType::BiStream(link) => {
Self::handle_incoming_request_bistream(id, link, negotiator, shutdown).await | random_line_split | |
modular.rs | {
pub fn new(
service_registry: Arc<dyn ServiceRegistry + Send + Sync + 'static>,
tunnel_registry: Arc<dyn TunnelRegistry + Send + Sync + 'static>,
router: Arc<dyn Router + Send + Sync + 'static>,
authentication_handler: Arc<dyn AuthenticationHandler + Send + Sync + 'static>,
tunnel_id_generator: ... | {
#[error(transparent)]
RegistrationError(#[from] TunnelRegistrationError),
#[error(transparent)]
RegistryNamingError(#[from] TunnelNamingError),
#[error(transparent)]
RequestProcessingError(RequestProcessingError),
#[error("Authentication refused to remote by either breach of protocol or invalid/inadequ... | TunnelLifecycleError | identifier_name |
pixel_format.rs | flags includes RGB or LUMINANCE.
pub rgb_bit_count: Option<u32>,
/// Red (or Y) mask for reading color data. For instance, given the A8R8G8B8 format,
/// the red mask would be 0x00ff0000.
pub r_bit_mask: Option<u32>,
/// Green (or U) mask for reading color data. For instance, given the A8R8G8B8 f... |
}
bitflags! {
pub struct PixelFormatFlags: u32 {
/// Texture contains alpha data.
const ALPHA_PIXELS = 0x1;
/// Alpha channel only uncomressed data (used in older DDS files)
const ALPHA = 0x2;
/// Texture contains compressed RGB data.
const FOURCC = 0x4;
///... | {
let mut pf: PixelFormat = Default::default();
if let Some(bpp) = format.get_bits_per_pixel() {
pf.flags.insert(PixelFormatFlags::RGB); // means uncompressed
pf.rgb_bit_count = Some(bpp as u32)
}
pf.fourcc = Some(FourCC(FourCC::DX10)); // we always use extention ... | identifier_body |
pixel_format.rs | flags includes RGB or LUMINANCE.
pub rgb_bit_count: Option<u32>,
/// Red (or Y) mask for reading color data. For instance, given the A8R8G8B8 format,
/// the red mask would be 0x00ff0000.
pub r_bit_mask: Option<u32>,
/// Green (or U) mask for reading color data. For instance, given the A8R8G8B8 f... |
let flags = PixelFormatFlags::from_bits_truncate(r.read_u32::<LittleEndian>()?);
let fourcc = r.read_u32::<LittleEndian>()?;
let rgb_bit_count = r.read_u32::<LittleEndian>()?;
let r_bit_mask = r.read_u32::<LittleEndian>()?;
let g_bit_mask = r.read_u32::<LittleEndian>()?;
... | {
return Err(Error::InvalidField("Pixel format struct size".to_owned()));
} | conditional_block |
pixel_format.rs | /// flags includes RGB or LUMINANCE.
pub rgb_bit_count: Option<u32>,
/// Red (or Y) mask for reading color data. For instance, given the A8R8G8B8 format,
/// the red mask would be 0x00ff0000.
pub r_bit_mask: Option<u32>,
/// Green (or U) mask for reading color data. For instance, given the A8R8G8... | )?;
Ok(())
}
}
impl Default for PixelFormat {
fn default() -> PixelFormat {
PixelFormat {
size: 32, // must be 32
flags: PixelFormatFlags::empty(),
fourcc: None,
rgb_bit_count: None,
r_bit_mask: None,
g_bit_mask: No... | writeln!(
f,
" RGBA bitmasks: {:?}, {:?}, {:?}, {:?}",
self.r_bit_mask, self.g_bit_mask, self.b_bit_mask, self.a_bit_mask | random_line_split |
pixel_format.rs | /// flags includes RGB or LUMINANCE.
pub rgb_bit_count: Option<u32>,
/// Red (or Y) mask for reading color data. For instance, given the A8R8G8B8 format,
/// the red mask would be 0x00ff0000.
pub r_bit_mask: Option<u32>,
/// Green (or U) mask for reading color data. For instance, given the A8R8G8... | <W: Write>(&self, w: &mut W) -> Result<(), Error> {
w.write_u32::<LittleEndian>(self.size)?;
w.write_u32::<LittleEndian>(self.flags.bits())?;
w.write_u32::<LittleEndian>(self.fourcc.as_ref().unwrap_or(&FourCC(0)).0)?;
w.write_u32::<LittleEndian>(self.rgb_bit_count.unwrap_or(0))?;
... | write | identifier_name |
amfinder_config.py | """
id = id.lower()
if id in PAR:
# Special case, look into a specific folder.
if id in ['generator', 'discriminator', 'model'] and \
PAR[id] is not None:
return os.path.join(get_appdir(),
'trained_networks',
... | build_arg_parser | identifier_name | |
amfinder_config.py | the current level is level 1 (colonization).
"""
return get('level') == 1
def intra_struct():
"""
Indicate whether the current level is level 2 (AM fungal structures).
"""
return get('level') == 2
def set(id, value, create=False):
"""
Updates application settings.
:para... | Returns absolute paths to input files.
:param files: Raw list of input file names (can contain wildcards).
"""
| random_line_split | |
amfinder_config.py | etypes
import zipfile as zf
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
import amfinder_log as AmfLog
HEADERS = [['Y', 'N', 'X'], ['A', 'V', 'H', 'I']]
PAR = {
'run_mode': None,
'level': 1,
'model': None,
'tile_edge': 126,
'input_files': ['*.jpg'],
'batch_s... |
elif id in PAR['monitors']:
PAR['monitors'][id] = value
elif create:
PAR[id] = value
else:
AmfLog.warning(f'Unknown parameter {id}')
def training_subparser(subparsers):
"""
Defines arguments used in training mode.
:param subparsers: ... | PAR[id] = value
if id == 'level':
PAR['header'] = HEADERS[int(value == 2)] # Ensures 0 or 1. | conditional_block |
amfinder_config.py | etypes
import zipfile as zf
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
import amfinder_log as AmfLog
HEADERS = [['Y', 'N', 'X'], ['A', 'V', 'H', 'I']]
PAR = {
'run_mode': None,
'level': 1,
'model': None,
'tile_edge': 126,
'input_files': ['*.jpg'],
'batch_s... |
def tsv_name():
"""
Return the TSV file corresponding to the current annotation level.
"""
if PAR['level'] == 1:
return 'col.tsv'
else:
return 'myc.tsv'
def get(id):
"""
Retrieve application settings.
:param id: Unique identifier.
"""
id ... | """ Returns the application directory. """
return APP_PATH | identifier_body |
main.rs | r: init::Resources) -> init::LateResources {
let mut rcc = p.device.RCC.constrain();
let mut flash = p.device.FLASH.constrain();
let mut gpioa = p.device.GPIOA.split(&mut rcc.ahb);
let mut gpiob = p.device.GPIOB.split(&mut rcc.ahb);
let mut gpioc = p.device.GPIOC.split(&mut rcc.ahb); | rcc.apb2.rstr().modify(|_, w| w.syscfgrst().clear_bit());
// Enable systick
p.core.SYST.set_clock_source(SystClkSource::Core);
p.core.SYST.set_reload(16_000_000);
p.core.SYST.enable_interrupt();
p.core.SYST.enable_counter();
// Set up our clocks & timer & delay
let clocks = rcc.cfgr.fr... |
// Enable the syscfg
rcc.apb2.enr().modify(|_, w| w.syscfgen().enabled());
rcc.apb2.rstr().modify(|_, w| w.syscfgrst().set_bit()); | random_line_split |
main.rs | r: init::Resources) -> init::LateResources {
let mut rcc = p.device.RCC.constrain();
let mut flash = p.device.FLASH.constrain();
let mut gpioa = p.device.GPIOA.split(&mut rcc.ahb);
let mut gpiob = p.device.GPIOB.split(&mut rcc.ahb);
let mut gpioc = p.device.GPIOC.split(&mut rcc.ahb);
// Enable ... |
fn exti9_5(_t: &mut Threshold, mut r: EXTI9_5::Resources) {
if r.EXTI.pr1.read().pr8().bit_is_set() {
r.EXTI.pr1.modify(|_, w| w.pr8().set_bit());
*r.STATE = State::Ble;
}
if r.EXTI.pr1.read().pr9().bit_is_set() {
r.EXTI.pr1.modify(|_, w| w.pr9().set_bit());
*r.STATE = Sta... | {
let res = r.BLE.read_raw();
match res {
Ok(n) => {
if n < 32 {
return
}
(*r.DRAW_BUFFER)[*r.BUFFER_POS as usize] = n;
*r.BUFFER_POS += 1;
if *r.BUFFER_POS == 16 {
*r.BUFFER_POS = 0;
}
}
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.