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 |
|---|---|---|---|---|
utils.py | import jsonpickle
import json as serializer
from pkg_resources import Requirement, resource_filename
import os
import csv
from Crypto.Cipher import ARC4
import base64
import socket
import getpass
from solidfire.factory import ElementFactory
from filelock import FileLock
import sys
def kv_string_to_dict(kv_string):
... | (encoded_sensitive_data):
cipher = ARC4.new(socket.gethostname().encode('utf-8') + "SOLIDFIRE".encode('utf-8'))
decoded = cipher.decrypt(base64.b64decode(encoded_sensitive_data[2:-1]))
return decoded.decode('utf-8') | decrypt | identifier_name |
utils.py | import jsonpickle
import json as serializer
from pkg_resources import Requirement, resource_filename
import os
import csv
from Crypto.Cipher import ARC4
import base64
import socket
import getpass
from solidfire.factory import ElementFactory
from filelock import FileLock
import sys
def kv_string_to_dict(kv_string):
... |
return connections
def write_connections(ctx, connections):
try:
connectionsCsvLocation = resource_filename(Requirement.parse("solidfire-cli"), "connections.csv")
connectionsLock = resource_filename(Requirement.parse("solidfire-cli"), "connectionsLock")
with open(connectionsCsvLocation... | connection["verifyssl"] = False | conditional_block |
utils.py | import jsonpickle
import json as serializer
from pkg_resources import Requirement, resource_filename
import os
import csv
from Crypto.Cipher import ARC4
import base64
import socket
import getpass
from solidfire.factory import ElementFactory
from filelock import FileLock
import sys
def kv_string_to_dict(kv_string):
... |
def filter_objects_from_simple_keypaths(objs, simpleKeyPaths):
# First, we assemble the key paths.
# They start out like this:
# [accouts.username, accounts.initiator_secret.secret, accounts.status]
# and become like this:
# {"accounts":{"username":True, "initiator_secret":{"secret":True}, "status"... | """ | random_line_split |
assets.py | # Copyright 2016 Quantopian, 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 in writ... |
def _make_sids(tblattr):
def _(self):
return tuple(map(
itemgetter('sid'),
sa.select((
getattr(self, tblattr).c.sid,
)).execute().fetchall(),
))
return _
sids = property(
_make_sids('asset_rou... | if adjustment not in ADJUSTMENT_STYLES:
raise ValueError(
'Invalid adjustment style {!r}. Allowed adjustment styles are '
'{}.'.format(adjustment, list(ADJUSTMENT_STYLES))
)
oc = self.get_ordered_contracts(root_symbol)
exchange = self._get_root_sy... | identifier_body |
assets.py | # Copyright 2016 Quantopian, 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 in writ... | (self):
es = sa.select(self.exchanges.c).execute().fetchall()
return {
name: ExchangeInfo(name, canonical_name, country_code)
for name, canonical_name, country_code in es
}
@lazyval
def symbol_ownership_map(self):
return build_ownership_map(
t... | exchange_info | identifier_name |
assets.py | # Copyright 2016 Quantopian, 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 in writ... |
else:
raise FutureContractsNotFound(sids=misses)
return hits
def lookup_symbol(self, symbol):
"""Lookup an equity by symbol. This method can only resolve the equity
if exactly one equity has ever owned the ticker.
Parameters
----------
s... | raise EquitiesNotFound(sids=misses) | conditional_block |
assets.py | # Copyright 2016 Quantopian, 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 in writ... | missing.add(sid)
# All requests were cache hits. Return requested sids in order.
if not missing:
return [hits[sid] for sid in sids]
update_hits = hits.update
# Look up cache misses by type.
type_to_assets = self.group_by_type(missing)
# Ha... | # about an asset.
raise SidsNotFound(sids=[sid])
hits[sid] = asset
except KeyError: | random_line_split |
game.rs | use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot,
};
use tokio::time;
use logic::components::{Movement, WorldInteraction};
use logic::legion::prelude::{Entity, World};
use logic::resources::DeadEntities;
us... |
/// Attempt to send the value, returning false if the receiver was closed.
pub fn send(self, value: T) -> bool {
match self.sender.send(value) {
Ok(()) => true,
Err(_) => false,
}
}
}
| {
let (sender, receiver) = oneshot::channel();
(Callback { sender }, receiver)
} | identifier_body |
game.rs | use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot,
};
use tokio::time;
use logic::components::{Movement, WorldInteraction};
use logic::legion::prelude::{Entity, World};
use logic::resources::DeadEntities;
us... | (&mut self) -> crate::Result<Snapshot> {
self.send_with(|callback| Command::Snapshot { callback })
.await
}
/// Handle an action performed by a player
pub async fn handle_action(&mut self, action: Action, player: PlayerId) -> crate::Result<()> {
self.sender
.send(Com... | snapshot | identifier_name |
game.rs | use std::collections::BTreeMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use tokio::sync::{
mpsc::{self, error::TrySendError},
oneshot,
};
use tokio::time;
use logic::components::{Movement, WorldInteraction};
use logic::legion::prelude::{Entity, World};
use logic::resources::DeadEntities;
us... | #[derive(Debug)]
enum Command {
Request {
request: Request,
callback: Callback<Response>,
},
RegisterPlayer {
callback: Callback<PlayerHandle>,
},
DisconnectPlayer(PlayerId),
Snapshot {
callback: Callback<Snapshot>,
},
PerformAction {
action: Actio... | pub struct GameHandle {
sender: mpsc::Sender<Command>,
}
| random_line_split |
tmsExport_generated.go | // Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/splunk"
"github.com/SAP/jenk... |
}
log.DeferExitHandler(handler)
defer handler()
telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
tmsExport(stepConfig, &stepTelemetryData, &influx)
stepTelemetryData.ErrorCode = "0"
log.Entry().Info("SUCCESS")
},
}
addTmsExportFlags(createTmsExportCmd, &stepConfig)
return cre... | {
splunkClient.Initialize(GeneralConfig.CorrelationID,
GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
GeneralConfig.HookConfig.SplunkConfig.SendLogs)
splunkClient.Send(... | conditional_block |
tmsExport_generated.go | // Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/splunk"
"github.com/SAP/jenk... | (path, resourceName string) {
measurementContent := []struct {
measurement string
valType string
name string
value interface{}
}{
{valType: config.InfluxField, measurement: "step_data", name: "tms", value: i.step_data.fields.tms},
}
errCount := 0
for _, metric := range measurementConten... | persist | identifier_name |
tmsExport_generated.go | // Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/splunk"
"github.com/SAP/jenk... | {
var theMetaData = config.StepData{
Metadata: config.StepMetadata{
Name: "tmsExport",
Aliases: []config.Alias{},
Description: "This step allows you to export an MTA file (multi-target application archive) and multiple MTA extension descriptors into a TMS (SAP Cloud Transport Management service) ... | identifier_body | |
tmsExport_generated.go | // Code generated by piper's step-generator. DO NOT EDIT.
package cmd
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/SAP/jenkins-library/pkg/config"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/splunk"
"github.com/SAP/jenk... | log.RegisterSecret(stepConfig.TmsServiceKey)
if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
log.RegisterHook(&sentryHook)
}
if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
s... | } | random_line_split |
par_granges.rs | //! # ParGranges
//!
//! Iterates over chunked genomic regions in parallel.
use anyhow::Result;
use bio::io::bed;
use crossbeam::channel::{bounded, Receiver};
use lazy_static::lazy_static;
use log::*;
use num_cpus;
use rayon::prelude::*;
use rust_htslib::{
bam::{HeaderView, IndexedReader, Read},
bcf::{Read as b... | else {
None
};
let restricted_ivs = match (bed_intervals, bcf_intervals) {
(Some(bed_ivs), Some(bcf_ivs)) => Some(Self::merge_intervals(bed_ivs, bcf_ivs)),
(Some(bed_ivs), None) => Some(bed_ivs),
(None, Some... | {
Some(
Self::bcf_to_intervals(&header, regions_bcf)
.expect("Parsed BCF/VCF to intervals"),
)
} | conditional_block |
par_granges.rs | //! # ParGranges
//!
//! Iterates over chunked genomic regions in parallel.
use anyhow::Result;
use bio::io::bed;
use crossbeam::channel::{bounded, Receiver};
use lazy_static::lazy_static;
use log::*;
use num_cpus;
use rayon::prelude::*;
use rust_htslib::{
bam::{HeaderView, IndexedReader, Read},
bcf::{Read as b... |
// An empty BAM with correct header
// A BED file with the randomly generated intervals (with expected number of positions)
// proptest generate random chunksize, cpus
proptest! {
#[test]
// add random chunksize and random cpus
// NB: using any larger numbers for this tends to b... | {
prop::collection::vec(arb_ivs(max_iv, max_ivs), 0..max_chr)
} | identifier_body |
par_granges.rs | //! # ParGranges
//!
//! Iterates over chunked genomic regions in parallel.
use anyhow::Result;
use bio::io::bed;
use crossbeam::channel::{bounded, Receiver};
use lazy_static::lazy_static;
use log::*;
use num_cpus;
use rayon::prelude::*;
use rust_htslib::{
bam::{HeaderView, IndexedReader, Read},
bcf::{Read as b... | .collect())
}
/// Merge two sets of restriction intervals together
fn merge_intervals(
a_ivs: Vec<Lapper<u32, ()>>,
b_ivs: Vec<Lapper<u32, ()>>,
) -> Vec<Lapper<u32, ()>> {
let mut intervals = vec![vec![]; a_ivs.len()];
for (i, (a_lapper, b_lapper)) in a_ivs.... | lapper.merge_overlaps();
lapper
}) | random_line_split |
par_granges.rs | //! # ParGranges
//!
//! Iterates over chunked genomic regions in parallel.
use anyhow::Result;
use bio::io::bed;
use crossbeam::channel::{bounded, Receiver};
use lazy_static::lazy_static;
use log::*;
use num_cpus;
use rayon::prelude::*;
use rust_htslib::{
bam::{HeaderView, IndexedReader, Read},
bcf::{Read as b... | (&self, tid: u32, start: u32, stop: u32) -> Vec<Self::P> {
let mut results = vec![];
for i in start..stop {
let chr = SmartString::from(&tid.to_string());
let pos = PileupPosition::new(chr, i);
results.push(pos);
}
results
... | process_region | identifier_name |
medrs.rs | extern crate config;
extern crate mediawiki;
extern crate papers;
extern crate regex;
extern crate wikibase;
#[macro_use]
extern crate lazy_static;
/*
use papers::crossref2wikidata::Crossref2Wikidata;
use papers::orcid2wikidata::Orcid2Wikidata;
use papers::pubmed2wikidata::Pubmed2Wikidata;
use papers::semanticscholar2... | ("action", "query"),
("prop", "extlinks"),
("ellimit", "500"),
("titles", title.as_str()),
]);
let result = api
.get_query_api_json_all(¶ms)
.expect("query.extlinks failed");
let mut urls: Vec<String> = vec![];
result["query"]["pages"]
.as_obje... | random_line_split | |
medrs.rs | extern crate config;
extern crate mediawiki;
extern crate papers;
extern crate regex;
extern crate wikibase;
#[macro_use]
extern crate lazy_static;
/*
use papers::crossref2wikidata::Crossref2Wikidata;
use papers::orcid2wikidata::Orcid2Wikidata;
use papers::pubmed2wikidata::Pubmed2Wikidata;
use papers::semanticscholar2... | (filename: &str) -> Vec<String> {
if filename.is_empty() {
return vec![];
}
let file = File::open(filename).expect(format!("no such file: {}", filename).as_str());
let buf = BufReader::new(file);
buf.lines()
.map(|l| l.expect("Could not parse line"))
.collect()
}
fn read_fil... | lines_from_file | identifier_name |
medrs.rs | extern crate config;
extern crate mediawiki;
extern crate papers;
extern crate regex;
extern crate wikibase;
#[macro_use]
extern crate lazy_static;
/*
use papers::crossref2wikidata::Crossref2Wikidata;
use papers::orcid2wikidata::Orcid2Wikidata;
use papers::pubmed2wikidata::Pubmed2Wikidata;
use papers::semanticscholar2... |
fn output_sparql_result_items(sparql: &String) {
let api = Api::new("https://www.wikidata.org/w/api.php").expect("Can't connect to Wikidata");
let result = api.sparql_query(&sparql).expect("SPARQL query failed");
let varname = result["head"]["vars"][0]
.as_str()
.expect("Can't find first v... | {
let rep: String = if lines.is_empty() {
"".to_string()
} else {
"wd:".to_string() + &lines.join(" wd:")
};
sparql.replace(pattern, &rep)
} | identifier_body |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from guozu.models import *
from django.db.models import Q
import datetime
from django import forms
from django.utils import simplejson as json
i... | draw.text((110, 230),unicode('昆明,你能为我们','utf-8'),(255,255,255),font=font1)
draw.text((90, 290),unicode('带来第一场胜利吗?!','utf-8'),(255,255,255),font=font1)
draw.text((130, 230),unicode('莫愁长征无知己,','utf-8'),(255,255,255),font=font1)
draw.text((60, 290),unicode('天涯海角永相随!国足必胜!','utf-8'),(255,255,255),font=font2)... | draw.text((110, 290),unicode('心就一天是国足的!','utf-8'),(255,255,255),font=font1)
draw.text((50, 230),unicode('赢了一起狂,输了一起扛!','utf-8'),(255,255,255),font=font1)
draw.text((180, 290),unicode('国足雄起!','utf-8'),(255,255,255),font=font1) | random_line_split |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from guozu.models import *
from django.db.models import Q
import datetime
from django import forms
from django.utils import simplejson as json
i... | )
im.save(os.path.join(user_upload_folder, 'm_'+imageid+'.'+file_ext))
return HttpResponse(imageid+'.'+file_ext)
def clipResizeImg(**args):
args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':100}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[key]
... | nail((100, 100), Image.ANTIALIAS | conditional_block |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from guozu.models import *
from django.db.models import Q
import datetime
from django import forms
from django.utils import simplejson as json
i... |
def guozuImage(request):
ba = Image.open("/Users/dongli/Documents/Outsourcing/project/project/template/guozu/images/logo.png")
im = Image.open('/Users/dongli/Documents/Outsourcing/project/project/template/guozu/images/test.png')
bg = Image.open('/Users/dongli/Documents/Outsourcing/project/project/template... | return HttpResponse('1') | identifier_body |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from guozu.models import *
from django.db.models import Q
import datetime
from django import forms
from django.utils import simplejson as json
i... | id=openid).count():
record = serializers.serialize('json', GuozuRecord.objects.filter(openid=openid).order_by('-id'))
rtype = 1
else:
record = serializers.serialize('json', GuozuRecord.objects.all().order_by('-id')[0:10])
rtype = 2
data = serializers.serialize('json', GuozuRecord.objects.all().order_by(... | .filter(open | identifier_name |
host_window.py | #!/bin/python
"""
This file creates the window for displaying the output of the venous flow
detected by the analog and digital modules. The input is from a PIC18F2550
libUSB device. Since the maximum frequency of sampling we need is around
10 Hertz, the low sampling rate of the USB device will not pose a problem.
Thi... | info_sizer.Add(self.txt_info_box, 0, wx.ALL, 10)
# Add the sizers to main sizer
main_sizer.Add(button_sizer, flag=wx.ALIGN_CENTER_VERTICAL)
main_sizer.AddSpacer(20)
main_sizer.Add(info_sizer, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
# Bind events to the button
s... | # Add the items to sizers
button_sizer.Add(self.start_button, 0, wx.ALL, 10)
info_sizer.Add(self.result_box, 0, wx.ALL, 10) | random_line_split |
host_window.py | #!/bin/python
"""
This file creates the window for displaying the output of the venous flow
detected by the analog and digital modules. The input is from a PIC18F2550
libUSB device. Since the maximum frequency of sampling we need is around
10 Hertz, the low sampling rate of the USB device will not pose a problem.
Thi... |
else:
average = mean(self.daq.data0)
res_string = '%.2f' %average
self.control_box.result_box.SetLabel(res_string)
def on_exit(self, event):
""" Quit the window """
self.Destroy
def on_about(self, event):
""" Display an about message """
... | average = 0.0 | conditional_block |
host_window.py | #!/bin/python
"""
This file creates the window for displaying the output of the venous flow
detected by the analog and digital modules. The input is from a PIC18F2550
libUSB device. Since the maximum frequency of sampling we need is around
10 Hertz, the low sampling rate of the USB device will not pose a problem.
Thi... |
class VSGraphFrame(wx.Frame):
""" Main frame for the measurement application"""
title = "Venous flow calculation"
def __init__(self):
wx.Frame.__init__(self, None, -1, self.title)
self.SAMPLING_TIME = 10000.0 # Set the sampling time here.
self.daq = VSDataAquis... | """ A static box for controlling the start and stop of the device and
displaying the final result of the venous flow measurement."""
def __init__(self, parent, ID, label):
wx.Panel.__init__(self, parent, ID)
# Create two box sizers, one for the button and one for the status
# me... | identifier_body |
host_window.py | #!/bin/python
"""
This file creates the window for displaying the output of the venous flow
detected by the analog and digital modules. The input is from a PIC18F2550
libUSB device. Since the maximum frequency of sampling we need is around
10 Hertz, the low sampling rate of the USB device will not pose a problem.
Thi... | (self, event):
""" Update the plot whenever data is obtained """
if self.sampling_timer.IsRunning():
self.daq.get_data()
self.draw_plot()
else:
self.control_box.txt_info_box.SetLabel('Measurement complete')
self.calculate()
ret... | on_redraw_timer | identifier_name |
plot_materials.py | #!/usr/bin/env python
#coding:utf8
import os
import sys
import traceback
import numpy as np
import matplotlib
import matplotlib.cm
import matplotlib.pyplot as plt
import meep_materials
## Interesting materials:
## was_plotted has_model See_also
## Si OK ... | f.seek(160); x_axis_type = np.fromfile(f, dtype=np.uint8, count=1)[0]
print(x_axis_type)
f.seek(166); x_start, x_end = np.fromfile(f, dtype=np.float32, count=2)
print(x_start)
print(x_end)
## Load the n, k data
f.seek(174); raw_eps = np.fromfile(f, dtype=np.float32, count=datalengt... | f.seek(151); datalength = np.fromfile(f, dtype=np.uint16, count=1)[0]
print(datalength) | random_line_split |
plot_materials.py | #!/usr/bin/env python
#coding:utf8
import os
import sys
import traceback
import numpy as np
import matplotlib
import matplotlib.cm
import matplotlib.pyplot as plt
import meep_materials
## Interesting materials:
## was_plotted has_model See_also
## Si OK ... |
except:
print("WARNING: data from file '%s' could not be plotted due to error" % (plotlabel))
print(traceback.format_exc())
print(sys.exc_info())
plt.subplot(3,1,1); plt.legend(loc=(0,0),prop={'size':6}); plt.ylabel("permittivity $\\epsilon_r'$"); plt.title(sys.argv[1])
plt.subplot(3,1,2);... | plt.subplot(3,1,3)
print(" Plotting k for '%s' with %d data points" % (plotlabel, len(k)))
plt.plot(freq, k, color=color, marker='o', markersize=0, label=plotlabel)
plt.xlim(freq_range);
plt.grid(True) | conditional_block |
plot_materials.py | #!/usr/bin/env python
#coding:utf8
import os
import sys
import traceback
import numpy as np
import matplotlib
import matplotlib.cm
import matplotlib.pyplot as plt
import meep_materials
## Interesting materials:
## was_plotted has_model See_also
## Si OK ... | (filename):#{{{
""" Reads the permittivity function from a given file with SCOUT binary format
The SCOUT database of materials is supplied with the SCOUT program and may be freely downloaded
from http://www.mtheiss.com/download/scout.zip
Different files use different units for the x-axis (179 file... | load_SCOUT_permittivity | identifier_name |
plot_materials.py | #!/usr/bin/env python
#coding:utf8
import os
import sys
import traceback
import numpy as np
import matplotlib
import matplotlib.cm
import matplotlib.pyplot as plt
import meep_materials
## Interesting materials:
## was_plotted has_model See_also
## Si OK ... |
#}}}
## Functions loading data from different format files
## Note: you must obtain the SOPRA and SCOUT databases from the web, if you want to use them
def load_SCOUT_permittivity(filename):#{{{
""" Reads the permittivity function from a given file with SCOUT binary format
The SCOUT database of materials is... | complex_eps = mat.eps
for polariz in mat.pol:
complex_eps += polariz['sigma'] * polariz['omega']**2 / (polariz['omega']**2 - freq**2 - 1j*freq*polariz['gamma'])
return complex_eps # + sum(0) | identifier_body |
generate_concept_dicts.py | #!/usr/bin/env python
# Encoding required to deal with 'micro' character
"""Script for auto-generating DICOM SR context groups from FHIR JSON value set
resources.
"""
from io import BytesIO
import json
import ftplib
import glob
import logging
import os
import re
import sys
import tempfile
from pprint import pprint
f... | response = urllib_request.urlopen(url)
return response.read()
def _get_text(element):
text = "".join(element.itertext())
return text.strip()
def get_table_o1():
logger.info("process Table O1")
url = "http://dicom.nema.org/medical/dicom/current/output/chtml/part16/chapter_O.html#table_O-1"
ro... | rser=ET.XMLParser(encoding="utf-8"))
def _download_html(url):
| identifier_body |
generate_concept_dicts.py | #!/usr/bin/env python
# Encoding required to deal with 'micro' character
"""Script for auto-generating DICOM SR context groups from FHIR JSON value set
resources.
"""
from io import BytesIO
import json
import ftplib
import glob
import logging
import os
import re
import sys
import tempfile
from pprint import pprint
f... | # XXX = 0
try:
for ftp_filepath in fhir_value_set_files:
ftp_filename = os.path.basename(ftp_filepath)
logger.info(f'process file "{ftp_filename}"')
with open(ftp_filepath, "rb") as fp:
content = fp.read()
value_set = json.loads(conten... | random_line_split | |
generate_concept_dicts.py | #!/usr/bin/env python
# Encoding required to deal with 'micro' character
"""Script for auto-generating DICOM SR context groups from FHIR JSON value set
resources.
"""
from io import BytesIO
import json
import ftplib
import glob
import logging
import os
import re
import sys
import tempfile
from pprint import pprint
f... | _fhir_value_sets(local_dir):
ftp_host = "medical.nema.org"
if not os.path.exists(local_dir):
os.makedirs(local_dir)
logger.info("storing files in " + local_dir)
logger.info(f'log into FTP server "{ftp_host}"')
ftp = ftplib.FTP(ftp_host, timeout=60)
ftp.login("anonymous")
ftp_path =... | me
def download | conditional_block |
generate_concept_dicts.py | #!/usr/bin/env python
# Encoding required to deal with 'micro' character
"""Script for auto-generating DICOM SR context groups from FHIR JSON value set
resources.
"""
from io import BytesIO
import json
import ftplib
import glob
import logging
import os
import re
import sys
import tempfile
from pprint import pprint
f... | le D1")
url = "http://dicom.nema.org/medical/dicom/current/output/chtml/part16/chapter_D.html#table_D-1"
root = _parse_html(_download_html(url))
namespaces = {"w3": root.tag.split("}")[0].strip("{")}
body = root.find("w3:body", namespaces=namespaces)
table = body.findall(".//w3:tbody", namespaces=na... | "process Tab | identifier_name |
lobby.go | package main
import (
"fmt"
"log"
"errors"
"sync"
//"bytes"
"time"
"net"
//"net/http"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/*
Enumerated constants for commands
*/
const (
C_Leave = iota //0
C_Kick = iota //1
C_End = iota //2
C_Start = iota //3
C_Terminate = iota //4
)
type Lobby inte... | (uId int, user string) (*HostUser, error) {
hostUser := HostUser{
userId: uId,
username: user,
Send: make(chan interface{}),
Receive: make(chan interface{}),
}
return &hostUser, nil
}
func newAnonUser(nick string) *AnonUser {
anon := AnonUser{
Nickname: nick,
Ready: false,
Send: make(chan interface{... | newHostUser | identifier_name |
lobby.go | package main
import (
"fmt"
"log"
"errors"
"sync"
//"bytes"
"time"
"net"
//"net/http"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/*
Enumerated constants for commands
*/
const (
C_Leave = iota //0
C_Kick = iota //1
C_End = iota //2
C_Start = iota //3
C_Terminate = iota //4
)
type Lobby inte... | else {
user := s.PlayerMap[gMsg.Player].(AnonUser)
user.Send <- gMsg
}
case "msgall":
s.LobbyHost.Send <- gMsg
}
}
}
/*
Main goroutine for processing lobby commands
*/
func (s Session) dataHandler() {
for {
select {
case data := <-s.Data:
switch jsonType := data.(type) {
case SetRead... | {
user := s.PlayerMap[gMsg.Player].(HostUser)
user.Send <- gMsg
} | conditional_block |
lobby.go | package main
import (
"fmt"
"log"
"errors"
"sync"
//"bytes"
"time"
"net"
//"net/http"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/*
Enumerated constants for commands
*/
const (
C_Leave = iota //0
C_Kick = iota //1
C_End = iota //2
C_Start = iota //3
C_Terminate = iota //4
)
type Lobby inte... | u.socket.On("terminate", func() {
terminate := Command{
Cmd: C_Terminate,
}
jsonMsg, err := json.Marshal(terminate)
if err != nil {
log.Print(err)
}
u.Sess.Send <- jsonMsg
})
u.socket.On("msgserver", func(msg map[string]interface{}) {
data := make(map[string]interface{}, 2)
data["player"] = u.P... | random_line_split | |
lobby.go | package main
import (
"fmt"
"log"
"errors"
"sync"
//"bytes"
"time"
"net"
//"net/http"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/*
Enumerated constants for commands
*/
const (
C_Leave = iota //0
C_Kick = iota //1
C_End = iota //2
C_Start = iota //3
C_Terminate = iota //4
)
type Lobby inte... |
func (s Session) sendTimeout() {
time.Sleep(10 * time.Second)
s.timeout <- true
}
func (s Session) requestTimeout() {
s.timeout = make(chan bool, 1)
var gs GameStart
select {
case t := <- s.timeout:
if t { //server timed out
gs = GameStart{
Response: false,
Feedback: "Server was unable to host."... | {
addr := s.game.host + ":" + s.game.port
err := s.connectSession(addr)
if err != nil {
//return nil, err
log.Print(err)
}
request := make(map[string]interface{})
request["event"] = "new"
request["players"] = s.CurrentUserCount()
request["maxplayers"] = s.game.MaxUsers()
jsonMsg, err := json.Marshal(reques... | identifier_body |
session.go | package popart
import (
"bufio"
"fmt"
"io"
"net"
"net/textproto"
"strconv"
"strings"
"time"
)
const (
stateAuthorization = iota
stateTransaction
stateUpdate
stateTerminateConnection
)
type operationHandler func(s *session, args []string) error
var (
operationHandlers = map[string]operationHandler{
"A... |
if err := s.handler.AuthenticatePASS(s.username, args[0]); err != nil {
return err
}
return s.signIn()
}
// handleQUIT is a callback for the client terminating the session. It will do
// slightly different things depending on the current state of the transaction.
// RFC 1939, pages 5 (in authorization state) and... | {
return NewReportableError("please provide username first")
} | conditional_block |
session.go | package popart
import (
"bufio"
"fmt"
"io"
"net"
"net/textproto"
"strconv"
"strings" | const (
stateAuthorization = iota
stateTransaction
stateUpdate
stateTerminateConnection
)
type operationHandler func(s *session, args []string) error
var (
operationHandlers = map[string]operationHandler{
"APOP": (*session).handleAPOP,
"CAPA": (*session).handleCAPA,
"DELE": (*session).handleDELE,
"LIST":... | "time"
)
| random_line_split |
session.go | package popart
import (
"bufio"
"fmt"
"io"
"net"
"net/textproto"
"strconv"
"strings"
"time"
)
const (
stateAuthorization = iota
stateTransaction
stateUpdate
stateTerminateConnection
)
type operationHandler func(s *session, args []string) error
var (
operationHandlers = map[string]operationHandler{
"A... | (args []string) (err error) {
return s.withMessageDo(args[0], func(msgId uint64) error {
if err := s.respondOK("%d octets", s.msgSizes[msgId]); err != nil {
return err
}
readCloser, err := s.handler.GetMessageReader(msgId)
if err != nil {
return err
}
defer s.closeOrReport(readCloser)
dotWriter := ... | handleRETR | identifier_name |
session.go | package popart
import (
"bufio"
"fmt"
"io"
"net"
"net/textproto"
"strconv"
"strings"
"time"
)
const (
stateAuthorization = iota
stateTransaction
stateUpdate
stateTerminateConnection
)
type operationHandler func(s *session, args []string) error
var (
operationHandlers = map[string]operationHandler{
"A... |
func printTopLine(line []byte, readErr error, writer io.Writer) error {
if readErr == io.EOF || readErr == nil {
if err := writeWithError(writer, line); err != nil {
return err
}
}
if readErr != nil {
return readErr
}
return writeWithError(writer, []byte{'\n'})
}
func writeWithError(w io.Writer, conten... | {
return s.withMessageDo(args[0], func(msgId uint64) error {
noLines, err := strconv.ParseUint(args[1], 10, 64)
if err != nil {
return errInvalidSyntax
}
if err := s.writer.PrintfLine("+OK"); err != nil {
return err
}
readCloser, err := s.handler.GetMessageReader(msgId)
if err != nil {
return er... | identifier_body |
game.py | import os.path, re, datetime, difflib, logging
from pyquery import PyQuery as pq
from src.download import open_or_download, get_page, sanity_check_game,sanity_check_game_copa
from src.season import BASE_URL
from models.basemodel import BaseModel
from models.team import Team, TeamName
from peewee import (PrimaryKeyField... | (BaseModel):
"""
Class representing a Game.
A game only contains basic information about the game and the scores.
"""
id = PrimaryKeyField()
game_acbid = IntegerField(unique=True, index=True)
team_home_id = ForeignKeyField(Team, related_name='games_home', index=True, null=True)
team_awa... | Game | identifier_name |
game.py | import os.path, re, datetime, difflib, logging
from pyquery import PyQuery as pq
from src.download import open_or_download, get_page, sanity_check_game,sanity_check_game_copa
from src.season import BASE_URL
from models.basemodel import BaseModel
from models.team import Team, TeamName
from peewee import (PrimaryKeyField... |
elif i == 3:
score_home_attribute = 'score_home_second'
score_away_attribute = 'score_away_second'
elif i == 4:
score_home_attribute = 'score_home_third'
score_away_attribute = 'score_away_third'
elif i == 5:
... | score_home_attribute = 'score_home_first'
score_away_attribute = 'score_away_first' | conditional_block |
game.py | import os.path, re, datetime, difflib, logging
from pyquery import PyQuery as pq
from src.download import open_or_download, get_page, sanity_check_game,sanity_check_game_copa
from src.season import BASE_URL
from models.basemodel import BaseModel
from models.team import Team, TeamName
from peewee import (PrimaryKeyField... |
@staticmethod
def create_instance(raw_game, game_acbid, season, competition_phase,round_phase=None):
"""
Extract all the information regarding the game such as the date, attendance, venue, score per quarter or teams.
Therefore, we need first to extract and insert the teams in the data... | sanity_check_game_copa(season.GAMES_COPA_PATH, logging_level) | identifier_body |
game.py | import os.path, re, datetime, difflib, logging
from pyquery import PyQuery as pq
from src.download import open_or_download, get_page, sanity_check_game,sanity_check_game_copa
from src.season import BASE_URL
from models.basemodel import BaseModel
from models.team import Team, TeamName
from peewee import (PrimaryKeyField... | if quarter_data:
try:
game_dict[score_home_attribute], game_dict[score_away_attribute] = list(
map(int, quarter_data.split("|")))
except ValueError:
pass
referees_data = info_game_data('.estnaranja')('td... | elif i == 6:
score_home_attribute = 'score_home_extra'
score_away_attribute = 'score_away_extra'
quarter_data = info_game_data('.estnaranja')('td').eq(i).text() | random_line_split |
utils.py | import re
import importlib
from collections import namedtuple
import itertools
import json
from io import StringIO, BytesIO
import zipfile
import csv
import pysolr
from reversion.models import Version
from django.conf import settings
from django.utils.translation import gettext as _
from django.contrib.auth.decorato... |
if val:
if attr.endswith('date'):
display_value = repr(val.value)
else:
display_value = str(val.value)
attr_confidence = val.confidence
else:
display_value = '... | val = getattr(obj, attr).get_value()
except AttributeError:
val = None | random_line_split |
utils.py | import re
import importlib
from collections import namedtuple
import itertools
import json
from io import StringIO, BytesIO
import zipfile
import csv
import pysolr
from reversion.models import Version
from django.conf import settings
from django.utils.translation import gettext as _
from django.contrib.auth.decorato... |
index += 1
return objects
def import_class(cl):
d = cl.rfind('.')
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
def format_facets(facet_dict):
'''
pysolr formats facets in a weird way. This helper function con... | objects[index] = name | conditional_block |
utils.py | import re
import importlib
from collections import namedtuple
import itertools
import json
from io import StringIO, BytesIO
import zipfile
import csv
import pysolr
from reversion.models import Version
from django.conf import settings
from django.utils.translation import gettext as _
from django.contrib.auth.decorato... | (change_type):
for field in getattr(differ, change_type)():
if field not in skip_fields:
if change_type == 'changed':
yield {
'field_name': field,
'to': differ.current_dict[field],
... | makeIt | identifier_name |
utils.py | import re
import importlib
from collections import namedtuple
import itertools
import json
from io import StringIO, BytesIO
import zipfile
import csv
import pysolr
from reversion.models import Version
from django.conf import settings
from django.utils.translation import gettext as _
from django.contrib.auth.decorato... |
def format_facets(facet_dict):
'''
pysolr formats facets in a weird way. This helper function converts their
list-like data structure into a dict that we can iterate more easily.
Basic idea: convert counts from a list to a dict containing a list of tuples
and a flag for whether any facets were f... | d = cl.rfind('.')
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname) | identifier_body |
listing-ctrl.js | angular.module('listing.roommi', ['uiGmapgoogle-maps', 'ui.bootstrap', 'parse-angular', 'fbook.roommi'])
.config(function(uiGmapGoogleMapApiProvider) {
console.log('config maps');
uiGmapGoogleMapApiProvider.configure({
key: 'AIzaSyCCMEJsPzyGW-oLOShTOJw_Pe9Qv2YMAZo',
v: '3.17',
libraries: '... | (dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
r... | calculateAge | identifier_name |
listing-ctrl.js | angular.module('listing.roommi', ['uiGmapgoogle-maps', 'ui.bootstrap', 'parse-angular', 'fbook.roommi'])
.config(function(uiGmapGoogleMapApiProvider) {
console.log('config maps');
uiGmapGoogleMapApiProvider.configure({
key: 'AIzaSyCCMEJsPzyGW-oLOShTOJw_Pe9Qv2YMAZo',
v: '3.17',
libraries: '... | ;
};
FB.apiAngular('/'+user.albumid+'/photos')
.then(function (photoData) {
for (var i = 10 - 1; i >= 0; i--) {
user.profilePhotos.push(photoData.data[i].images[1].source);
};
var User = Parse.User.current();
var shortname = user.profileDat... | {
user.albumid = user.profileData.albums.data[i].id;
} | conditional_block |
listing-ctrl.js | angular.module('listing.roommi', ['uiGmapgoogle-maps', 'ui.bootstrap', 'parse-angular', 'fbook.roommi']) | v: '3.17',
libraries: 'places'
});
})
.controller("ListingCtrl", function($scope, $rootScope, $state, $stateParams, $modal, fbookFactory, FacebookAngularPatch, uiGmapGoogleMapApi, markersFactory) {
$scope.pictureFiles = [];
$scope.picUrls = [];
var Listing = Parse.Object.extend("listing");
va... |
.config(function(uiGmapGoogleMapApiProvider) {
console.log('config maps');
uiGmapGoogleMapApiProvider.configure({
key: 'AIzaSyCCMEJsPzyGW-oLOShTOJw_Pe9Qv2YMAZo', | random_line_split |
listing-ctrl.js | angular.module('listing.roommi', ['uiGmapgoogle-maps', 'ui.bootstrap', 'parse-angular', 'fbook.roommi'])
.config(function(uiGmapGoogleMapApiProvider) {
console.log('config maps');
uiGmapGoogleMapApiProvider.configure({
key: 'AIzaSyCCMEJsPzyGW-oLOShTOJw_Pe9Qv2YMAZo',
v: '3.17',
libraries: '... |
// FACEBOOK PROFILE UPDATE
updateProf = function () {
FB.apiAngular('me?fields=id,name,first_name,last_name,email,birthday,education,gender,work,albums')
.then(function (profileData) {
user.profileData = profileData;
user.age = calculateAge(profileData.birthday);
})
... | {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
... | identifier_body |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... | working directory contained in the WhiteboxTools settings.json file.
Example Usage:
>> .*EXE_NAME run --routes=footpath.shp --dem=DEM.tif -o=assessedRoutes.shp --length=50.0 --dist=200
Note: Use of this tool requires a valid license. To obtain a license,
contact Whitebox Geospatial Inc. (support@w... | Input/output file names can be fully qualified, or can rely on the | random_line_split |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... | else if flag_val == "-outlet" {
outlet_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-o" || flag_val == "-output" {
output_file = if keyval {
vec[1].to_string()
... | {
input_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} | conditional_block |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... |
fn get_tool_name() -> String {
String::from("CorrectStreamVectorDirection") // This should be camel case and is a reference to the tool name.
}
fn run(args: &Vec<String>) -> Result<(), std::io::Error> {
let tool_name = get_tool_name();
let sep: String = path::MAIN_SEPARATOR.to_string();
// Read in ... | {
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
println!(
"correct_stream_vector_direction v{} by Dr. John B. Lindsay (c) 2023.",
VERSION.unwrap_or("Unknown version")
);
} | identifier_body |
main.rs | /*
Authors: Prof. John Lindsay
Created: 15/08/2023 (oringinally in Whitebox Toolset Extension)
Last Modified: 15/08/2023
License: MIT
*/
use rstar::primitives::GeomWithData;
use rstar::RTree;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::ops::Index;
use std::path;
use std::str;
use std::time::... | (&self) -> Point2D {
self[0]
}
fn get_last_node(&self) -> Point2D {
self[self.vertices.len() - 1]
}
} | get_first_node | identifier_name |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... | <T> {
back: NonNull<Node<T>>,
}
impl<T> Sender<T> {
/// Sends a message and if the receiver disconnected, an error is returned.
pub fn send(&mut self, message: T) -> Result<(), NoRecv<T>> {
// First we allocate the node for our message.
let alloc = OwnedAlloc::new(Node {
message... | Sender | identifier_name |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... |
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// This dereferral is safe because the queue always have at least one
// node. This single node is only dropped when the last side to
// disconnect drops.
let res = unsafe {
// Let's try to mark next's bit so that rece... | {
// Safe because we always have at least one node, which is only dropped
// in the last side to disconnect's drop.
let back = unsafe { self.back.as_ref() };
back.next.load(Relaxed).is_null()
} | identifier_body |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... |
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<T> fmt::Debug for Receiver<T> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
write!(fmtr, "spmc::Receiver {} ptr: {:p} {}", '{', self.inner, '}')
}
}
unsafe impl... | {
let ptr = expected.as_ptr();
// We are not oblied to succeed. This is just cleanup and some other
// thread might do it.
let next = match self
.inner
.front
.compare_exchange(ptr, next, Relaxed, Relaxed)
{
... | conditional_block |
spmc.rs | pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynch... | // the front.
let mut front_nnptr = unsafe {
// First we load pointer stored in the front.
bypass_null(self.inner.front.load(Relaxed))
};
loop {
// Let's remove the node logically first. Safe to derefer this
// pointer because we paused th... | // suffers from it, yeah.
let pause = self.inner.incin.inner.pause();
// Bypassing null check is safe because we never store null in | random_line_split |
threeHandle.js | import * as THREE from 'three'
import Stats from 'three/examples/jsm/libs/stats.module.js'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js'
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js'
import { DDSLoader } from 'three/examples/jsm/loaders/DDSLoader'
import { FBXLoader } from '... | this.width = 500
this.height = 500
this.scene = null
this.light = null
this.camera = null
this.controls = null
this.renderer = null
this.fov = 60
this.mixer = null
this.Stats = null
this.manager = null
this.crossOrigin = 'anonymous'
this.requestHeader = {}
this... | import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
class ThreeHandle {
constructor() { | random_line_split |
threeHandle.js |
import * as THREE from 'three'
import Stats from 'three/examples/jsm/libs/stats.module.js'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js'
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js'
import { DDSLoader } from 'three/examples/jsm/loaders/DDSLoader'
import { FBXLoader } from ... |
// https://threejs.org/docs/index.html#api/zh/math/Box3.makeEmpty
// https://blog.csdn.net/ithanmang/article/details/82217963
async getSize( object ) {
const box = new THREE.Box3().setFromObject( object )
const boxSize = box.getSize( new THREE.Vector3() )
const length = boxSize.length()
const bo... | ' )
} | identifier_name |
threeHandle.js |
import * as THREE from 'three'
import Stats from 'three/examples/jsm/libs/stats.module.js'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js'
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js'
import { DDSLoader } from 'three/examples/jsm/loaders/DDSLoader'
import { FBXLoader } from ... | const loader = new THREE.TextureLoader()
const texturePlante = loader.load( url )
const material = new THREE.MeshPhongMaterial( {
map : texturePlante
} )
return material
}
loadObj( baseUrl, objUrl, materials, fn ) {
const loader = new OBJLoader( this.manager )
loader.setRequestHeade... | .manager )
loader.setCrossOrigin( this.crossOrigin )
loader.setRequestHeader( this.requestHeader )
const that = this
loader.load(
baseUrl,
( object ) => {
fn && fn( object )
},
that.onProgress,
that.onError
)
}
// fbx模型加载贴图
loadImage( url ) {
| identifier_body |
demo.py | #Copyright (c) 2018-2020 William Emerison Six
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish... |
TARGET_FRAMERATE = 60 # fps
# to try to standardize on 60 fps, compare times between frames
time_at_beginning_of_previous_frame = glfw.get_time()
# Loop until the user closes the window
while not glfw.window_should_close(window):
# poll the time to try to get a constant framerate
while glfw.get_time() < tim... | global paddle1, paddle2
if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS:
paddle1.input_offset_y -= 10.0
if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS:
paddle1.input_offset_y += 10.0
if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS:
paddle2.input_offset_y -= 10.0
if glfw.g... | identifier_body |
demo.py | #Copyright (c) 2018-2020 William Emerison Six
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish... | Vertex(x= 10.0, y=30.0),
Vertex(x=-10.0, y=30.0)],
r=0.578123,
g=0.0,
b=1.0,
initial_position=Vertex(-90.0,0.0))
paddle2 = Paddle(vertices=[Vertex(x=-10.0, y=-30.0),
Vert... | random_line_split | |
demo.py | #Copyright (c) 2018-2020 William Emerison Six
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish... | (self):
return f"Vertex(x={repr(self.x)},y={repr(self.y)})"
def translate(self, tx, ty):
return Vertex(x=self.x + tx, y=self.y + ty)
def scale(self, scale_x, scale_y):
return Vertex(x=self.x * scale_x, y=self.y * scale_y)
def rotate(self,angle_in_radians):
return Vertex(x=... | __repr__ | identifier_name |
demo.py | #Copyright (c) 2018-2020 William Emerison Six
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish... |
global paddle_1_rotation, paddle_2_rotation
if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS:
paddle1.rotation += 0.1
if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS:
paddle1.rotation -= 0.1
if glfw.get_key(window, glfw.KEY_J) == glfw.PRESS:
paddle2.rotation += 0.1
if g... | paddle2.input_offset_y += 10.0 | conditional_block |
workplace_preparation.py | import math
import deepdish as dd
import shutil
import subprocess
from os import path, makedirs, remove, listdir
from argparse import ArgumentParser
from threading import Thread
import numpy as np
from matplotlib import pyplot as plt
number_of_images_in_temp_model = 10
def parse_args() -> str:
"""
Function t... |
def draw_rel_camera_pose(image: int, origin: list, camera_pose: list, plot_dir_path: str) -> None:
"""
Debug function for plotting the relative camera poses
:param image: number of current image
:param origin: list of [x,y,z] of the origin
:param camera_pose: list of [x1,y1,z1][x2,y2,z2] of the c... | """
The function return the absolut R & T for the first image in temp model
:param image_src: path to image file (colmap output)
:return R&T: R = list[0], T list[1] or None if image1 not exists
"""
# read images file
with open(image_src, 'r') as file:
lines = file.readlines()[4::2]
... | identifier_body |
workplace_preparation.py | import math
import deepdish as dd
import shutil
import subprocess
from os import path, makedirs, remove, listdir
from argparse import ArgumentParser
from threading import Thread
import numpy as np
from matplotlib import pyplot as plt
number_of_images_in_temp_model = 10
def parse_args() -> str:
"""
Function t... |
# compute the absolut camera pose
camera_pose = rotation + translation
if do_plot:
draw_rel_camera_pose(image, translation, camera_pose, ref_pose_images_path)
# save the values foreach image (in R & T format)
camera_pose_recover[image] = [rotation, translation]
... | rotation = rel_rotation @ np.linalg.inv(prev_rotation.T)
translation = rel_translation + prev_translation | conditional_block |
workplace_preparation.py | import math
import deepdish as dd
import shutil
import subprocess
from os import path, makedirs, remove, listdir
from argparse import ArgumentParser
from threading import Thread
import numpy as np
from matplotlib import pyplot as plt
number_of_images_in_temp_model = 10
def parse_args() -> str:
"""
Function t... | (workspace_path: str) -> None:
"""
The function deletes all the files in the workspace folder except the input video
"""
# make sure the workspace in empty
for filename in listdir(workspace_path):
if filename.endswith('.h264'):
continue
path_to_node = path.join(workspace_... | clear_workspace | identifier_name |
workplace_preparation.py | import math
import deepdish as dd
import shutil
import subprocess
from os import path, makedirs, remove, listdir
from argparse import ArgumentParser
from threading import Thread
import numpy as np
from matplotlib import pyplot as plt
number_of_images_in_temp_model = 10
def parse_args() -> str:
"""
Function t... | """
# create temp images folder
path_to_temp_model = path.join(temp_dir_path, 'temp_model')
path_to_temp_images = path.join(path_to_temp_model, 'temp_images')
# remove old temporary folder if exists
if path.exists(path_to_temp_model) and path.isdir(path_to_temp_model):
shutil.rmtree(pa... | """
The function prepares the images for our model based on a given video
:param temp_dir_path: video in h264 format
:return number_of_images: path to temporary model folder | random_line_split |
common.go | package common
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/lo... | case "eth":
return regexp.MatchString("^0x[a-km-z0-9]{40}$", address)
default:
return false, fmt.Errorf("%w %s", errInvalidCryptoCurrency, crypto)
}
}
// YesOrNo returns a boolean variable to check if input is "y" or "yes"
func YesOrNo(input string) bool {
if strings.EqualFold(input, "y") || strings.EqualFold(... | switch strings.ToLower(crypto) {
case "btc":
return regexp.MatchString("^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,90}$", address)
case "ltc":
return regexp.MatchString("^[L3M][a-km-zA-HJ-NP-Z1-9]{25,34}$", address) | random_line_split |
common.go | package common
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/lo... |
// SetHTTPClient sets a custom HTTP client.
func SetHTTPClient(client *http.Client) error {
if client == nil {
return errHTTPClientInvalid
}
m.Lock()
_HTTPClient = client
m.Unlock()
return nil
}
// NewHTTPClientWithTimeout initialises a new HTTP client and its underlying
// transport IdleConnTimeout with the... | {
if agent == "" {
return errUserAgentInvalid
}
m.Lock()
_HTTPUserAgent = agent
m.Unlock()
return nil
} | identifier_body |
common.go | package common
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/lo... | (original, incoming error) error {
errSliceP, ok := original.(*multiError)
if ok {
errSliceP.offset = nil
}
if incoming == nil {
return original // Skip append - continue as normal.
}
if !ok {
// This assumes that a standard error is passed in and we can want to
// track it and add additional errors.
er... | AppendError | identifier_name |
common.go | package common
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/lo... |
} else if x > 1 && unicode.IsUpper(rune(s[x-1])) {
if s[left:x-1] == "" {
continue
}
result = append(result, s[left:x-1])
left = x - 1
}
}
result = append(result, s[left:])
return strings.Join(result, " ")
}
// InArray checks if _val_ belongs to _array_
func InArray(val, array interface{}) (exi... | {
result = append(result, s[left:x])
left = x
} | conditional_block |
grafananet.go | package route
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Dieterbe/go-metrics"
"github.com/golang/snappy"
dest "github.com/grafana/carbon-relay-ng/destination"
"github.com/grafana/car... | else {
r.dispatch = dispatchNonBlocking
}
r.wg.Add(cfg.Concurrency)
for i := 0; i < cfg.Concurrency; i++ {
r.in[i] = make(chan []byte, cfg.BufSize/cfg.Concurrency)
go r.run(r.in[i])
}
r.config.Store(baseConfig{matcher, make([]*dest.Destination, 0)})
// start off with a transport the same as Go's DefaultT... | {
r.dispatch = dispatchBlocking
} | conditional_block |
grafananet.go | package route
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Dieterbe/go-metrics"
"github.com/golang/snappy"
dest "github.com/grafana/carbon-relay-ng/destination"
"github.com/grafana/car... | }
ioutil.ReadAll(resp.Body)
resp.Body.Close()
return
}
}
func (route *GrafanaNet) Shutdown() error {
//conf := route.config.Load().(Config)
// trigger all of our queues to be flushed to the tsdb-gw
route.shutdown <- struct{}{}
// wait for all tsdb-gw writes to complete.
route.wg.Wait()
return nil
}
f... | } else {
// if it's neither of the above, let's log it, but make it look not too scary
log.Infof("GrafanaNet %s resulted in code %s (should be harmless)", path, resp.Status) | random_line_split |
grafananet.go | package route
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Dieterbe/go-metrics"
"github.com/golang/snappy"
dest "github.com/grafana/carbon-relay-ng/destination"
"github.com/grafana/car... |
func (route *GrafanaNet) flush(mda schema.MetricDataArray, req *http.Request) (time.Duration, error) {
pre := time.Now()
resp, err := route.client.Do(req)
dur := time.Since(pre)
if err != nil {
return dur, err
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
bod, err := ioutil.ReadAll(resp.Body)
res... | {
if len(metrics) == 0 {
return metrics
}
mda := schema.MetricDataArray(metrics)
data, err := msg.CreateMsg(mda, 0, msg.FormatMetricDataArrayMsgp)
if err != nil {
panic(err)
}
route.numOut.Inc(int64(len(metrics)))
buffer.Reset()
snappyBody := snappy.NewWriter(buffer)
snappyBody.Write(data)
snappyBody.C... | identifier_body |
grafananet.go | package route
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Dieterbe/go-metrics"
"github.com/golang/snappy"
dest "github.com/grafana/carbon-relay-ng/destination"
"github.com/grafana/car... | (metrics []*schema.MetricData, buffer *bytes.Buffer) []*schema.MetricData {
if len(metrics) == 0 {
return metrics
}
mda := schema.MetricDataArray(metrics)
data, err := msg.CreateMsg(mda, 0, msg.FormatMetricDataArrayMsgp)
if err != nil {
panic(err)
}
route.numOut.Inc(int64(len(metrics)))
buffer.Reset()
sn... | retryFlush | identifier_name |
process.go | package model
import (
"encoding/binary"
"encoding/hex"
"net"
"os"
"strings"
"time"
"github.com/ds3lab/easeml/engine/database/model/types"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/pkg/errors"
)
// GetProcessByID returns a process given its id.
func (context Context) GetProce... |
return allResults[0], nil
}
// GetProcesses lists all processes given some filter criteria.
func (context Context) GetProcesses(
filters F,
limit int,
cursor string,
sortBy string,
order string,
) (result []types.Process, cm types.CollectionMetadata, err error) {
c := context.Session.DB(context.DBName).C("pr... | {
err = ErrNotFound
return
} | conditional_block |
process.go | package model
import (
"encoding/binary"
"encoding/hex"
"net"
"os"
"strings"
"time"
"github.com/ds3lab/easeml/engine/database/model/types"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/pkg/errors"
)
// GetProcessByID returns a process given its id.
func (context Context) GetProce... |
// getOutboundIP returns the preferred outbound ip of this machine
func getOutboundIP() (ip string, err error) {
var conn net.Conn
conn, err = net.Dial("udp", "8.8.8.8:80")
if err != nil {
return
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
ip = localAddr.IP.String()
return
}
// SetP... | {
if processType != types.ProcController && processType != types.ProcScheduler && processType != types.ProcWorker {
panic("invalid processType")
}
var hostID string
hostID, err = os.Hostname()
if err != nil {
err = errors.Wrap(err, "get hostname from os failed")
return
}
var hostAddress string
hostAddr... | identifier_body |
process.go | package model
import (
"encoding/binary"
"encoding/hex"
"net"
"os"
"strings"
"time"
"github.com/ds3lab/easeml/engine/database/model/types"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/pkg/errors"
)
// GetProcessByID returns a process given its id.
func (context Context) GetProce... | // If a cursor was specified then we have to do a range query.
if cursor != "" {
comparer := "$gt"
if order == "desc" {
comparer = "$lt"
}
// If there is no sorting then the cursor only points to the _id field.
if sortBy != "" && sortBy != "id" {
splits := strings.Split(cursor, "-")
cursor = split... | random_line_split | |
process.go | package model
import (
"encoding/binary"
"encoding/hex"
"net"
"os"
"strings"
"time"
"github.com/ds3lab/easeml/engine/database/model/types"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/pkg/errors"
)
// GetProcessByID returns a process given its id.
func (context Context) GetProce... | (
filters F,
limit int,
cursor string,
sortBy string,
order string,
) (result []types.Process, cm types.CollectionMetadata, err error) {
c := context.Session.DB(context.DBName).C("processes")
// Validate the parameters.
if sortBy != "" &&
sortBy != "id" &&
sortBy != "process-id" &&
sortBy != "host-id" &... | GetProcesses | identifier_name |
intcode.rs | //! This module implements an IntCode interpreter.
use std::convert::TryFrom;
// The following terminology notes are taken from day 2 part 2
// - memory: the list of integers used when interpreting
// - address/position: the value at a given index into memory
// - opcode: mark the beginning of an instruction and d... | /// `mem` is the initial machine memory state, it is modified during the run
///
/// Will panic if it encounters an unknown opcode
pub fn interpret(mut mem: &mut [isize], mut input: impl Input, mut output: impl Output) -> isize {
let mut ip: usize = 0;
loop {
match step(&mut mem, ip, &mut input, &mut ou... | random_line_split | |
intcode.rs | //! This module implements an IntCode interpreter.
use std::convert::TryFrom;
// The following terminology notes are taken from day 2 part 2
// - memory: the list of integers used when interpreting
// - address/position: the value at a given index into memory
// - opcode: mark the beginning of an instruction and d... |
}
#[derive(Debug, PartialEq)]
enum AddrMode {
Pos = 0,
Imm = 1,
}
impl TryFrom<isize> for AddrMode {
type Error = &'static str;
fn try_from(num: isize) -> Result<Self, Self::Error> {
match num {
0 => Ok(Self::Pos),
1 => Ok(Self::Imm),
_ => Err("invalid add... | {
match num {
1 => Ok(Self::Add),
2 => Ok(Self::Multiply),
3 => Ok(Self::ReadIn),
4 => Ok(Self::WriteOut),
5 => Ok(Self::JmpIfTrue),
6 => Ok(Self::JmpIfFalse),
7 => Ok(Self::LessThan),
8 => Ok(Self::Equals),
... | identifier_body |
intcode.rs | //! This module implements an IntCode interpreter.
use std::convert::TryFrom;
// The following terminology notes are taken from day 2 part 2
// - memory: the list of integers used when interpreting
// - address/position: the value at a given index into memory
// - opcode: mark the beginning of an instruction and d... | (num: isize) -> Result<Self, Self::Error> {
match num {
1 => Ok(Self::Add),
2 => Ok(Self::Multiply),
3 => Ok(Self::ReadIn),
4 => Ok(Self::WriteOut),
5 => Ok(Self::JmpIfTrue),
6 => Ok(Self::JmpIfFalse),
7 => Ok(Self::LessThan),
... | try_from | identifier_name |
main.go | package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
_ "github.com/lib/pq"
)
var (
db *sql.DB
config tomlConfig
clientConn *net.TCPConn
closeSignChan = make(... | ber) {
if v, ok := groups.Load(memberInfo.GroupNum); ok {
g := v.(Group)
if _, ok := g.Members.Load(memberInfo.QQNum); !ok {
g.Members.Store(memberInfo.QQNum, memberInfo)
}
}
}
func welcomeNewMember(subtype, groupNo, QQNum, operateQQ int64) (message string) {
var newbeMission string
if groupNo == 17171294... | oupMemberList {
if v, ok := groups.Load(nm.GroupNum); ok {
g := v.(Group)
if flag {
g.Members = GetGroupMembersFromDB(g.ID, g.GroupNum)
flag = false
}
if g.Members == nil {
g.Members = new(sync.Map)
}
if _, ok := g.Members.Load(nm.QQNum); !ok {
g.Members.Store(nm.QQNum, nm)
trans... | identifier_body |
main.go | package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
_ "github.com/lib/pq"
)
var (
db *sql.DB
config tomlConfig
clientConn *net.TCPConn
closeSignChan = make(... |
return
}
s := strings.SplitN(strings.TrimSpace(cmd), ":", 2)
if len(s) == 2 {
groupNum, err := strconv.ParseInt(strings.TrimSpace(s[0]), 10, 64)
if err != nil {
fmt.Println(err)
return
}
if g, ok := groups.Load(groupNum); ok {
sendGroupMessage(g.(Group).GroupNum, s[1])
} else {
fmt.Println(... | {
leaveGroup(groupNum)
getGroupList()
} | conditional_block |
main.go | package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
_ "github.com/lib/pq"
)
var (
db *sql.DB
config tomlConfig
clientConn *net.TCPConn
closeSignChan = make(... | var userID int64
var count int64
err = trans.QueryRow("select count(1) from users where qq_numer = $1", nm.QQNum).Scan(&count)
if err != nil {
//reportError(err)
trans.Rollback()
continue
}
if count > 0 {
err = trans.QueryRow("select id from users where qq_numer = $1", nm.QQN... | continue
} | random_line_split |
main.go | package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
_ "github.com/lib/pq"
)
var (
db *sql.DB
config tomlConfig
clientConn *net.TCPConn
closeSignChan = make(... | (cmd string) {
if cmd == "exit" {
close(closeSignChan)
return
} else if cmd == "init" {
getLoginQQ()
getGroupList()
return
} else if strings.HasPrefix(cmd, "random:") {
var i int32 = 0
var target = rand.Int31n(300)
groups.Range(func(key, value interface{}) bool {
if i == target {
sendGroupMess... | cmd | identifier_name |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... |
fn cpu_name() -> String {
// use cupid;
let info = cupid::master();
match info {
Some(x) => {
match x.brand_string() {
Some(x) => { ["CPU: ".to_owned(), x.to_owned()].join("") }
_ => { "Could not get CPU Name".to_owned() }
}
}
_ => { "Could not get CPU Name".to_owned() }
... | {
let ram_used = get_ram_used(system);
[cpu.to_owned(), ram.to_owned(), ram_used].join("\n")
} | identifier_body |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... |
if is_dir_or_subdir_linux(&mnt, "/snap") { continue; }
if is_dir_or_subdir_linux(&mnt, "/sys") { continue; }
out = format!("{}\n{} Size: {}; Free: {}",
out, mount.fs_mounted_on, mount.total, mount.avail);
}
}
Err(x) => println!("\nMounts: error: {}", x)
}
out
}
fn i... | { continue; } | conditional_block |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... | () -> String {
let sys = System::new();
let mut out = String::new();
match sys.mounts() {
Ok(mounts) => {
for mount in mounts.iter() {
if mount.total == bytesize::ByteSize::b(0) { continue; }
let mnt = mount.fs_mounted_on.clone();
if is_dir_or_subdir_linux(&mnt, "/boot") { contin... | get_hdd | identifier_name |
main.rs | #![recursion_limit="128"]
//#![allow(unused_imports)]
//#![allow(dead_code)]
extern crate gl;
extern crate glutin;
#[macro_use] extern crate nom;
extern crate image;
extern crate time;
extern crate cupid;
extern crate sysinfo;
extern crate systemstat;
extern crate bytesize;
// extern crate subprocess;
use {
gl::*,
... | out = format!("{}\n{} Size: {}; Free: {}",
out, mount.fs_mounted_on, mount.total, mount.avail);
}
}
Err(x) => println!("\nMounts: error: {}", x)
}
out
}
fn is_dir_or_subdir_linux(test: &str, path: &str) -> bool {
let tc = test.chars().count();
let pc = path.chars().count();
le... | random_line_split | |
lib.rs | #[macro_use]
extern crate compre_combinee;
extern crate combine;
mod errors;
mod details;
mod traits;
mod stop_watch;
use std::collections::{HashMap};
use combine::{parser, eof, satisfy, choice, attempt};
use combine::parser::range::{take_while1};
use combine::parser::char::*;
use combine::{Parser, many, optional, sk... | __ <- satisfy(|c: char| c == 'e' || c == 'E'),
sign_char <- optional(satisfy(|c: char| c == '+' || c == '-')),
digits <- digit_sequence();
{
let sign = match sign_char {
Some('-') => -1.0,
_ => 1.0
};
let mut acc = 0;
... | fn exponent_parser<'a>() -> impl Parser<&'a str, Output = f64> {
c_hx_do!{ | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.