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 |
|---|---|---|---|---|
io_export_arm.py | (aabb_center[1])) * 2, \
abs((bobject.bound_box[6][2] - bobject.bound_box[0][2]) / 2 + abs(aabb_center[2])) * 2 \
]
def export_mesh_data(self, exportMesh, bobject, o, has_armature=False):
exportMesh.calc_normals_split()
# exportMesh.calc_loop_triangles()
loops = export... | cdata = np.array(cdata, dtype='<i2')
if has_tang:
tangdata *= 32767
tangdata = np.array(tangdata, dtype='<i2')
# Output
o['vertex_arrays'] = []
o['vertex_arrays'].append({ 'attrib': 'pos', 'values': pdata })
o['vertex_arrays'].append({ 'attrib... | random_line_split | |
geom_func.py | not invert the triangle being deformed.'''
dm1 = trim[1]-trim[0] #precompute in final algorithm
dm2 = trim[2]-trim[0] #precompute in final algorithm
Am = np.cross(dm1,dm2)/2 #precompute in final algorithm
ds1 = tris[1]-tris[0]
ds2 = tris[2]-tris[0]
As = np.cross(ds1,ds2)/2
#Ra is a rotation_matrix t... | F = get_F(trim,tris)
b = tris[0] - F.dot(trim[0])
return lambda X: phi(F,X,b) | identifier_body | |
geom_func.py | material/reference space that is
deformed to tris, which is a triangle in real space.
returns the 3x3 rotation matrix aligning both their area normals and their first shape vector.
get_R assumes the deformation is continuous and did not invert the triangle being deformed.'''
dm1 = trim[1]-trim[0] #precomput... | phi | identifier_name | |
geom_func.py | # # test the explicit deformation map for a number of triangles
# tris = mesh.triangles[71]
# trim = mesh.triangles[30]
# mtos = get_phi(trim,tris)
# trim_mapped = np.array([mtos(trim[0]),mtos(trim[1]),mtos(trim[2])])
# print('tris is')
# print(tris)
# print('trim is mapped to')
# print(trim_mapped)
# print('difference... | # #normalize the mean radius to 1
# mesh.vertices /= np.cbrt(mesh.volume*3/(4*np.pi)) | random_line_split | |
geom_func.py | and maybe precomputing a?), and then njiting it.
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians. Uses the Euler-Rodriguez formula.
"""
axis = np.asarray(axis)
axis = axis / np.sqrt(np.dot(axis, axis))
a = np.cos(th... |
R = Rb.dot(Ra)
if testing:
# test that R = Rb.dot(Ra).T rotates Amhat onto Ashat
assert(np.isclose(np.abs(np.dot(R.dot(Amhat),Ashat)),1.).all())
# test that R = (Rb*Ra).T rotates dm1 onto ds1
assert(np.isclose(R.dot(dm1/np.linalg.norm(dm1)),ds1/np.linalg.norm(ds1)).all())
return R
########################... | assert(np.isclose(np.dot(Rb, v1),v2).all())
assert(np.isclose(np.abs(np.dot(np.dot(Ra, Amhat),Ashat)),1.).all()) | conditional_block |
train_i2t_gan.py | loader = dataloader(transform, batch_size)
return loader
import numpy as np
normalization = torch.Tensor([np.log(2 * np.pi)])
def NLL(sample, params):
|
def make_target(word_idcs):
target = torch.zeros(word_idcs.size(0), 2100).cuda()
for idx in range(word_idcs.shape[0]):
target[idx][word_idcs[idx]] = 1
return target
from random import shuffle
def true_randperm(size, device=torch.device("cuda:0")):
def unmatched_randperm(size):
l1 = ... | """Analytically computes
E_N(mu_2,sigma_2^2) [ - log N(mu_1, sigma_1^2) ]
If mu_2, and sigma_2^2 are not provided, defaults to entropy.
"""
mu = params[:,:,0]
logsigma = params[:,:,1]
c = normalization.to(mu.device)
inv_sigma = torch.exp(-logsigma)
tmp = (sample - mu) * in... | identifier_body |
train_i2t_gan.py | (img_root='/media/bingchen/research3/CUB_birds/CUB_200_2011/images'):
img_meta_root = img_root
img_meta_root = img_meta_root.replace('images','birds_meta')
def loader(transform, batch_size=4):
data = CaptionImageDataset(img_root, img_meta_root, transform=transform)
data_loader = DataLoader(... | image_cap_loader | identifier_name | |
train_i2t_gan.py | 16.parameters(),
net_tg.sentence_attn_4.parameters(),
net_tg.sentence_attn_16.parameters(),
), 'lr': 0.1*args.lr})
net_tg.zero_grad()
noise = torch.randn(b_size, 128).cuda()
g_t... | opt_tg.add_param_group({'params': chain(net_tg.word_attn_4.parameters(),
net_tg.word_attn_16.parameters(),
net_tg.sentence_attn_4.parameters(),
net_tg.sentence_attn_16.parameters(),
), 'lr... | conditional_block | |
train_i2t_gan.py | loader = dataloader(transform, batch_size)
return loader
import numpy as np
normalization = torch.Tensor([np.log(2 * np.pi)])
def NLL(sample, params):
"""Analytically computes
E_N(mu_2,sigma_2^2) [ - log N(mu_1, sigma_1^2) ]
If mu_2, and sigma_2^2 are not provided, defaults to entropy.
"""
... | loss_disc.backward()
opt_td.step()
text_d_val += real_predict.mean().item()
### 3.2 train the image-text discriminator
net_tdi.zero_grad()
real_predict = net_tdi(real_text_latent, img_feat_4, img_feat_16)
fake_predict = net_tdi(g_text_latent.detach(), img_feat_4... | real_predict = net_td(real_text_latent)
fake_predict = net_id(g_text_latent.detach())
loss_disc = F.relu(1-real_predict).mean() + F.relu(1+fake_predict).mean() | random_line_split |
jquery.pagination.js | _per_page: 10,
num_display_entries: 10,
current_page: 0,
num_edge_entries: 0,
link_to: "#",
prev_text: "Prev",
next_text: "Next",
ellipse_text: "...",
jump:true,
jump_input_style:"pagjump_txt",
jump_button_style:"pagjump_btn",
prev_show_always: true,... | ge = function() {
if (current_page < numPages() - 1) {
pageSelected(current_page + 1);
return true;
}
else {
return false;
}
}
// When all initialisation is done, draw the links
drawLinks();
});
}... | ;
}
}
this.nextPa | conditional_block |
jquery.pagination.js | _per_page: 10,
num_display_entries: 10,
current_page: 0,
num_edge_entries: 0,
link_to: "#",
prev_text: "Prev",
next_text: "Next",
ellipse_text: "...",
jump:true,
jump_input_style:"pagjump_txt",
jump_button_style:"pagjump_btn",
prev_show_always: true,... | });
};
}
// Extract current_page from options
var current_page = opts.current_page;
// Create a sane value for maxentries and items_per_page
maxentries = (!maxentries || maxentries < 0) ? 1 : maxentries;
opts.items_per_page = (!opts.items_per_page || opts.items_pe... | pageSelected(page_id-1,e); | random_line_split |
jquery.pagination.js | _per_page: 10,
num_display_entries: 10,
current_page: 0,
num_edge_entries: 0,
link_to: "#",
prev_text: "Prev",
next_text: "Next",
ellipse_text: "...",
jump:true,
jump_input_style:"pagjump_txt",
jump_button_style:"pagjump_btn",
prev_show_always: true,... |
/**
* This is the event handling function for the pagination links.
* @param {int} page_id The new page number
*/
function pageSelected(page_id, evt) {
current_page = page_id;
drawLinks();
var continuePropagation = opts.callback(page_id, pan... | {
var ne_half = Math.ceil(opts.num_display_entries / 2);
var np = numPages();
var upper_limit = np - opts.num_display_entries;
var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
var end = current_page > ne_half... | identifier_body |
jquery.pagination.js | _per_page: 10,
num_display_entries: 10,
current_page: 0,
num_edge_entries: 0,
link_to: "#",
prev_text: "Prev",
next_text: "Next",
ellipse_text: "...",
jump:true,
jump_input_style:"pagjump_txt",
jump_button_style:"pagjump_btn",
prev_show_always: true,... | () {
return Math.ceil(maxentries / opts.items_per_page);
}
/**
* Calculate start and end point of pagination links depending on
* current_page and num_display_entries.
* @return {Array}
*/
function getInterval() {
var ne_half = Math.ceil(... | numPages | identifier_name |
tag_processor.go | 2 {
if number < (1 << 4) {
return 1
} else if number < (1 << 11) {
return 2
} else if number < (1 << 18) {
return 3
} else if number < (1 << 25) {
return 4
} else {
return 5
}
}
/*
* Return the number of bytes required to store a variable-length unsigned
* 32-bit integer in base-128 varint encoding.
... | (v int64) uint32 {
return uint64Size(zigzag64(v))
}
/*
* Pack an unsigned 32-bit integer in base-128 varint encoding and return the
* number of bytes written, which must be 5 or less.
*/
func Uint32Pack(value uint32, buf []byte) ([]byte, uint32) {
var rv uint32 = 0
if value >= 0x80 {
buf = append(buf, byte(va... | sint64Size | identifier_name |
tag_processor.go | }
out = append(out, uint8(lo)|0x80,
uint8(lo>>7)|0x80,
uint8(lo>>14)|0x80,
uint8(lo>>21)|0x80)
if hi < 8 {
out = append(out, uint8(hi<<4)|uint8(lo>>28))
return out, 5
} else {
out = append(out, uint8(hi&7<<4)|uint8(lo>>28)|0x80)
hi = hi >> 3
}
rv = 5
for hi >= 128 {
out = append(out, uint8(hi|0... | {
if b := v & 1; b != 0 {
return -int64(v>>1) - 1
} else {
return int64(v >> 1)
}
} | identifier_body | |
tag_processor.go | _v uint32 = uint32(v >> 32)
if upper_v == 0 {
return UInt32Size(uint32(v))
} else if upper_v < (1 << 3) {
return 5
} else if upper_v < (1 << 10) {
return 6
} else if upper_v < (1 << 17) {
return 7
} else if upper_v < (1 << 24) {
return 8
} else if upper_v < (1 << 31) {
return 9
} else {
return 10
... | random_line_split | ||
tag_processor.go | )
return buf, 10
} else {
return Uint32Pack(uint32(value), buf)
}
}
/*
* Pack a signed 32-bit integer using ZigZag encoding and return the number of
* bytes written.
*/
func Sint32Pack(value int32, buf []byte) ([]byte, uint32) {
return Uint32Pack(zigzag32(value), buf)
}
/*
* Pack a 64-bit unsigned integer ... | {
return uint64(ParseUint32(length, data))
} | conditional_block | |
forothree.go | else if unicode.IsLower(run[0]) {
str := string(run[0])
str = strings.ToUpper(str)
slic[i] = str
res := strings.Join(slic,"")
return res
} else {
continue
}
}
return ""
}
func strtoaciicode(s string, n int) (string) { //change a char number n in string to ascicode
slic := strings.... | {
str := string(run[0])
str = strings.ToLower(str)
slic[i] = str
res := strings.Join(slic,"")
return res
} | conditional_block | |
forothree.go | if err != nil {
fmt.Println("[-]error, something wrong when parsing the url in directory: %s",err)
}
if u.Scheme == "" { //parsing when no http schema
u.Scheme = "https"
x := strings.SplitAfterN(urlz,"/",2)
u.Host = x[0]
temp = x[1]
domain = u.Scheme + "://" + u.Host
} else { //parsing when there's... | payloads2 | identifier_name | |
forothree.go | string, before string, after string, wg *sync.WaitGroup) { //request engine
//prepare url
url := ""
if (before == "DOMAINMOD") { //url exception for bypass that modify domain
r.Url = r.Url[:len(r.Url)-1]
url = r.Url + after + "/" + dir
} else if strings.HasPrefix(before, "DIRMOD") { //url exception for byp... | {
r.Xheaders = true
var wg sync.WaitGroup
defer func(){
//wg.Done()
wg.Wait()
}()
g,_ := os.Open("headerbypass.txt") // iterate file lineByLine
g2 := bufio.NewScanner(g)
var lol []string
for g2.Scan() {
var line =... | identifier_body | |
forothree.go | ,err := url.QueryUnescape(urlz)
u,err := url.Parse(unparse)
var dir,domain = "",""
if err != nil {
fmt.Println("[-]error, something wrong when parsing the url : %s",err)
}
if u.Scheme == "" { //parsing when no http schema
u.Scheme = "https"
x := strings.SplitAfterN(urlz,"/",2)
u.Host = x[0]
dir = ... |
return domain,dir
}
func parseurldirs (urlz string) (string,[]string) { //parse url with subdirectory
unparse,err := url.QueryUnescape(urlz)
u,err := url.Parse(unparse)
var temp,domain = "",""
if err != nil {
fmt.Println("[-]error, something wrong when parsing the url in directory: %s",err)
}
if u.Schem... | random_line_split | |
Sponsoring.js | () {
const { status } = this.state;
const { form } = this.state;
return (
<>
<DemoNavbar />
<main ref="main" style={{userSelect: 'none'}}>
<div className="position-relative">
<section className="section section-lg section-shaped pb-150 " style={{backgroundCol... | render | identifier_name | |
Sponsoring.js | />
</Col>
<Col className="mt-9 mt-sm-6" sm="6" xs="12">
<center>
<h2 className="align-items-center display-1 text-white" style={{marginTop:"100px"}}>
<MovingComponent
... | {
const { status } = this.state;
const { form } = this.state;
return (
<>
<DemoNavbar />
<main ref="main" style={{userSelect: 'none'}}>
<div className="position-relative">
<section className="section section-lg section-shaped pb-150 " style={{backgroundColor:... | identifier_body | |
Sponsoring.js | 44,0.08301-0.00781,0.12402 l-1.99268,15.94141C42.96436,42.78711,40.73535,45,38,45z"></path> <path fill="#5A7A84" d="M12,45H4c-0.55225,0-1-0.44727-1-1V22c0-0.55273,0.44775-1,1-1h8c0.55225,0,1,0.44727,1,1v22 C13,44.55273,12.55225,45,12,45z"></path></g></svg>
</div>
<h3>Publicité su... | random_line_split | ||
Sponsoring.js | c-0.55225,0-1-0.44727-1-1V22c0-0.55273,0.44775-1,1-1h8c0.55225,0,1,0.44727,1,1v22 C13,44.55273,12.55225,45,12,45z"></path></g></svg>
</div>
<h3>Publicité sur Facebook</h3>
<p className=" lead">
Faire de la pub sur Facebook efficace et renta... | this.setState({ status: "SUCCESS" });
this.setState({ form: "off" });
setTimeout(() => {
this.setState({ status: "" });
this.setState({ form: "on" });
}, (5000));
} else {
this.setS | conditional_block | |
model.go | returned when retries are exhausted.
errTooManyRetries = errors.New("Too many retries")
// Error returned from a transaction callback to trigger a rollback and
// retry. Other errors cause a rollback and abort.
errRetryTransaction = errors.New("Retry transaction")
)
//////////////////////////////////////////
// ... | // BundleLink with a particular id or slug. Id is tried first, slug if id
// doesn't exist.
// Note: This can fail if the bundle is deleted between fetching BundleLink
// and BundleData. However, it is highly unlikely, costly to mitigate (using
// a serializable transaction), and unimportant (error 500 instead of 404).... | return bLinks, nil
}
// GetBundleByLinkIdOrSlug retrieves a BundleData object linked to by a | random_line_split |
model.go | returned when retries are exhausted.
errTooManyRetries = errors.New("Too many retries")
// Error returned from a transaction callback to trigger a rollback and
// retry. Other errors cause a rollback and abort.
errRetryTransaction = errors.New("Retry transaction")
)
//////////////////////////////////////////
// ... |
if err != nil {
return nil, nil, err
}
bData, err := getBundleDataByHash(dbRead, bLink.Hash)
if err != nil {
return nil, nil, err
}
return bLink, bData, nil
}
// GetDefaultBundleList retrieves a list of BundleLink objects describing
// default bundles. All default bundles have slugs.
func GetDefaultBundleLi... | {
bLink, err = getDefaultBundleLinkBySlug(dbRead, idOrSlug)
} | conditional_block |
model.go | returned when retries are exhausted.
errTooManyRetries = errors.New("Too many retries")
// Error returned from a transaction callback to trigger a rollback and
// retry. Other errors cause a rollback and abort.
errRetryTransaction = errors.New("Retry transaction")
)
//////////////////////////////////////////
// ... | (tx *sqlx.Tx, bundle *NewBundle, asDefault bool) (*BundleLink, *BundleData, error) {
// All default bundles must have non-empty slugs.
if asDefault && bundle.Slug == "" {
return nil, nil, fmt.Errorf("default bundle must have non-empty slug")
}
bHashRaw := hash.Raw([]byte(bundle.Json))
bHash := bHashRaw[:]
// ... | storeBundle | identifier_name |
model.go | returned when retries are exhausted.
errTooManyRetries = errors.New("Too many retries")
// Error returned from a transaction callback to trigger a rollback and
// retry. Other errors cause a rollback and abort.
errRetryTransaction = errors.New("Retry transaction")
)
//////////////////////////////////////////
// ... |
// All default bundles have non-empty slugs. Check just in case.
func getDefaultBundleList(q sqlx.Queryer) ([]*BundleLink, error) {
var bLinks []*BundleLink
if err := sqlx.Select(q, &bLinks, "SELECT * FROM bundle_link WHERE is_default AND slug IS NOT NULL"); err != nil {
return nil, err
}
return bLinks, nil
}
... | {
var bData BundleData
if err := sqlx.Get(q, &bData, "SELECT * FROM bundle_data WHERE hash=?", hash); err != nil {
if err == sql.ErrNoRows {
err = ErrNotFound
}
return nil, err
}
return &bData, nil
} | identifier_body |
selenium_test.go | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package tests
import (
"errors"
"fmt"
"net"
"os"
"testing"
"time"
"github.com/tebeka/selenium"
gclien... | *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an | random_line_split | |
selenium_test.go | || captureTab == nil {
return fmt.Errorf("Not found capture tab: %v", err)
}
if err := captureTab.Click(); err != nil {
return fmt.Errorf("%v", err)
}
createBtn, err := webdriver.FindElement(selenium.ByXPATH, ".//*[@id='create-capture']")
if err != nil || createBtn == nil {
return fmt.Errorf("Not fo... | {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, iface := range ifaces {
//neglect interfaces which are down
if iface.Flags&net.FlagUp == 0 {
continue
}
//neglect loopback interface
if iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err... | identifier_body | |
selenium_test.go | 44:24444 -p 5900:25900 -e --shm-size=1g -p 6080:26080 -e SCREEN_WIDTH=1600 -e SCREEN_HEIGHT=1400 -e NOVNC=true elgalu/selenium", true},
{"docker exec grid wait_all_done 30s", true},
}
tearDownCmds := []helper.Cmd{
{fmt.Sprintf("%s stop", topology), true},
{"docker stop grid", true},
{"docker rm -f grid", tru... |
injectSrc, err := findElement(selenium.ByXPATH, ".//*[@id='inject-src']/input")
if err != nil {
return err
}
if err := injectSrc.Click(); err != nil {
return fmt.Errorf("Failed to click on inject input: %s", err.Error())
}
if err = selectNode("G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.... | {
return fmt.Errorf("Could not click on generator tab: %s", err.Error())
} | conditional_block |
selenium_test.go | (t *testing.T) {
gopath := os.Getenv("GOPATH")
topology := gopath + "/src/github.com/skydive-project/skydive/scripts/simple.sh"
setupCmds := []helper.Cmd{
{fmt.Sprintf("%s start 124.65.54.42/24 124.65.54.43/24", topology), true},
{"docker pull elgalu/selenium", true},
{"docker run -d --name=grid -p 4444:24444... | TestSelenium | identifier_name | |
lib.rs | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Pallet transporter used to move funds between chains.
#![cfg_att... | (&self) -> Weight {
T::WeightInfo::message()
}
fn message_response(
&self,
dst_chain_id: ChainId,
message_id: MessageIdOf<T>,
req: EndpointRequest,
resp: EndpointResponse,
) -> DispatchResult {
// ensure request... | message_weight | identifier_name |
lib.rs | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Pallet transporter used to move funds between chains.
#![cfg_att... | ChainId,
Identity,
MessageIdOf<T>,
Transfer<BalanceOf<T>>,
OptionQuery,
>;
/// Events emitted by pallet-transporter.
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
/// Emits when there is a new o... | _,
Identity, | random_line_split |
api-blueprint-resource.js | undocumented: true
}];
}
function renderDocumentation(req, res) {
var index = req.path.indexOf(module.exports.apiBlueprintDocsUri);
if (index === -1) {
throw new Error('Invalid documentation request path ' + req.path);
}
var mountpoint = req.path.substring(index + module.exports.api... |
function addQueryParameter(parameter, checkFunction, json, done) {
if (json.__domain && json.__domain !== 'local') {
return done(null, json);
}
async.each(json.ast.resourceGroups, function(resourceGroup, groupDone) {
async.each(resourceGroup.resources, function(resource, resourceDone) {
... | {
addQueryParameter({
name: 'spy-for-versioning',
description: '**DEVELOPMENT ONLY:** when `true`, generate a schema from this resource\'s response, and capture responses from external systems like JDS and VistA.\n\nSchemas are generated under `src/core/api-blueprint/schemas`, and external responses... | identifier_body |
api-blueprint-resource.js | undocumented: true
}];
}
function renderDocumentation(req, res) {
var index = req.path.indexOf(module.exports.apiBlueprintDocsUri);
if (index === -1) {
throw new Error('Invalid documentation request path ' + req.path);
}
var mountpoint = req.path.substring(index + module.exports.api... |
fullHtml = html;
sendHtml(res, error, html);
});
});
}
function renderSingleResource(mountpoint, req, res) {
if (renderedHtml[mountpoint]) {
return sendHtml(res, null, renderedHtml[mountpoint]);
}
async.waterfall([
apiBlueprint.jsonDocumentationForPath.... | {
return res.status(500).rdkSend(error);
} | conditional_block |
api-blueprint-resource.js | undocumented: true
}];
}
function renderDocumentation(req, res) {
var index = req.path.indexOf(module.exports.apiBlueprintDocsUri);
if (index === -1) {
throw new Error('Invalid documentation request path ' + req.path);
}
var mountpoint = req.path.substring(index + module.exports.api... | (parameter, checkFunction, json, done) {
if (json.__domain && json.__domain !== 'local') {
return done(null, json);
}
async.each(json.ast.resourceGroups, function(resourceGroup, groupDone) {
async.each(resourceGroup.resources, function(resource, resourceDone) {
var applies = fal... | addQueryParameter | identifier_name |
api-blueprint-resource.js | = req.query.source;
if (!_.startsWith(markdownPath, 'http')) {
var rootPath = __dirname.substring(0, __dirname.indexOf(rootDir) + rootDir.length);
markdownPath = rootPath + markdownPath;
}
var mountpoint = req.query.mountpoint;
apiBlueprint.loadFullMarkdown(markdownPath, mountpoint, nul... | });
return resource;
}
function renderHtml(json, done) { | random_line_split | |
LFEDocumentClassifier.py | *
from FileIO import *
# Handle command line arguments and set program parameters
if USE_CLI_ARGUMENTS:
args = collectCommandLineArguments()
USE_REUTERS = args.useReuters
USE_RAW_CSV = args.useCSV
CSV_FILE_PATH = args.csvPath
CSV_INPUT_COL = args.inputName
CSV_TARGET_COL = args.targetName
... |
# Apply all pre-processing to clean text and themes
ic = InputCleaner(dataFile, themePairs, 'excellenceText', 'themeExcellence', GENERATE_1D_THEMES)
ic.cleanText(REMOVE_NUMERIC, REMOVE_SINGLE_LETTERS, REMOVE_KEYWORDS, REMOVE_EXTRA_SPACES)
categoryCount = len(ALL_THEMES_LIST)
# TODO: [PIPELINE SPLIT 2]... | else:
# Read raw .XLSX file and store as pandas data-frame
dataFile = pd.read_excel(LFE_DATA_FILE_PATH, engine='openpyxl') | random_line_split |
LFEDocumentClassifier.py | from FileIO import *
# Handle command line arguments and set program parameters
if USE_CLI_ARGUMENTS:
args = collectCommandLineArguments()
USE_REUTERS = args.useReuters
USE_RAW_CSV = args.useCSV
CSV_FILE_PATH = args.csvPath
CSV_INPUT_COL = args.inputName
CSV_TARGET_COL = args.targetName
CLA... |
elif CLASSIFIER_NAME == 'nn':
if NN_USE_KERAS:
classifier = MultiLayerPerceptronKeras(featuresMasks, targetMasks,
TEST_GROUP_SIZE,
RANDOM_STATE,
NN_BATCH_SIZE,
... | classifier = ComplementNaiveBayes(featuresMasks, targetMasks,
USE_MULTI_LABEL_CLASSIFICATION,
TEST_GROUP_SIZE,
RANDOM_STATE,
PRINT_PROGRESS) | conditional_block |
state_chart.js | 0, .14)"
},
new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
// define the node's outer shape, which will surround the TextBlock
$(go.Shape, "RoundedRectangle", roundedRectangleParams,
{
name: "SHAPE", f... | random_line_split | ||
state_chart.js | () {
go.ForceDirectedLayout.call(this);
this._isObserving = false;
}
go.Diagram.inherit(ContinuousForceDirectedLayout, go.ForceDirectedLayout);
ContinuousForceDirectedLayout.prototype.isFixed = function (v) {
return v.node.isSelected;
};
// optimization: reuse the ForceDirectedNetwork rather than re-crea... | ContinuousForceDirectedLayout | identifier_name | |
state_chart.js | clear the network when replacing the model.
if (e.modelChange !== "" ||
(e.change === go.ChangedEvent.Transaction && e.propertyName === "StartingFirstTransaction")) {
lay.network = null;
}
});
}
var net = this.network;
if (net === null) { // ... | text: "动作"
};
// and add the link data to the model
model.addLinkData(linkdata);
// select the new Node
var newnode | nment = obj.part;
var diagram = e.diagram;
diagram.startTransaction("Add State");
// get the node data for which the user clicked the button
var fromNode = adornment.adornedPart;
var fromData = fromNode.data;
// create a new "State" data object, positioned off to the rig... | identifier_body |
multisig.go | menu.Option(menuItemStrings[sign], sign, false, func(opt wmenu.Opt) error {
wmenu.Clear()
id, proceed:= getSignParams()
if proceed == false {
fmt.Println("Transaction cancelled")
} else {
if SCID != "" {
sendTransaction(SCID, "Sign", "", 0, id)
} else {
fmt.Println("Please enter a SCID (M... | }
//Enter deposit amount, return value.
func getDepositAmount() (int64, bool) {
scanner := bufio.NewScanner(os.Stdin)
var amountString string
fmt.Print("Enter deposit amount in Dero: ")
scanner.Scan()
amountString = scanner.Text()
wmenu.Clear()
fmt.Printf("Do you want to deposit %s Dero? Enter Y/N (Yes/No)", ... | random_line_split | |
multisig.go | .Option(menuItemStrings[sign], sign, false, func(opt wmenu.Opt) error {
wmenu.Clear()
id, proceed:= getSignParams()
if proceed == false {
fmt.Println("Transaction cancelled")
} else {
if SCID != "" {
sendTransaction(SCID, "Sign", "", 0, id)
} else {
fmt.Println("Please enter a SCID (Menu O... |
}
return -1
}
// containsString returns true if slice contains element
func containsString(slice []string, element string) bool {
return !(posString(slice, element) == -1)
}
/*-----------------------------------------------------------RPC Functions--------------------------------------------------------------... | {
return index
} | conditional_block |
multisig.go | .Option(menuItemStrings[sign], sign, false, func(opt wmenu.Opt) error {
wmenu.Clear()
id, proceed:= getSignParams()
if proceed == false {
fmt.Println("Transaction cancelled")
} else {
if SCID != "" {
sendTransaction(SCID, "Sign", "", 0, id)
} else {
fmt.Println("Please enter a SCID (Menu O... |
/*-----------------------------------------------------------RPC Functions-----------------------------------------------------------------*/
//sendTransaction: send a transaction to the wallet or sign a transaction. entry should be "Send" or "Sign".
func sendTransaction(scid string, entry string, to string, ... | {
return !(posString(slice, element) == -1)
} | identifier_body |
multisig.go | := mainMenu()
return mm.Run()
})
menu.Option(menuItemStrings[displayUnsigned], displayUnsigned, false, func(opt wmenu.Opt) error {
wmenu.Clear()
displayTransactions(SCID, 1, "")
pressToContinue()
mm := mainMenu()
return mm.Run()
})
menu.Option(menuItemStrings[displaySigned], displaySigned, false,... | getKeysFromDaemon | identifier_name | |
local.rs | // by python, but they're not, so...
file_dbs: ShardedLmdb::new(files_root, 100 * GIGABYTES, executor.clone(), lease_time)
.map(Arc::new),
directory_dbs: ShardedLmdb::new(
directories_root,
5 * GIGABYTES,
executor.clone(),
lease_time,
)
... | {
Err(format!("Got hash collision reading from store - digest {:?} was requested, but retrieved bytes with that fingerprint had length {}. Congratulations, you may have broken sha256! Underlying bytes: {:?}", digest, bytes.len(), bytes))
} | conditional_block | |
local.rs | : AsRef<Path>>(
executor: task_executor::Executor,
path: P,
) -> Result<ByteStore, String> {
Self::new_with_lease_time(executor, path, DEFAULT_LEASE_TIME)
}
pub fn new_with_lease_time<P: AsRef<Path>>(
executor: task_executor::Executor,
path: P,
lease_time: Duration,
) -> Result<ByteStor... | .begin_rw_txn()
.and_then(|mut txn| {
let key = VersionedFingerprint::new(
aged_fingerprint.fingerprint,
ShardedLmdb::schema_version(),
);
txn.del(database, &key, None)?;
txn
.del(lease_database, &key, None)
... | env | random_line_split |
local.rs | ,
path: P,
) -> Result<ByteStore, String> {
Self::new_with_lease_time(executor, path, DEFAULT_LEASE_TIME)
}
pub fn new_with_lease_time<P: AsRef<Path>>(
executor: task_executor::Executor,
path: P,
lease_time: Duration,
) -> Result<ByteStore, String> {
let root = path.as_ref();
let fi... | load_bytes_with | identifier_name | |
runtime.rs | palette::pixel::{Srgb};
use rusttype::{FontCollection};
use tiled;
use calcium_game::{LoopTimer};
use calcium_rendering::{Error};
use calcium_rendering::texture::{Texture};
use calcium_rendering_2d::render_data::{RenderBatch, ShaderMode, Rectangle, Projection, RenderData, RenderSet, UvMode};
use calcium_rendering_2d:... |
}
pub fn render(&mut self, batches: &mut Vec<RenderBatch<R>>) {
//let mut batches = Vec::new();
let mut normaltexture = RenderBatch::new(
ShaderMode::Texture(self.tex.clone()), UvMode::YDown
);
normaltexture.push_rectangle_full_texture(
// position is cen... | {
if pinput.w {self.position.y -= self.speed * delta;}
if pinput.a {self.position.x -= self.speed * delta;}
if pinput.s {self.position.y += self.speed * delta;}
if pinput.d {self.position.x += self.speed * delta;}
} | conditional_block |
runtime.rs | palette::pixel::{Srgb};
use rusttype::{FontCollection};
use tiled;
use calcium_game::{LoopTimer};
use calcium_rendering::{Error};
use calcium_rendering::texture::{Texture};
use calcium_rendering_2d::render_data::{RenderBatch, ShaderMode, Rectangle, Projection, RenderData, RenderSet, UvMode};
use calcium_rendering_2d:... | (&mut self) -> Point2<f32> {
self.position
}
pub fn get_name(&mut self) -> &String {
&self.name
}
}
struct PlayerInput {
pub w: bool,
pub a: bool,
pub s: bool,
pub d: bool,
pub tab: bool,
}
pub struct StaticRuntime {
pub log: Logger,
}
impl Runtime for StaticRuntim... | get_position | identifier_name |
runtime.rs | use palette::pixel::{Srgb};
use rusttype::{FontCollection};
use tiled;
use calcium_game::{LoopTimer};
use calcium_rendering::{Error};
use calcium_rendering::texture::{Texture};
use calcium_rendering_2d::render_data::{RenderBatch, ShaderMode, Rectangle, Projection, RenderData, RenderSet, UvMode};
use calcium_rendering_... | );
normaltexture.push_rectangle_full_texture(
// position is centered in the texture
Rectangle::new(self.position + -self.size/2.0, self.position + self.size/2.0)
);
batches.push(normaltexture);
if self.selected {
let mut selectiontexture = Re... | }
pub fn render(&mut self, batches: &mut Vec<RenderBatch<R>>) {
//let mut batches = Vec::new();
let mut normaltexture = RenderBatch::new(
ShaderMode::Texture(self.tex.clone()), UvMode::YDown | random_line_split |
runtime.rs | palette::pixel::{Srgb};
use rusttype::{FontCollection};
use tiled;
use calcium_game::{LoopTimer};
use calcium_rendering::{Error};
use calcium_rendering::texture::{Texture};
use calcium_rendering_2d::render_data::{RenderBatch, ShaderMode, Rectangle, Projection, RenderData, RenderSet, UvMode};
use calcium_rendering_2d:... | }
pub fn get_position(&mut self) -> Point2<f32> {
self.position
}
pub fn get_name(&mut self) -> &String {
&self.name
}
}
struct PlayerInput {
pub w: bool,
pub a: bool,
pub s: bool,
pub d: bool,
pub tab: bool,
}
pub struct StaticRuntime {
pub log: Logger,
}
... | {
//let mut batches = Vec::new();
let mut normaltexture = RenderBatch::new(
ShaderMode::Texture(self.tex.clone()), UvMode::YDown
);
normaltexture.push_rectangle_full_texture(
// position is centered in the texture
Rectangle::new(self.position + -self.s... | identifier_body |
manager.py | elif self._filesystem.exists(self._artifacts_directory):
self._port.limit_archived_results_count()
# Rename the existing results folder for archiving.
self._port.rename_results_folder()
# Create the output directory if it doesn't already exist.
self._port.hos... | return int(worker_name.split('/')[1]) if worker_name else -1 | identifier_body | |
manager.py | ':
# Restore the test order to user specified order.
# base.tests() may change the order as it returns tests in the
# real, external/wpt, virtual order.
if paths:
test_names = self._restore_order(paths, test_names)
if not self._options.no_expectat... | (self, tests_to_run, tests_to_skip):
# Don't show results in a new browser window because we're already
# printing the link to diffs in the loop
self._options.show_results = False
while True:
initial_results, all_retry_results = self._run_test_once(
tests_to_... | _run_test_loop | identifier_name |
manager.py | ':
# Restore the test order to user specified order.
# base.tests() may change the order as it returns tests in the
# real, external/wpt, virtual order.
if paths:
test_names = self._restore_order(paths, test_names)
if not self._options.no_expectat... |
test_names += list(set(original_test_names) - set(test_names))
return test_names
def _collect_tests(self, args):
return self._finder.find_tests(
args,
test_lists=self._options.test_list,
filter_files=self._options.isolated_script_test_filter_file,
... | if test.startswith(path) or fnmatch.fnmatch(test, path):
test_names.append(test) | conditional_block |
manager.py | ':
# Restore the test order to user specified order.
# base.tests() may change the order as it returns tests in the
# real, external/wpt, virtual order.
if paths:
test_names = self._restore_order(paths, test_names)
if not self._options.no_expectat... | exit_code = exit_codes.INTERRUPTED_EXIT_STATUS
else:
if initial_results.interrupted:
exit_code = exit_codes.EARLY_EXIT_STATUS
if (self._options.show_results
and (exit_code or initial_results.total_failures)):
... | self._copy_results_html_file(self._artifacts_directory,
'results.html')
if (initial_results.interrupt_reason is
test_run_results.InterruptReason.EXTERNAL_SIGNAL): | random_line_split |
decision_tree.py |
oldEntropy = calEntropy(dataSet)
bestIndex = -1
maxInfoGainRotio = 0.0
for index in range(labelNum):
newEntropy = 0.0
splitInfo = 0.0
attrValueList = [entry[index] for entry in dataSet]
attrValueSet = set(attrValueList)
for uniqueValue in attrValueSet:
... | random_line_split | ||
decision_tree.py | float(labelsCount[key])/entryNum # propotion 特定标签占总标签比例
entropy -= propotion * log(propotion, 2)
return entropy
def calGini(dataSet):
"""
输入:二维数据集
输出:二维数据集的基尼系数
描述:计算数据集的基尼系数,基尼系数越大数据集越混乱
"""
entryNum = len(dataSet)
labelsCount = {}
for entry in dataSet:
... | :
propotion = | conditional_block | |
decision_tree.py |
subEntry = entry[:col]
subEntry.extend(entry[col+1:])
subDataSet.append(subEntry)
return subDataSet
def selectBestAttrIndex(dataSet, algorithm):
"""
输入:二维数据集
输出:熵减最大的属性在 dataSet 中的下标
描述:
先计算dataSet的熵,然后通过属性数目,遍历计算按照每个属性划分得到的熵;
比较得到熵减最大的属性,返回它... | tries) # 获得数据集二维列表
attr = ['attr' + str(i) for i in range(len(dataSet[0])-1)] # 获得属性向量
return dataSet, attr
def saveCarDataRes(path, carDataSetRes):
with open(path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(carDataSetRes)
def ca... | :
with open(path, 'r') as rf:
tree = eval(rf.read())
return tree
def loadCarDataSet(path):
with open(path, 'r') as csvfile:
entries = csv.reader(csvfile)
dataSet = list(en | identifier_body |
decision_tree.py | ��得dataSet中每个属性的所有value的列表
attrValueSet = set(attrValueList) # 获得value列表的不重复set,在ID3和C4.5中遍历计算每个value的熵,CART中用value进行二分类计算gini系数
for uniqueValue in attrValueSet:
subDataSet = splitDataSet(dataSet, index, uniqueValue) # 分离出col=index, value = uniqueValue 的数据集
p = float(len(su... | RT_Tree/car_C | identifier_name | |
bitfinex.py |
def _get_v2_symbols(self, assets):
"""
Workaround to support Bitfinex v2
TODO: Might require a separate asset dictionary
:param assets:
:return:
"""
v2_symbols = []
for asset in assets:
v2_symbols.append(self._get_v2_symbol(asset))
... | pair = asset.symbol.split('_')
symbol = 't' + pair[0].upper() + pair[1].upper()
return symbol | identifier_body | |
bitfinex.py | ize(date)
order = Order(
dt=date,
asset=self.assets[order_status['symbol']],
amount=amount,
stop=stop_price,
limit=limit_price,
filled=filled,
id=str(order_status['id']),
commission=commission
)
order... | response = self._request(
'order/status', {'order_id': int(order_id)}) | random_line_split | |
bitfinex.py | t' + pair[0].upper() + pair[1].upper()
return symbol
def _get_v2_symbols(self, assets):
"""
Workaround to support Bitfinex v2
TODO: Might require a separate asset dictionary
:param assets:
:return:
"""
v2_symbols = []
for asset in assets:
... |
if end_dt is not None:
end_ms = get_ms(end_dt)
url += '&end={0:f}'.format(end_ms)
else:
is_list = False
url += '/last'
try:
self.ask_request()
response = requests.get(url)
... | start_ms = get_ms(start_dt)
url += '&start={0:f}'.format(start_ms) | conditional_block |
bitfinex.py | t' + pair[0].upper() + pair[1].upper()
return symbol
def _get_v2_symbols(self, assets):
"""
Workaround to support Bitfinex v2
TODO: Might require a separate asset dictionary
:param assets:
:return:
"""
v2_symbols = []
for asset in assets:
... | (self):
# TODO: fetch account data and keep in cache
return None
def get_candles(self, data_frequency, assets, bar_count=None,
start_dt=None, end_dt=None):
"""
Retrieve OHLVC candles from Bitfinex
:param data_frequency:
:param assets:
:pa... | get_account | identifier_name |
compile.py | ('#'):
typ, arg = 'channel', arg[1:]
elif ':' in arg:
typ, arg = arg.split(':', 1)
else:
typ = 'str'
data = {}
if '(' in typ and typ.endswith(')'):
typ, typarg = typ.split('(', 1)
typarg = typarg[:-1]
data['type-argument'] = typarg
# make sure the... | split_on_space = False
continue
if split_on_space and c.isspace():
if gather:
tokens.append(gather)
gather = ''
else:
gather += c
if gather:
tokens.append(gather)
if expectstack:
warn('unbalanced brackets... | if c in expectmap:
expectstack.append(expectmap[c])
if expectstack and c == expectstack[-1]:
expectstack.pop()
if c == ':' and not expectstack: | random_line_split |
compile.py | '):
typ, arg = 'channel', arg[1:]
elif ':' in arg:
typ, arg = arg.split(':', 1)
else:
typ = 'str'
data = {}
if '(' in typ and typ.endswith(')'):
typ, typarg = typ.split('(', 1)
typarg = typarg[:-1]
data['type-argument'] = typarg
# make sure the ty... |
# names should be [a-z][0-9] and - only
if not all(c.isalpha() or c.isdigit() or c == '-' for c in name):
warn('name has invalid characters: {}'.format(name))
return name
def check_verb(verb):
if not verb.upper() == verb: # verbs should be upper case
warn('verb not upcased: {}'.format(... | warn('name has whitespace: {}'.format(name)) | conditional_block |
compile.py | '):
typ, arg = 'channel', arg[1:]
elif ':' in arg:
typ, arg = arg.split(':', 1)
else:
typ = 'str'
data = {}
if '(' in typ and typ.endswith(')'):
typ, typarg = typ.split('(', 1)
typarg = typarg[:-1]
data['type-argument'] = typarg
# make sure the ty... | (fmt, data):
data['format'] = fmt
# do our own tokenizing, to force balanced parens but handle : outside
tokens = []
expectstack = []
expectmap = {'(': ')', '[': ']', '<': '>'}
gather = ''
split_on_space = True
for c in fmt:
if c in expectmap:
expectstack.append(expe... | parse_format | identifier_name |
compile.py | '):
typ, arg = 'channel', arg[1:]
elif ':' in arg:
typ, arg = arg.split(':', 1)
else:
typ = 'str'
data = {}
if '(' in typ and typ.endswith(')'):
typ, typarg = typ.split('(', 1)
typarg = typarg[:-1]
data['type-argument'] = typarg
# make sure the ty... |
def check_name(name):
name = name.strip()
if not name: # names should have length
warn('zero-length name')
if name.lower() != name: # names should be lower-case
warn('name not lowcased: {}'.format(name))
if len(name.split()) > 1: # names should have no whitespace
warn('name has... | b, arg = unpack_brackets(arg_orig)
ret = {}
if not b:
# literal
return (['left', 'right'], {'type': 'literal', 'type-argument': arg})
elif b == '<':
typ = parse_inner_arg(arg, ret)
ret.update(typ)
return (['left', 'right'], ret)
elif b == '[':
ret['type'] ... | identifier_body |
splayTree.py | .value = value
self.parent = None
self.left = None
self.right = None
def search(self, value):
n = self._find(value)
n._splay()
return n
def insert(self, value):
"""
Inserts a new node with the specified value into the tree, which is then
... |
p.right = l
# move parent down + left
p.parent = self
self.left = p
# move this node up + left
self.parent = g
if g is not None:
if p is g.left:
g.left = self
elif p is g.right:
g.right = self
... | l.parent = p | conditional_block |
splayTree.py | self.left = None
self.right = None
def search(self, value):
n = self._find(value)
n._splay()
return n
def insert(self, value):
"""
Inserts a new node with the specified value into the tree, which is then
splayed around it.
O(n), amortized O(log... | """inserts value into tree. sets type if this hasn't been done yet."""
if self.typing is None: # first insertion: set type of this tree
self.typing = type(value)
else: # perform type check
if type(value) != self.typing:
raise TypeError("Type " + str(type(value))... | identifier_body | |
splayTree.py | .value = value
self.parent = None
self.left = None
self.right = None
def search(self, value):
n = self._find(value)
n._splay()
return n
| Inserts a new node with the specified value into the tree, which is then
splayed around it.
O(n), amortized O(log n).
"""
insertion_point = self._find(value)
n = SplayNode(value)
# value already in the tree; add at leftmost position in right subtreepa
if... | def insert(self, value):
""" | random_line_split |
splayTree.py | = value
self.parent = None
self.left = None
self.right = None
def search(self, value):
n = self._find(value)
n._splay()
return n
def insert(self, value):
"""
Inserts a new node with the specified value into the tree, which is then
splay... | (self, value):
"""
Searches for the specified value. If found, splays the tree around it;
removes it from the tree; finds its immediate predecessor; splays the
left subtree around that node; and attaches it to the right subtree. If
not found, splays the tree around its neare... | delete | identifier_name |
catalog.py | from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import random
import string
from oauth2client.client import flow_from_clientsecrets, FlowExchangeError
import httplib2
import json
import requests
CLIENT_ID = json.loads(open(
'client_secrets.json',
'r').read())['web'... | (item):
delItem = session.query(Item).filter_by(name=item).one_or_none()
if delItem is not None:
creator = getUserInfo(delItem.user_id)
if 'username' in login_session:
if creator.id == login_session[user_id]:
if request.method == 'POST':
session.de... | deleteItem | identifier_name |
catalog.py |
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import random
import string
from oauth2client.client import flow_from_clientsecrets, FlowExchangeError
import httplib2
import json
import requests
CLIENT_ID = json.loads(open(
'client_secrets.json',
'r').read())['web... | return response
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/'
'tokeninfo?access_token=%s' % access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
if result.get('error') is not None:
response = make_response... | except FlowExchangeError:
response = make_response(json.dumps(
'Failed to upgrade the authorization code'), 401)
response.headers['Content-Type'] = 'application/json' | random_line_split |
catalog.py |
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import random
import string
from oauth2client.client import flow_from_clientsecrets, FlowExchangeError
import httplib2
import json
import requests
CLIENT_ID = json.loads(open(
'client_secrets.json',
'r').read())['web... |
# function to retrieve User from user ID
def getUserInfo(user_id):
user = session.query(User).filter_by(id=user_id).one()
return user | try:
user = session.query(User).filter_by(email=email).one()
return user.id
except:
return None | identifier_body |
catalog.py | from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
import random
import string
from oauth2client.client import flow_from_clientsecrets, FlowExchangeError
import httplib2
import json
import requests
CLIENT_ID = json.loads(open(
'client_secrets.json',
'r').read())['web'... |
return render_template(
'catalog.html',
categories=categories,
items=items,
STATE=state)
# single category listing - all items in category
@app.route('/catalog/<category>/')
def showCategory(category):
cat = session.query(Category).filter_by(name=category).one_or_none()
if... | return render_template(
'publiccatalog.html',
categories=categories,
items=items, STATE=state) | conditional_block |
consumer.go | config,
client: client,
consumer: scsmr,
read: make(map[int32]int64),
acked: make(map[int32]int64),
partIDs: make([]int32, 0),
messages: make(chan *sarama.ConsumerMessage),
errors: make(chan *sarama.ConsumerError),
}
// Register consumer group and consumer itself
if err := consumer.regis... | {
if err := c.zoo.RegisterGroup(c.group, c.topic); err != nil {
return err
}
if err := c.zoo.RegisterConsumer(c.group, c.id, c.topic); err != nil {
return err
}
return nil
} | identifier_body | |
consumer.go | Notifier{Logger}
}
if c.CommitEvery < 10*time.Millisecond {
c.CommitEvery = 0
}
if c.DefaultOffsetMode != sarama.OffsetOldest && c.DefaultOffsetMode != sarama.OffsetOldest {
c.DefaultOffsetMode = sarama.OffsetOldest
}
if c.ZKSessionTimeout == 0 {
c.ZKSessionTimeout = time.Second
}
}
type Consumer struct {... | () string { return c.group }
// Topic exposes the group topic
func (c *Consumer) Topic() string { return c.topic }
// Offset manually retrives the stored offset for a partition ID
func (c *Consumer) Offset(partitionID int32) (int64, error) {
return c.zoo.Offset(c.group, c.topic, partitionID)
}
// Ack marks a consum... | Group | identifier_name |
consumer.go | Notifier{Logger}
}
if c.CommitEvery < 10*time.Millisecond {
c.CommitEvery = 0
}
if c.DefaultOffsetMode != sarama.OffsetOldest && c.DefaultOffsetMode != sarama.OffsetOldest {
c.DefaultOffsetMode = sarama.OffsetOldest
}
if c.ZKSessionTimeout == 0 {
c.ZKSessionTimeout = time.Second
}
}
type Consumer struct {... |
select {
case c.errors <- msg:
// fmt.Printf("!,%s,%d,%s\n", c.id, msg.Partition, msg.Error())
case <-done:
// fmt.Printf("@,%s\n", c.id)
return
}
case <-done:
// fmt.Printf("@,%s\n", c.id)
return
}
}
}
// PRIVATE
// Shutdown the consumer, triggered by the main loop
func (c *Consu... | {
offset, err := c.client.GetOffset(c.topic, msg.Partition, sarama.EarliestOffset)
if err == nil {
c.rLock.Lock()
c.read[msg.Partition] = offset
c.rLock.Unlock()
}
errs <- struct{}{}
} | conditional_block |
consumer.go | Notifier{Logger}
}
if c.CommitEvery < 10*time.Millisecond {
c.CommitEvery = 0
}
if c.DefaultOffsetMode != sarama.OffsetOldest && c.DefaultOffsetMode != sarama.OffsetOldest {
c.DefaultOffsetMode = sarama.OffsetOldest
}
if c.ZKSessionTimeout == 0 {
c.ZKSessionTimeout = time.Second
}
}
type Consumer struct {... | c.read[msg.Partition] = offset
c.rLock.Unlock()
}
errs <- struct{}{}
}
select {
case c.errors <- msg:
// fmt.Printf("!,%s,%d,%s\n", c.id, msg.Partition, msg.Error())
case <-done:
// fmt.Printf("@,%s\n", c.id)
return
}
case <-done:
// fmt.Printf("@,%s\n", c.id)
retur... | if err == nil {
c.rLock.Lock() | random_line_split |
meetingPlanner.py | class, which hosts our graph of DateNode nodes
class DateGraph:
def __init__(self,begDate,endDate):
listDates = getDateRange(begDate,endDate)
#list that holds dates in the graph and maps each date to date data
self.dates={}
#at initialization (initializes data for every date in the ... |
#adding a user that is completely absent
def addAbsentUser(self,user):
self.completelyAbsent.add(user)
#adding a user that is completely present
def addPresentUser(self,user):
self.completelyPresent.add(user)
#getting all the users that are absent on a specific date
... | dataToConsider = self.dates[timedate]
dataToConsider.usersAbsent.add(user)
dataToConsider.degree=len(dataToConsider.usersAbsent) | identifier_body |
meetingPlanner.py | class, which hosts our graph of DateNode nodes
class DateGraph:
def __init__(self,begDate,endDate):
listDates = getDateRange(begDate,endDate)
#list that holds dates in the graph and maps each date to date data
self.dates={}
#at initialization (initializes data for every date in the ... | if (userSelectedDate):
print("I am sorry, it seems there was an invalid input! Please try again: \n")
else:
#we have to check off all present
#in other words, do nothing, because all present doesnt really matter
... | dates=None
if (userSelectedDate):
dates=input("Please enter an individual date in the form mm/dd/yyyy or a range in the form mm/dd/yyyy:mm/dd/yyyy, or - if you wish to stop entering dates.")
else:
dates=input("Please enter either ALL ABSENT, ALL PRESENT, a date r... | conditional_block |
meetingPlanner.py | class, which hosts our graph of DateNode nodes
class DateGraph:
def __init__(self,begDate,endDate):
listDates = getDateRange(begDate,endDate)
#list that holds dates in the graph and maps each date to date data
self.dates={}
#at initialization (initializes data for every date in the ... | (self,timedate):
absentees=[]
for x in self.dates[timedate].usersAbsent:
absentees.append(x)
for x in self.completelyAbsent:
absentees.append(x)
return absentees
#counts the degree of a node
def countDegree(self,timedate):
#count the degree here
... | getAbsentUsers | identifier_name |
meetingPlanner.py | class, which hosts our graph of DateNode nodes
class DateGraph:
def __init__(self,begDate,endDate):
listDates = getDateRange(begDate,endDate)
#list that holds dates in the graph and maps each date to date data
self.dates={}
#at initialization (initializes data for every date in the ... | print("\n")
print("------------------------------------------------------\n")
#some functions to help with date stuff
#gets all the dates in the given range (returns a list of datetimes)
def getDateRange(begDate,endDate):
testDate=datetime.date(begDate.year,begDate.month,be... | if (y!=len(listAbsent)-1):
print(" "+y+",")
else:
print(" "+y)
| random_line_split |
supervisor.go | ' of the child processes (that is, the child
// processes after the terminated child process in the start order)
// are terminated. Then the terminated child process and all
// child processes after it are restarted
SupervisorStrategyRestForOne = SupervisorStrategyType("rest_for_one")
// SupervisorStrategySimpleO... | (supervisor Process, spec *SupervisorSpec, message interface{}) (interface{}, error) {
switch m := message.(type) {
case MessageDirectChildren:
children := []etf.Pid{}
for i := range spec.Children {
if spec.Children[i].process == nil {
continue
}
children = append(children, spec.Children[i].process.S... | handleDirect | identifier_name |
supervisor.go | if p != nil && p.IsAlive() {
p.Exit(ex.Reason)
}
}
return ex.Reason
}
waitTerminatingProcesses = handleMessageExit(ps, ex, spec, waitTerminatingProcesses)
case <-ps.Context().Done():
return "kill"
case direct := <-chs.Direct:
value, err := handleDirect(ps, spec, direct.Message)
... | {
for i := range spec {
if spec[i].Name == specName {
return spec[i], nil
}
}
return SupervisorChildSpec{}, fmt.Errorf("unknown child")
} | identifier_body | |
supervisor.go |
}
// Supervisor is implementation of ProcessBehavior interface
type Supervisor struct{}
type messageStartChild struct {
name string
args []etf.Term
}
// ProcessInit
func (sv *Supervisor) ProcessInit(p Process, args ...etf.Term) (ProcessState, error) {
behavior, ok := p.Behavior().(SupervisorBehavior)
if !ok {
... | {
continue
} | conditional_block | |
supervisor.go | ' of the child processes (that is, the child
// processes after the terminated child process in the start order)
// are terminated. Then the terminated child process and all
// child processes after it are restarted
SupervisorStrategyRestForOne = SupervisorStrategyType("rest_for_one")
// SupervisorStrategySimpleO... | return process, nil
}
func startChildren(supervisor Process, spec *SupervisorSpec) {
spec.restarts = append(spec.restarts, time.Now().Unix())
if len(spec.restarts) > int(spec.Strategy.Intensity) {
period := time.Now().Unix() - spec.restarts[0]
if period <= int64(spec.Strategy.Period) {
lib.Warning("Superviso... | return nil, fmt.Errorf("internal error: can't start child %#v", value)
} | random_line_split |
array.rs | isize{
fn into(self)->usize{ self as usize }
}
*/
#[derive(Debug)]
pub struct Array<T,I=i32>(pub Vec<T>,PhantomData<I>);
// my array helper fn's
impl<T:Clone,I:IndexTrait+Clone> Array<T,I>{
/// TODO - better name. preserves ordering of vec![v;count].
pub fn from_val_n(val:T, n:i32)->Self{
let v=vec![val; n as... | {
self.0.splice(range,replace_with)
}
pub fn drain_filter<F:FnMut(&mut T)->bool>(&mut self, filter: F) -> DrainFilter<T, F> {
self.0.drain_filter(filter)
}
}
impl<T,INDEX:IndexTrait> Deref for Array<T,INDEX>{
type Target=[T];
fn deref(&self)->&Self::Target { self.0.deref() }
}
impl<T,INDEX:IndexTrait> Array... |
impl<T,INDEX:IndexTrait> Array<T,INDEX>{
/// TODO - figure out how to convert RangeArguemnt indices
pub fn splice<I:IntoIterator<Item=T>,R:RangeArgument<usize>>(&mut self, range:R, replace_with:I)-> Splice<<I as IntoIterator>::IntoIter> | random_line_split |
array.rs | isize{
fn into(self)->usize{ self as usize }
}
*/
#[derive(Debug)]
pub struct Array<T,I=i32>(pub Vec<T>,PhantomData<I>);
// my array helper fn's
impl<T:Clone,I:IndexTrait+Clone> Array<T,I>{
/// TODO - better name. preserves ordering of vec![v;count].
pub fn from_val_n(val:T, n:i32)->Self{
let v=vec![val; n as... | (&self)->*const T{self.0.as_ptr()}
fn as_mut_ptr(&mut self)->*mut T{self.0.as_mut_ptr()}
fn swap(&mut self, a:INDEX,b:INDEX){
self.0.swap(a.my_into(),b.my_into())
}
fn reverse(&mut self){self.0.reverse()}
fn iter(&self)->Iter<T>{self.0.iter()}
fn iter_mut(&mut self)->IterMut<T>{self.0.iter_mut()}
fn windows(&s... | as_ptr | identifier_name |
array.rs | {
fn into(self)->usize{ self as usize }
}
*/
#[derive(Debug)]
pub struct Array<T,I=i32>(pub Vec<T>,PhantomData<I>);
// my array helper fn's
impl<T:Clone,I:IndexTrait+Clone> Array<T,I>{
/// TODO - better name. preserves ordering of vec![v;count].
pub fn from_val_n(val:T, n:i32)->Self{
let v=vec![val; n as usize... |
pub fn as_slice(&self) -> &[T]{
self.0.as_slice()
}
pub fn as_mut_slice(&mut self) -> &mut [T]{
self.0.as_mut_slice()
}
pub fn swap_remove(&mut self, index: I) -> T{
self.0.swap_remove(index.my_into())
}
pub fn insert(&mut self, index: I, element: T){
self.0.insert(index.my_into(),element)
}
pub fn re... | {
self.0.truncate(len.my_into());
} | identifier_body |
codemap.rs | <Span> {
self.primary_spans.first().cloned()
}
/// Returns all primary spans.
pub fn primary_spans(&self) -> &[Span] {
&self.primary_spans
}
/// Returns the strings to highlight. We always ensure that there
/// is an entry for each of the primary spans -- for each primary
/// span P, if there is... | {
src.drain(..3);
} | conditional_block | |
codemap.rs | Span { lo: BytePos(lo), hi: self.hi }
}
/// Returns `self` if `self` is not the dummy span, and `other` otherwise.
pub fn substitute_dummy(self, other: Span) -> Span {
if self.source_equal(&DUMMY_SPAN) { other } else { self }
}
pub fn contains(self, other: Span) -> bool {
self.lo <= other.lo && ... | /// The absolute path of the file that the source came from.
pub abs_path: Option<FileName>,
/// The complete source code
pub src: Option<Rc<String>>,
/// The start position of this source in the CodeMap
pub start_pos: BytePos,
/// The end position of this source in the CodeMap
pub end_pos: BytePos,
/... | /// originate from files has names between angle brackets by convention,
/// e.g. `<anon>`
pub name: FileName, | random_line_split |
codemap.rs | Span { lo: BytePos(lo), hi: self.hi }
}
/// Returns `self` if `self` is not the dummy span, and `other` otherwise.
pub fn substitute_dummy(self, other: Span) -> Span {
if self.source_equal(&DUMMY_SPAN) { other } else { self }
}
pub fn contains(self, other: Span) -> bool {
self.lo <= other.lo && ... | (self, other: Span) -> Option<Span> {
if self.hi > other.hi {
Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
} else {
None
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy)]
pub struct Spanned<T> {
pub node: T,
pub span: Span,
}
/// A collection of spans. Spans have two or... | trim_start | identifier_name |
lstm.py |
print(row)
# print(sql_select_Query)
# sql_select_Query="SELECT concat( year,Month) as Date , unit_price as data FROM oildata"
df = pd.read_sql(sql_select_Query, connection);
columnsNamesArr = df.columns.values
listOfColumnNames = list(columnsNamesArr)
print(listOfColumnNames)
print(len(listOfCol... |
valX, valY = get_val()
# create and fit the LSTM network
from pandas import DataFrame
train1 = DataFrame()
val1 = DataFrame()
# for i in range(5):
model = Sequential()
model.add(LSTM(units=300, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(units=25... | X1, y1 = [], []
print(train_size + 6)
print(len(df))
for i in range(train_size + 6, len(df)):
X1.append(scaled_data[i - 6:i, 0])
y1.append(scaled_data[i, 0])
X1, y1 = np.array(X1), np.array(y1)
print(X1)
print(len(X1))
X1 = np.r... | identifier_body |
lstm.py | )
# # print( last_date.index)
# forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])
# plt.plot(train['data'])
# plt.plot(valid['data'])
# print(forecast)
# plt.plot(forecast['Prediction'])
# plt.show()
#
from sklearn.preprocessing import MinMaxScaler
from keras.models impor... | X1.append(scaled_data[i - 6:i, 0])
y1.append(scaled_data[i, 0]) | conditional_block | |
lstm.py | ,max_p=3, max_q=3, m=12,start_P=0, seasonal=False,d=1, D=1, trace=True,error_action='ignore',suppress_warnings=True)
# # model = auto_arima(training,seasonal=True,trace=True,error_action='ignore',suppress_warnings=True)
# model.fit(training)
# forecast = model.predict(n_periods=test_size)
# # rms=np.sqrt(np.mean(np... | get_train | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.