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
from contextlib import contextmanager from functools import partial import urlparse from django.core.cache import get_cache from django.core.handlers.wsgi import WSGIHandler from django.test.signals import template_rendered from django.test.client import RequestFactory, store_rendered_templates from mock import patch ...
(): cache = get_cache("django.core.cache.backends.locmem.LocMemCache") cache.clear() patcher = patch("ccui.core.cache.cache", cache) patcher.start() yield cache patcher.stop() class CachingFunctionalTestMixin(object): def setUp(self): self.cache = get_cache("django.core.cache.back...
locmem_cache
identifier_name
utils.py
from contextlib import contextmanager from functools import partial import urlparse from django.core.cache import get_cache from django.core.handlers.wsgi import WSGIHandler from django.test.signals import template_rendered from django.test.client import RequestFactory, store_rendered_templates from mock import patch ...
return self._resource_list_class def get_resource_list_class(self): raise NotImplementedError def assertSameResource(self, res1, res2): self.assertEqual(res1._location, res2._location) def assertSameResourceList(self, list1, list2): self.assertEqual( [r._l...
self._resource_list_class = self.get_resource_list_class()
conditional_block
utils.py
from contextlib import contextmanager from functools import partial import urlparse from django.core.cache import get_cache from django.core.handlers.wsgi import WSGIHandler from django.test.signals import template_rendered from django.test.client import RequestFactory, store_rendered_templates from mock import patch ...
response_dict.setdefault( "http://fake.base/rest/users/current?_type=json", response( users.one( email=user.email, firstName=user.firstName, lastName=user.lastName, screenName=user.screenName ...
if response_dict is None: response_dict = {} else: response_dict = response_dict.copy()
random_line_split
utils.py
from contextlib import contextmanager from functools import partial import urlparse from django.core.cache import get_cache from django.core.handlers.wsgi import WSGIHandler from django.test.signals import template_rendered from django.test.client import RequestFactory, store_rendered_templates from mock import patch ...
class Url(object): """ A wrapper class for comparing urls with querystrings while avoiding dict-ordering dependencies. Order of keys in querystring should not matter, although order of multiple values for a single key does matter. """ def __init__(self, url): self.url = url ...
""" Generic smoke tests that will be run for all resource types. """ pass
identifier_body
jquery-collision.js
/* Copyright (c) 2011 Sean Cusack MIT-LICENSE: 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, d...
Collision.prototype.distance = function(other) { var tc = c.target; var oc = c.overlap; return Math.sqrt((tc.centerx() - oc.centerx()) * (tc.centerx() - oc.centerx()) + (tc.centery() - oc.centery()) * (tc.centery() - oc.centery())); } function CollisionFactory(targets, ...
{ this.target = targetNode; this.obstacle = obstacleNode; this.overlap = overlapCoords; this.overlapType = overlapType; }
identifier_body
jquery-collision.js
/* Copyright (c) 2011 Sean Cusack MIT-LICENSE: 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, d...
return clone; } CollisionCoords.prototype.move = function(dx, dy) { this.x1 += dx; this.x2 += dx; this.y1 += dy; this.y2 += dy; return this; }; CollisionCoords.prototype.update = function(obj) { if ("x1" in obj) this.x1 = obj["x1"]; if (...
{ clone.x1 += parseInt(this.proto.css("margin-left")) || 0; clone.x1 += parseInt(this.proto.css("border-left")) || 0; clone.x1 += parseInt(this.proto.css("padding-left")) || 0; clone.x2 -= parseInt(this.proto.css("padding-right")) || 0; clone.x2 -= parseInt(th...
conditional_block
jquery-collision.js
/* Copyright (c) 2011 Sean Cusack MIT-LICENSE: 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, d...
})]; } } if (hit) { if (dirs["NW"] && dirs["NE"]) hit[0].dir = "N"; if (dirs["NE"] && dirs["SE"]) hit[0].dir = "E"; if (dirs["SE"] && dirs["SW"]) hit[0].dir = "S"; if (dirs["SW"] && dirs["NW"]) hit[0].dir = "W"; if (...
random_line_split
jquery-collision.js
/* Copyright (c) 2011 Sean Cusack MIT-LICENSE: 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, d...
(targets, obstacles, containment) { this.targets = targets; this.obstacles = obstacles; this.collisions = null; this.cache = null; if (containment) this.containment = containment; else this.containment = null; } CollisionFactory.prototype.getCollisions = function...
CollisionFactory
identifier_name
regex.py
# https://developers.google.com/edu/python/regular-expressions # https://docs.python.org/3/howto/regex.html ''' Check out the following links for more information: https://docs.python.org/3/howto/regex.html https://docs.python.org/3/library/re.html https://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy Sh...
import re ''' search('r'pattern,text) : serach pattern in test, 'r' flag = raw string. which passes through backslashes without change which is very handy for regular expressions importance of rflag in particular, \b matches empty string specifically at the start and end of a word. re expects the string \b, however...
'''
random_line_split
regex.py
# https://developers.google.com/edu/python/regular-expressions # https://docs.python.org/3/howto/regex.html ''' Check out the following links for more information: https://docs.python.org/3/howto/regex.html https://docs.python.org/3/library/re.html https://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy Sh...
# findall and groups str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher' tuples = re.findall(r'([\w\.-]+)@([\w\.-]+)', str) print (tuples) ## [('alice', 'google.com'), ('bob', 'abc.com')] for tuple in tuples: tuple print (tuple[0]) ## username print (tuple[1]) ## host ''' findall() wit...
print (email)
conditional_block
eth.rs
//! Ethernet PHY layer for the STM32H7 //! //! As well as this implementation, another notable implementation can //! be found as part of the [quartiq/stabilizer] project. The two //! implementations were developed independently, but both in the same //! year (2019) and they have many similarities. //! //! In particula...
(&self) -> u32 { self.eth_dma.dmacmfcr.read().mfc().bits() as u32 } } /// Clears the Ethernet interrupt flag /// /// # Safety /// /// This method implements a single register write to DMACSR pub unsafe fn interrupt_handler() { let eth_dma = &*stm32::ETHERNET_DMA::ptr(); eth_dma .dmacsr ...
number_packets_dropped
identifier_name
eth.rs
//! Ethernet PHY layer for the STM32H7 //! //! As well as this implementation, another notable implementation can //! be found as part of the [quartiq/stabilizer] project. The two //! implementations were developed independently, but both in the same //! year (2019) and they have many similarities. //! //! In particula...
/// Enables the Ethernet Interrupt. The following interrupts are enabled: /// /// * Normal Interrupt `NIE` /// * Receive Interrupt `RIE` /// * Transmit Interript `TIE` /// /// # Safety /// /// This method implements a single RMW to DMACIER pub unsafe fn enable_interrupt() { let eth_dma = &*stm32::ETHERNET_DMA::pt...
{ let eth_dma = &*stm32::ETHERNET_DMA::ptr(); eth_dma .dmacsr .write(|w| w.nis().set_bit().ri().set_bit().ti().set_bit()); let _ = eth_dma.dmacsr.read(); let _ = eth_dma.dmacsr.read(); // Delay 2 peripheral clocks }
identifier_body
eth.rs
//! Ethernet PHY layer for the STM32H7 //! //! As well as this implementation, another notable implementation can //! be found as part of the [quartiq/stabilizer] project. The two //! implementations were developed independently, but both in the same //! year (2019) and they have many similarities. //! //! In particula...
// Contains first buffer of packet AND contains last buf of // packet AND no errors AND not a contex descriptor self.rdes3 & (EMAC_DES3_FD | EMAC_DES3_LD | EMAC_DES3_ES | EMAC_DES3_CTXT) == (EMAC_DES3_FD | EMAC_DES3_LD) } /// Return true if this RDes is not curre...
// Write-back descriptor is valid if: //
random_line_split
models.py
import datetime import importlib import logging import re from collections import OrderedDict from copy import copy from datetime import date, timedelta from exceptions import ProperNotFound from typing import ItemsView, List, Tuple, Union from constants.common import (C_10A, C_10B, C_10C, C_10PASC, C_10T, PENT01_0A, ...
def items(self) -> ItemsView[date, Day]: return self._container.items() def serialize(self) -> dict: serialized = {} for date_, day in self.items(): serialized[date_.strftime('%Y-%m-%d')] = day.serialize() return serialized
if observance_id in [ii.id for ii in day.all]: return date_, day
conditional_block
models.py
import datetime import importlib import logging import re from collections import OrderedDict from copy import copy from datetime import date, timedelta from exceptions import ProperNotFound from typing import ItemsView, List, Tuple, Union from constants.common import (C_10A, C_10B, C_10C, C_10PASC, C_10T, PENT01_0A, ...
(self) -> Union[None, str]: if self.celebration: return self.celebration[0].title def get_proper(self) -> List[Tuple['Proper', 'Proper']]: """ Get proper that is used in today Mass. If given day does not have a dedicated proper, use the one from the latest Sunday. ...
get_celebration_name
identifier_name
models.py
import datetime import importlib import logging import re from collections import OrderedDict from copy import copy from datetime import date, timedelta from exceptions import ProperNotFound from typing import ItemsView, List, Tuple, Union from constants.common import (C_10A, C_10B, C_10C, C_10PASC, C_10T, PENT01_0A, ...
def serialize(self) -> dict: serialized = {} for container in ('tempora', 'celebration', 'commemoration'): serialized[container] = [i.serialize() for i in getattr(self, container)] return serialized def __str__(self): return str(self.tempora) + str(self.celebration...
""" Get proper that is used in today Mass. If given day does not have a dedicated proper, use the one from the latest Sunday. """ if self.celebration: try: return [i.get_proper() for i in self.celebration] except ProperNotFound as e: ...
identifier_body
models.py
import datetime import importlib import logging import re from collections import OrderedDict from copy import copy from datetime import date, timedelta from exceptions import ProperNotFound from typing import ItemsView, List, Tuple, Union from constants.common import (C_10A, C_10B, C_10C, C_10PASC, C_10T, PENT01_0A, ...
self._container[date_] = Day(date_, self) date_ += timedelta(days=1) def get_day(self, date_: datetime.date) -> Day: return self._container.get(date_) def find_day(self, observance_id: str) -> Union[None, Tuple[date, Day]]: """ Return a day representation by observance ...
date_ = date(year, 1, 1) while date_.year == year:
random_line_split
sample.go
// Copyright 2023 The Swarm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package storer import ( "bytes" "context" "crypto/hmac" "encoding/binary" "fmt" "math/big" "sort" "sync" "testing" "time" "github.com/etherspher...
(other SampleStats) { s.TotalDuration += other.TotalDuration s.TotalIterated += other.TotalIterated s.IterationDuration += other.IterationDuration s.SampleInserts += other.SampleInserts s.NewIgnored += other.NewIgnored s.InvalidStamp += other.InvalidStamp s.BelowBalanceIgnored += other.BelowBalanceIgnored s.Hma...
add
identifier_name
sample.go
// Copyright 2023 The Swarm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package storer import ( "bytes" "context" "crypto/hmac" "encoding/binary" "fmt" "math/big" "sort" "sync" "testing" "time" "github.com/etherspher...
ChunkLoadFailed int64 StampLoadFailed int64 } func (s *SampleStats) add(other SampleStats) { s.TotalDuration += other.TotalDuration s.TotalIterated += other.TotalIterated s.IterationDuration += other.IterationDuration s.SampleInserts += other.SampleInserts s.NewIgnored += other.NewIgnored s...
random_line_split
sample.go
// Copyright 2023 The Swarm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package storer import ( "bytes" "context" "crypto/hmac" "encoding/binary" "fmt" "math/big" "sort" "sync" "testing" "time" "github.com/etherspher...
type SampleStats struct { TotalDuration time.Duration TotalIterated int64 IterationDuration time.Duration SampleInserts int64 NewIgnored int64 InvalidStamp int64 BelowBalanceIgnored int64 HmacrDuration time.Duration Val...
{ // Calculate transformed address from wrapped chunk sChunk, err := soc.FromChunk(chunk) if err != nil { return swarm.ZeroAddress, err } taddrCac, err := transformedAddressCAC(hasher, sChunk.WrappedChunk()) if err != nil { return swarm.ZeroAddress, err } // Hash address and transformed address to make tra...
identifier_body
sample.go
// Copyright 2023 The Swarm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package storer import ( "bytes" "context" "crypto/hmac" "encoding/binary" "fmt" "math/big" "sort" "sync" "testing" "time" "github.com/etherspher...
// Skip chunks if they are not SOC or CAC if chItem.Type != swarm.ChunkTypeSingleOwner && chItem.Type != swarm.ChunkTypeContentAddressed { wstat.RogueChunk++ continue } chunkLoadStart := time.Now() chunk, err := db.ChunkStore().Get(ctx, chItem.ChunkAddress) if err != nil { ...
{ wstat.BelowBalanceIgnored++ continue }
conditional_block
voxel_detection.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Any, Dict, List, Optional, Sequence, Tuple, Union import mmcv import numpy as np import torch import torch.nn as nn from mmcv.parallel import collate, scatter from mmdet3d.core.bbox import get_box_type from mmdet3d.datasets.pipelines import Compose fro...
def __init__(self, model_cfg: mmcv.Config, deploy_cfg: mmcv.Config, device: str): super().__init__(model_cfg, deploy_cfg, device) def init_backend_model(self, model_files: Sequence[str] = None, **kwargs) -> torch.nn.Module: """I...
identifier_body
voxel_detection.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Any, Dict, List, Optional, Sequence, Tuple, Union import mmcv import numpy as np import torch import torch.nn as nn from mmcv.parallel import collate, scatter from mmdet3d.core.bbox import get_box_type from mmdet3d.datasets.pipelines import Compose fro...
(self, model_cfg: mmcv.Config, deploy_cfg: mmcv.Config, device: str): super().__init__(model_cfg, deploy_cfg, device) def init_backend_model(self, model_files: Sequence[str] = None, **kwargs) -> torch.nn.Module: """Initialize ba...
__init__
identifier_name
voxel_detection.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Any, Dict, List, Optional, Sequence, Tuple, Union import mmcv import numpy as np import torch import torch.nn as nn from mmcv.parallel import collate, scatter from mmdet3d.core.bbox import get_box_type from mmdet3d.datasets.pipelines import Compose fro...
else: model.module.show_result( data, result, out_dir=out_dir, file_name=f'model_output{i}', show=show, snapshot=True, ...
model.module.show_result( data, result, out_dir='', file_name='', show=show, snapshot=False, score_thr=0.3)
conditional_block
bnj.go
package service import ( "context" "encoding/json" "math/rand" "regexp" "strings" "time" "go-common/app/job/main/dm2/model" "go-common/app/service/main/archive/api" arcMdl "go-common/app/service/main/archive/model/archive" filterMdl "go-common/app/service/main/filter/api/grpc/v1" "go-common/library/ecode" ...
} return } func (s *Service) checkBnjDmMsg(c context.Context, msg string) (err error) { var ( msgLen = len([]rune(msg)) ) if msgRegex.MatchString(msg) { // 空白弹幕 err = ecode.DMMsgIlleagel return } if msgLen > _bnjDmMsgLen { err = ecode.DMMsgTooLong return } if strings.Contains(msg, `\n`) || strings.C...
dm.State = model.StateFilter log.Info("bnj filter service delete(dmid:%d,data:+%v)", dm.ID, filterReply)
random_line_split
bnj.go
package service import ( "context" "encoding/json" "math/rand" "regexp" "strings" "time" "go-common/app/job/main/dm2/model" "go-common/app/service/main/archive/api" arcMdl "go-common/app/service/main/archive/model/archive" filterMdl "go-common/app/service/main/filter/api/grpc/v1" "go-common/library/ecode" ...
ig *model.BnjLiveConfig start time.Time ) if bnjConfig, err = s.dao.BnjConfig(c); err != nil { log.Error("bnjLiveConfig error current:%v err:%+v", time.Now().String(), err) return } if bnjConfig == nil { log.Error("bnjLiveConfig error current:%v bnjConfig nil", time.Now().String()) return } if start...
identifier_body
bnj.go
package service import ( "context" "encoding/json" "math/rand" "regexp" "strings" "time" "go-common/app/job/main/dm2/model" "go-common/app/service/main/archive/api" arcMdl "go-common/app/service/main/archive/model/archive" filterMdl "go-common/app/service/main/filter/api/grpc/v1" "go-common/library/ecode" ...
.Context, tp int32, v *model.Video) (err error) { sub, err := s.dao.Subject(c, tp, v.Cid) if err != nil { return } if sub == nil { if v.XCodeState >= model.VideoXcodeHDFinish { if _, err = s.dao.AddSubject(c, tp, v.Cid, v.Aid, v.Mid, s.maxlimit(v.Duration), 0); err != nil { return } } } else { if...
eo(c context
identifier_name
bnj.go
package service import ( "context" "encoding/json" "math/rand" "regexp" "strings" "time" "go-common/app/job/main/dm2/model" "go-common/app/service/main/archive/api" arcMdl "go-common/app/service/main/archive/model/archive" filterMdl "go-common/app/service/main/filter/api/grpc/v1" "go-common/library/ecode" ...
= &model.DM{ ID: dmid, Type: model.SubTypeVideo, Oid: chosen.Cid, Mid: dm.Mid, Progress: int32((chosen.Duration + 1) * 1000), Pool: dm.Pool, State: model.StateAdminDelete, Ctime: dm.Ctime, Mtime: dm.Mtime, Content: &model.Content{ ID: dmid, FontSize: dm.C...
ror("bnjDmCount genDMID() error(%v)", err) return } forkDM :
conditional_block
raw.py
from typing import TypedDict, Callable, Union, Dict, List, Any, Iterable, Literal #Note: no docs for Memory or RawMemory #will create a copy with all typings unneccesary for casting removed once finished from enums import * #MapVisual.import -> from_string #MapVisual.export -> to_string #GameObject is a Union of a...
class InterShardMemory(): getLocal: Callable[[], str] setLocal: Callable[[str], None] getRemote: Callable[[str], str] class PathFinderOpts(TypedDict): roomCallback: Optional[Callable[[str], Union[CostMatrix, bool]]] plainCost: Optional[NumberType] swampCost: Optional[NumberType] flee: Optional[bool] maxOps: ...
constructionSites: Dict[str, ConstructionSite] cpu: CPUType creeps: Dict[str, Creep] flags: Dict[str, Flag] gcl: GLType gpl: GLType map: Map market: Market powerCreeps: Dict[str, PowerCreep] resources: ResourcesType rooms: Dict[str, Room] shard: ShardType spawns: Dict[str, StructureSpawn] structures: Dict[...
identifier_body
raw.py
from typing import TypedDict, Callable, Union, Dict, List, Any, Iterable, Literal #Note: no docs for Memory or RawMemory #will create a copy with all typings unneccesary for casting removed once finished from enums import * #MapVisual.import -> from_string #MapVisual.export -> to_string #GameObject is a Union of a...
class ShardType(TypedDict): name: str type: str ptr: bool class MultiRoomRouteOpts(TypedDict): routeCallback: Callable[[str, str], NumberType] class MultiRoomRouteOutput(TypedDict): exit: NumberType room: str class RoomStatus(TypedDict): status: str timestamp: NumberType class LineStyle(TypedDict): width: ...
level: NumberType progress: NumberType progressTotal: NumberType
random_line_split
raw.py
from typing import TypedDict, Callable, Union, Dict, List, Any, Iterable, Literal #Note: no docs for Memory or RawMemory #will create a copy with all typings unneccesary for casting removed once finished from enums import * #MapVisual.import -> from_string #MapVisual.export -> to_string #GameObject is a Union of a...
(RoomFindPathOpts): reusePath: Optional[NumberType] serializeMemory: Optional[bool] noPathFinding: Optional[bool] visualizePathStyle: Optional[RoomVisualPolyStyle] Pos = Union[RoomObject, RoomPos] class BaseCreep(RoomObject): hits: NumberType hitsMax: NumberType id: str memory: Any my: bool name: str owner...
CreepMoveToOpts
identifier_name
types.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Loaded representation for runtime types. use libra_types::{ account_address::AccountAddress, vm_error::{StatusCode, VMStatus}, }; use move_core_types::{ identifier::Identifier, language_storage::{StructTag, TypeTag}...
Signer => debug_write!(buf, "signer"), Vector(elem_ty) => { debug_write!(buf, "vector<")?; elem_ty.debug_print(buf)?; debug_write!(buf, ">") } Struct(struct_ty) => struct_ty.debug_print(buf), Reference(ty) => { ...
Address => debug_write!(buf, "address"),
random_line_split
types.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Loaded representation for runtime types. use libra_types::{ account_address::AccountAddress, vm_error::{StatusCode, VMStatus}, }; use move_core_types::{ identifier::Identifier, language_storage::{StructTag, TypeTag}...
(&self) -> VMResult<bool> { use FatType::*; match self { Bool | U8 | U64 | U128 | Address | Reference(_) | MutableReference(_) => Ok(false), Signer => Ok(true), Vector(ty) => ty.is_resource(), Struct(struct_ty) => Ok(struct_ty.is_resource), //...
is_resource
identifier_name
types.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Loaded representation for runtime types. use libra_types::{ account_address::AccountAddress, vm_error::{StatusCode, VMStatus}, }; use move_core_types::{ identifier::Identifier, language_storage::{StructTag, TypeTag}...
pub fn is_resource(&self) -> VMResult<bool> { use FatType::*; match self { Bool | U8 | U64 | U128 | Address | Reference(_) | MutableReference(_) => Ok(false), Signer => Ok(true), Vector(ty) => ty.is_resource(), Struct(struct_ty) => Ok(struct_ty.is_r...
{ use FatType::*; let res = match self { Bool => TypeTag::Bool, U8 => TypeTag::U8, U64 => TypeTag::U64, U128 => TypeTag::U128, Address => TypeTag::Address, Signer => TypeTag::Signer, Vector(ty) => TypeTag::Vector(Box::n...
identifier_body
hash2curve.rs
use super::FieldElement; use crate::{AffinePoint, FieldBytes, NistP384, ProjectivePoint, Scalar}; use elliptic_curve::{ bigint::{ArrayEncoding, U384}, consts::U72, generic_array::GenericArray, hash2curve::{FromOkm, GroupDigest, MapToCurve, OsswuMap, OsswuMapParams, Sgn0}, ops::Reduce, point::Dec...
} panic!("deriving key failed"); } } #[test] fn from_okm_fuzz() { let mut wide_order = GenericArray::default(); wide_order[24..].copy_from_slice(&NistP384::ORDER.to_be_byte_array()); let wide_order = NonZero::new(U576::from_be_byte_array(wide_order)...
{ assert_eq!(scalar.to_bytes().as_slice(), test_vector.sk_sm); continue 'outer; }
conditional_block
hash2curve.rs
use super::FieldElement; use crate::{AffinePoint, FieldBytes, NistP384, ProjectivePoint, Scalar}; use elliptic_curve::{ bigint::{ArrayEncoding, U384}, consts::U72, generic_array::GenericArray, hash2curve::{FromOkm, GroupDigest, MapToCurve, OsswuMap, OsswuMapParams, Sgn0}, ops::Reduce, point::Dec...
#[test] fn from_okm_fuzz() { let mut wide_order = GenericArray::default(); wide_order[24..].copy_from_slice(&NistP384::ORDER.to_be_byte_array()); let wide_order = NonZero::new(U576::from_be_byte_array(wide_order)).unwrap(); let simple_from_okm = move |data: GenericArray<u8, U7...
{ struct TestVector { dst: &'static [u8], key_info: &'static [u8], seed: &'static [u8], sk_sm: &'static [u8], } const TEST_VECTORS: &[TestVector] = &[ TestVector { dst: b"DeriveKeyPairVOPRF10-\x00\x00\x04", ...
identifier_body
hash2curve.rs
use super::FieldElement; use crate::{AffinePoint, FieldBytes, NistP384, ProjectivePoint, Scalar}; use elliptic_curve::{ bigint::{ArrayEncoding, U384}, consts::U72, generic_array::GenericArray, hash2curve::{FromOkm, GroupDigest, MapToCurve, OsswuMap, OsswuMapParams, Sgn0}, ops::Reduce, point::Dec...
const DST: &[u8] = b"QUUX-V01-CS02-with-P384_XMD:SHA-384_SSWU_RO_"; const TEST_VECTORS: &[TestVector] = &[ TestVector { msg: b"", p_x: hex!("eb9fe1b4f4e14e7140803c1d99d0a93cd823d2b024040f9c067a8eca1f5a2eeac9ad604973527a356f3fa3aeff0e4d83"), p...
q1_x: [u8; 48], q1_y: [u8; 48], }
random_line_split
hash2curve.rs
use super::FieldElement; use crate::{AffinePoint, FieldBytes, NistP384, ProjectivePoint, Scalar}; use elliptic_curve::{ bigint::{ArrayEncoding, U384}, consts::U72, generic_array::GenericArray, hash2curve::{FromOkm, GroupDigest, MapToCurve, OsswuMap, OsswuMapParams, Sgn0}, ops::Reduce, point::Dec...
() { struct TestVector { msg: &'static [u8], p_x: [u8; 48], p_y: [u8; 48], u_0: [u8; 48], u_1: [u8; 48], q0_x: [u8; 48], q0_y: [u8; 48], q1_x: [u8; 48], q1_y: [u8; 48], } const DST: &[u8]...
hash_to_curve
identifier_name
load_config.go
package cli import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "net" "os" "strings" "github.com/ethereum-optimism/optimism/op-node/rollup" ds "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/sync" leveldb "github.com/ipfs/go-ds-leveldb" "github.com/libp2p/go-libp2p/core/crypto" "githu...
(p uint) (uint16, error) { if p == 0 { return 0, nil } if p >= (1 << 16) { return 0, fmt.Errorf("port out of range: %d", p) } if p < 1024 { return 0, fmt.Errorf("port is reserved for system: %d", p) } return uint16(p), nil } // loadScoringParams loads the peer scoring options from the CLI context. func lo...
validatePort
identifier_name
load_config.go
package cli import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "net" "os" "strings" "github.com/ethereum-optimism/optimism/op-node/rollup" ds "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/sync" leveldb "github.com/ipfs/go-ds-leveldb" "github.com/libp2p/go-libp2p/core/crypto" "githu...
// loadScoringParams loads the peer scoring options from the CLI context. func loadScoringParams(conf *p2p.Config, ctx *cli.Context, rollupCfg *rollup.Config) error { scoringLevel := ctx.String(flags.Scoring.Name) // Check old names for backwards compatibility if scoringLevel == "" { scoringLevel = ctx.String(fl...
{ if p == 0 { return 0, nil } if p >= (1 << 16) { return 0, fmt.Errorf("port out of range: %d", p) } if p < 1024 { return 0, fmt.Errorf("port is reserved for system: %d", p) } return uint16(p), nil }
identifier_body
load_config.go
package cli import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "net" "os" "strings" "github.com/ethereum-optimism/optimism/op-node/rollup" ds "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/sync" leveldb "github.com/ipfs/go-ds-leveldb" "github.com/libp2p/go-libp2p/core/crypto" "githu...
var err error conf.AdvertiseTCPPort, err = validatePort(ctx.Uint(flags.AdvertiseTCPPort.Name)) if err != nil { return fmt.Errorf("bad advertised TCP port: %w", err) } conf.AdvertiseUDPPort, err = validatePort(ctx.Uint(flags.AdvertiseUDPPort.Name)) if err != nil { return fmt.Errorf("bad advertised UDP port: ...
{ conf.NoDiscovery = true }
conditional_block
load_config.go
package cli import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "net" "os" "strings" "github.com/ethereum-optimism/optimism/op-node/rollup" ds "github.com/ipfs/go-datastore" "github.com/ipfs/go-datastore/sync" leveldb "github.com/ipfs/go-ds-leveldb" "github.com/libp2p/go-libp2p/core/crypto" "githu...
if scoringLevel == "" { scoringLevel = ctx.String(flags.PeerScoring.Name) } if scoringLevel == "" { scoringLevel = ctx.String(flags.TopicScoring.Name) } if scoringLevel != "" { params, err := p2p.GetScoringParams(scoringLevel, rollupCfg) if err != nil { return err } conf.ScoringParams = params } ...
// loadScoringParams loads the peer scoring options from the CLI context. func loadScoringParams(conf *p2p.Config, ctx *cli.Context, rollupCfg *rollup.Config) error { scoringLevel := ctx.String(flags.Scoring.Name) // Check old names for backwards compatibility
random_line_split
training.py
import errno import os import io import random import logging import json import datetime import re import time from multiprocessing import Pool import fileinput import click import matplotlib # pylint: disable=wrong-import-position matplotlib.use('Agg') import matplotlib.pyplot as plt import genetic from .snake...
# print the json header and start a list of turns game_json.write(json.dumps(game_hdr)) game_json.seek(-1, io.SEEK_CUR) game_json.write(', "turns": [\n') # play the game for _board in game.run(): if game.turn_count > 0: game_json.write(",\n"...
player = game.add_snake(snake) game_log.write("game snake: %s func=%s\n" % (player, snake.move_func.func)) game_hdr["snakes"].append(dict( board_id=player.board_id, func=str(snake.move_func.func), ))
conditional_block
training.py
import errno import os import io import random import logging import json import datetime import re import time from multiprocessing import Pool import fileinput import click import matplotlib # pylint: disable=wrong-import-position matplotlib.use('Agg') import matplotlib.pyplot as plt import genetic from .snake...
height = height, game_count = game_count, game_round = game_round, gen_count = gen_count, snakes = snake_group, )) for result in pool.map(play_game, game_infos): for s...
width = width,
random_line_split
training.py
import errno import os import io import random import logging import json import datetime import re import time from multiprocessing import Pool import fileinput import click import matplotlib # pylint: disable=wrong-import-position matplotlib.use('Agg') import matplotlib.pyplot as plt import genetic from .snake...
def evolve( root_dir=None, width=20, height=20, max_gens=None, n_players=None, # players per game n_games=None, # games per round n_rounds=None, # number of games each player will play ): if not root_dir: now = datetime.datetime.now() root_dir = now.strftime("...
errs = [] turns = [] for line in fileinput.input(training_log_path): m = RE_LOG_WINNER.match(line) if m: winner = m.group('winner') try: w = eval(winner) # pylint: disable=eval-used errs.append(-w['err']) turns.append(w['t...
identifier_body
training.py
import errno import os import io import random import logging import json import datetime import re import time from multiprocessing import Pool import fileinput import click import matplotlib # pylint: disable=wrong-import-position matplotlib.use('Agg') import matplotlib.pyplot as plt import genetic from .snake...
(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise @click.command() @click.option('--root_dir', '-r', default='') @click.option('--width', '-w', default=20) @click.option('--height', '-h', ...
mkdir_p
identifier_name
final.py
import numpy as np import pandas as pd import cv2 as cv import sys import os import imutils from matplotlib import pyplot as plt from tqdm import tqdm import math import random from mpl_toolkits import mplot3d from timeit import default_timer as timer from datetime import timedelta # Funcao Objetivo def unsharp_mask(i...
#cv.imshow("Display window", sharpened) return sharpened def getCount(image,treshold,contrast): f = 131*(contrast + 127)/(127*(131-contrast)) alpha_c = f gamma_c = 127*(1-f) new_image = cv.addWeighted( image, alpha_c, image, 0, gamma_c) #add contrast for image image = unsharp_mask(new_im...
_contrast_mask = np.absolute(image - blurred) < threshold np.copyto(sharpened, image, where=low_contrast_mask)
conditional_block
final.py
import numpy as np import pandas as pd import cv2 as cv import sys import os import imutils from matplotlib import pyplot as plt from tqdm import tqdm import math import random from mpl_toolkits import mplot3d from timeit import default_timer as timer from datetime import timedelta # Funcao Objetivo def unsharp_mask(i...
(melhores, piores, medias): x = [i for i in range(0,len(melhores))] y_melhor = [] y_pior = [] y_media = [] for i in range(len(melhores)): y_melhor.append(f_alpine02(melhores[i])) y_media.append(f_alpine02(medias[i])) y_pior.append(f_alpine02(piores[i])) fig...
plot_evolucao_temporal
identifier_name
final.py
import numpy as np import pandas as pd import cv2 as cv import sys import os import imutils from matplotlib import pyplot as plt from tqdm import tqdm import math import random from mpl_toolkits import mplot3d from timeit import default_timer as timer from datetime import timedelta # Funcao Objetivo def unsharp_mask(i...
image_res ,image_thresh = cv.threshold(image_blur_gray,treshold,255,cv.THRESH_BINARY_INV) #get threshold image kernel = np.ones((3,3),np.uint8) opening = cv.morphologyEx(image_thresh,cv.MORPH_OPEN,kernel) dist_transform = cv.distanceTransform(opening,cv.DIST_L2,5) _, last_image = cv.threshold(d...
new_image = cv.addWeighted( image, alpha_c, image, 0, gamma_c) #add contrast for image image = unsharp_mask(new_image) image_blur_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
random_line_split
final.py
import numpy as np import pandas as pd import cv2 as cv import sys import os import imutils from matplotlib import pyplot as plt from tqdm import tqdm import math import random from mpl_toolkits import mplot3d from timeit import default_timer as timer from datetime import timedelta # Funcao Objetivo def unsharp_mask(i...
def crossover(P1, P2, tx_crossover): C1 = P1 C2 = P2 alpha = np.random.random() rand_c = np.random.random() rand_t = np.random.random() if tx_crossover > rand_c: #a t = int(alpha*P1[0] + (1 - alpha)*P2[0]) s = int(alpha*P2[0] + (1 - alpha)*P1[0]) if (...
individuo_mutado = [] # como a taxa de mutacao eh entre 0 e 1, temos: rand_treshrold = np.random.random() if rand_treshrold < tx_mutacao: individuo_mutado.append(np.random.randint(0, 255)) else: individuo_mutado.append(individuo[0]) rand_contrast = np.random.random() if rand...
identifier_body
SCRIPTER.js
var SCRIPTER = function () { var my = {}; var scriptAbort; // used to abort a script from a subscript var inputNoun = null; var debugMes = function (mes) { //println("@@"+mes+"@@"); }; SCRIPTCOMMANDS = { MoveToRoomX : function(room) { debugMes("MoveToRoomX("+room+")"); ...
return false; }, AssertObjectXIsInCurrentRoom : function(obj) { debugMes("AssertObjectXIsInCurrentRoom("+obj+")"); var o = OBJS.getTopObjectByName(obj); if(o.location === GAME.currentRoom) { return true; } return false; }, AssertObjectXIsInCurrentRoomOrPack : function(o...
{ return true; }
conditional_block
SCRIPTER.js
var SCRIPTER = function () { var my = {}; var scriptAbort; // used to abort a script from a subscript var inputNoun = null; var debugMes = function (mes) { //println("@@"+mes+"@@"); }; SCRIPTCOMMANDS = { MoveToRoomX : function(room) { debugMes("MoveToRoomX("+room+")"); ...
var objX = OBJS.getExactObjectByName(x); objX.location = GAME.currentRoom; println("OK"); return true; }, PrintScore : function () { debugMes("PrintScore()"); var score = 0; var obs = OBJS.getAllObjects(); for(var x=0;x<obs.length;++x) { var ob = obs[x]; ...
debugMes("MoveObjectXToCurrentRoom("+x+")");
random_line_split
my_finance_module.py
import urllib.request , time , re import pandas as pd import numpy , xgboost ,os from sklearn.model_selection import (StratifiedKFold,cross_val_score,cross_val_predict) from sklearn.metrics import (mean_squared_error,confusion_matrix) import matplotlib.pyplot as plt from matplotlib import dates from matplotlib.ticke...
t=time.localtime() mass.update({"time":str(t.tm_mday)+"-"+str(t.tm_mon)+"-"+str(t.tm_year)+" "+str(t.tm_hour)+":"+str(t.tm_min)+":"+str(t.tm_sec)}) return mass #################################################### def preprocess_mass(strings,t,init_point): Mass_DF={} for str1 in strings: # M...
tzset()
identifier_name
my_finance_module.py
import urllib.request , time , re import pandas as pd import numpy , xgboost ,os from sklearn.model_selection import (StratifiedKFold,cross_val_score,cross_val_predict) from sklearn.metrics import (mean_squared_error,confusion_matrix) import matplotlib.pyplot as plt from matplotlib import dates from matplotlib.ticke...
rice'] - Mass_df[str1]['Prev Close'] ) / Mass_df[str1]['Prev Close'] *100 PC = Mass_df[str1]['Prev Close'][1] # print(Mass_df[str1].columns) X = Mass_df[str1][['hour','minute','sec']][n-1:].values #преобразовали тип dataFrame в тип array Numpy # скользящая средняя rolling_mean = Mass_df[str1][...
'] = time_interval['hour'].astype('str') + ":" + time_interval['minute'].astype('str') + ":" + \ time_interval['sec'].astype('str') fmt = dates.DateFormatter("%H:%M:%S") time_interval1 = [dt.datetime.strptime(i, "%H:%M:%S") for i in time_interval['date']] # оцениваем качество пр...
identifier_body
my_finance_module.py
import urllib.request , time , re import pandas as pd import numpy , xgboost ,os from sklearn.model_selection import (StratifiedKFold,cross_val_score,cross_val_predict) from sklearn.metrics import (mean_squared_error,confusion_matrix) import matplotlib.pyplot as plt from matplotlib import dates from matplotlib.ticke...
time_interval['sec'].astype('str') fmt = dates.DateFormatter("%H:%M:%S") time_interval1 = [dt.datetime.strptime(i, "%H:%M:%S") for i in time_interval['date']] # оцениваем качество предсказаний accuracy = my_mean_sqeared_error(Y[-(test_col):] , y_pred1[-(test_col):] ) acc...
time_interval['date'] = time_interval['hour'].astype('str') + ":" + time_interval['minute'].astype('str') + ":" + \
random_line_split
my_finance_module.py
import urllib.request , time , re import pandas as pd import numpy , xgboost ,os from sklearn.model_selection import (StratifiedKFold,cross_val_score,cross_val_predict) from sklearn.metrics import (mean_squared_error,confusion_matrix) import matplotlib.pyplot as plt from matplotlib import dates from matplotlib.ticke...
у вероятность if abs(ma) > abs(av_Y): P = Gauss_probability(0.1,abs(ma),accuracy,mde) else: P = Gauss_probability(abs(1-abs(ma/av_Y)),abs(ma),accuracy,mde) #выводим на экран данные print(str1 +": procent %.3f%% of price in %d:%d:%d, probability: %.3f%% " % (last_price,time_interval[-3:-2]...
t(facecolor='white', alpha=0.7), transform=ax.transAxes, fontsize=12) ax.plot(time_interval1, y_pred, 'r-', label="predict", linewidth=2) ax.plot(time_interval1[:-point_pred], Y[-(test_col + train_point_print):], 'bo--', label="averaged sample", linewidth=1) # ax.plot(time_interval1[:-point_pred], Y[-...
conditional_block
ante.go
package auth import ( "bytes" "encoding/hex" "fmt" "os" "strings" "time" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/orientwalt/htdf/codec" txparam "github.com/orientwalt/htdf/params" sdk "git...
(tx StdTx) StdFee { return NewStdFee(txparam.DefaultMsgGas*uint64(len(tx.Msgs)), tx.Fee.GasPrice) } // NewAnteHandler returns an AnteHandler that checks and increments sequence // numbers, checks signatures & account numbers, and deducts fees from the first // signer. func NewAnteHandler(ak AccountKeeper, fck FeeColl...
EstimateFee
identifier_name
ante.go
package auth import ( "bytes" "encoding/hex" "fmt" "os" "strings" "time" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/orientwalt/htdf/codec" txparam "github.com/orientwalt/htdf/params" sdk "git...
if res := ValidateMemo(stdTx, params); !res.IsOK() { return newCtx, res, true } // stdSigs contains the sequence number, account number, and signatures. // When simulating, this would just be a 0-length slice. signerAddrs := stdTx.GetSigners() signerAccs := make([]Account, len(signerAddrs)) isGenesi...
{ newCtx.GasMeter().UseGas(sdk.Gas(txparam.DefaultMsgGas*uint64(len(stdTx.Msgs))), "AnteHandler") }
conditional_block
ante.go
package auth import ( "bytes" "encoding/hex" "fmt" "os" "strings" "time" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/orientwalt/htdf/codec" txparam "github.com/orientwalt/htdf/params" sdk "git...
params := ak.GetParams(ctx) // Ensure that the provided fees meet a minimum threshold for the validator, // if this is a CheckTx. This is only for local mempool purposes, and thus // is only ran on check tx. // junying-todo, 2019-11-07 // Check if Fee.Amount > Fee.Gas * minGasPrice or not // It can be r...
}
random_line_split
ante.go
package auth import ( "bytes" "encoding/hex" "fmt" "os" "strings" "time" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/orientwalt/htdf/codec" txparam "github.com/orientwalt/htdf/params" sdk "git...
// consumeSigVerificationGas consumes gas for signature verification based upon // the public key type. The cost is fetched from the given params and is matched // by the concrete type. // // TODO: Design a cleaner and flexible way to match concrete public key types. func consumeSigVerificationGas( meter sdk.GasMete...
{ // If pubkey is not known for account, set it from the StdSignature. pubKey := acc.GetPubKey() if simulate { // In simulate mode the transaction comes with no signatures, thus if the // account's pubkey is nil, both signature verification and gasKVStore.Set() // shall consume the largest amount, i.e. it take...
identifier_body
main.py
import logging import time import json from urllib.parse import urljoin from bs4 import BeautifulSoup as bs from selenium.common.exceptions import StaleElementReferenceException import pandas as pd from definitions import STATES, SCROLL_PAUSE_TIME from collectors import SeleniumCollector from collectors.errors import...
(self, exc_type, exc_val, exc_tb): super(MyLife, self).__exit__(exc_type, exc_val, exc_tb) def get_data(self): """ Takes self.url (for a general MyLife search), scrapes the site data, and adds it to the self.data_from_website DataFrame. MyLife keeps its full data set on...
__exit__
identifier_name
main.py
import logging import time import json from urllib.parse import urljoin from bs4 import BeautifulSoup as bs from selenium.common.exceptions import StaleElementReferenceException import pandas as pd from definitions import STATES, SCROLL_PAUSE_TIME from collectors import SeleniumCollector from collectors.errors import...
personal_details = [_ for _ in personal_details if len(_) == 2] personal_details = {detail.lower().replace(' ', '_'): value for detail, value in personal_details if value != 'Add Info'} birth_date = personal_details.pop('date_of_birth') if...
personal_details = personal_details.find_all(class_='item-container') personal_details = [detail.text.split(': ') for detail in personal_details]
random_line_split
main.py
import logging import time import json from urllib.parse import urljoin from bs4 import BeautifulSoup as bs from selenium.common.exceptions import StaleElementReferenceException import pandas as pd from definitions import STATES, SCROLL_PAUSE_TIME from collectors import SeleniumCollector from collectors.errors import...
def _gather_deep_data(self): """ Gathers the data that is deeper within the website by calling self._deep_data(url) for each record found during the general search in self.get_data() """ cleaned_data_from_website = list() for i, search_result in self.data_from...
""" Takes a URL for a specific MyLife record, scrapes the JSON data and returns a dictionary. :param url: url for which a deeper set of data is to be gathered. :return: """ def _nested_persons(persons): _persons = list() for person_ in persons: ...
identifier_body
main.py
import logging import time import json from urllib.parse import urljoin from bs4 import BeautifulSoup as bs from selenium.common.exceptions import StaleElementReferenceException import pandas as pd from definitions import STATES, SCROLL_PAUSE_TIME from collectors import SeleniumCollector from collectors.errors import...
if len(owns) > 0: profile_data['owns'] = owns profile_data['relatedTo'] = _nested_persons(soup.find_all(class_='relative-container')) profile_data['neighbors'] = _nested_persons(soup.find_all(class_='neighbor-container')) # Photos profile_data['pictures'] ...
automobile = [detail.text.split(': ') for detail in automobile.find_all(class_='item-container')] automobile = {detail.lower().replace(' ', '_'): value for detail, value in automobile if value != 'Add Info'} if len(automobile) == 0: cont...
conditional_block
mod.rs
pub mod context; pub mod types; ///////////////////// Validation Helpers ///////////////////// use std::collections::HashMap; use crate::frontend::validate::types::Type; use crate::frontend::parse::ast; ///////////////////// TYPES ///////////////////// // NOTE: Offsets are i32 for Cranelift /// Stores struct defin...
// e.g.: `let x: u32 = y.a;` // FieldAlias(), } pub struct AllocationTable { // Map of ((function_name, variable name) -> variable's usage) pub allocations: HashMap<(String, String), MemoryUsage>, } impl AllocationTable { pub fn new() -> Self { Self { allocations: HashMap::new(...
// TODO: References an existing variable -> ?? // e.g.: `let x: &u32 = &y;` // Borrow(&'input str), // TODO: Aliases a field of an existing variable -> ??
random_line_split
mod.rs
pub mod context; pub mod types; ///////////////////// Validation Helpers ///////////////////// use std::collections::HashMap; use crate::frontend::validate::types::Type; use crate::frontend::parse::ast; ///////////////////// TYPES ///////////////////// // NOTE: Offsets are i32 for Cranelift /// Stores struct defin...
(&mut self, name: &str) -> Result<&mut VariableData, String> { if let Some(&index) = self.all_variables.get(name) { return Ok(self.scopes[index].get_var_data_mut(name)); } Err(format!("No variable `{}` in scope", name)) } // NOTE: Program is valid at this point. No safety c...
get_variable_mut
identifier_name
mod.rs
pub mod context; pub mod types; ///////////////////// Validation Helpers ///////////////////// use std::collections::HashMap; use crate::frontend::validate::types::Type; use crate::frontend::parse::ast; ///////////////////// TYPES ///////////////////// // NOTE: Offsets are i32 for Cranelift /// Stores struct defin...
else { Err(format!("Type `{}` is not valid", t)) } } } } /// Returns alignment of the type in bytes fn alignment_of(&self, t: &Type) -> usize { match t { // TODO: Alignment should be same as pointer type Type::Referenc...
{ Ok(()) }
conditional_block
rtppacket.go
package rtp import "errors" /** Represents an RTP RTPPacket. * The RTPPacket class can be used to parse a RTPRawPacket instance if it represents RTP data. * The class can also be used to create a new RTP packet according to the parameters specified by * the user. */ type RTPPacket struct { receivetime *RTPTim...
() *RTPTime { return this.receivetime } /** Returns a pointer to the data of the entire packet. */ func (this *RTPPacket) GetPacket() []byte { return this.packet } func (this *RTPPacket) Dump() { /*int i; printf("Payload type: %d\n",(int)GetPayloadType()); printf("Extended sequence number: 0x%...
GetReceiveTime
identifier_name
rtppacket.go
package rtp import "errors" /** Represents an RTP RTPPacket. * The RTPPacket class can be used to parse a RTPRawPacket instance if it represents RTP data. * The class can also be used to create a new RTP packet according to the parameters specified by * the user. */ type RTPPacket struct { receivetime *RTPTim...
// We'll check if this is possibly a RTCP packet. For this to be possible // the marker bit and payload type combined should be either an SR or RR // identifier if this.header.marker != 0 { if this.header.payloadtype == (RTP_RTCPTYPE_SR & 127) { // don't check high bit (this was the marker!!) return errors.N...
{ return errors.New("ERR_RTP_PACKET_INVALIDPACKET") }
conditional_block
rtppacket.go
package rtp import "errors" /** Represents an RTP RTPPacket. * The RTPPacket class can be used to parse a RTPRawPacket instance if it represents RTP data. * The class can also be used to create a new RTP packet according to the parameters specified by * the user. */ type RTPPacket struct { receivetime *RTPTim...
} else { numpadbytes = 0 } payloadlength = len(this.packet) - numpadbytes - payloadoffset if payloadlength < 0 { return errors.New("ERR_RTP_PACKET_INVALIDPACKET") } return nil } /** Creates a new buffer for an RTP packet and fills in the fields according to the specified parameters. * If \c maxpacksize i...
if numpadbytes > len(this.packet)-payloadoffset { return errors.New("ERR_RTP_PACKET_INVALIDPACKET") }
random_line_split
rtppacket.go
package rtp import "errors" /** Represents an RTP RTPPacket. * The RTPPacket class can be used to parse a RTPRawPacket instance if it represents RTP data. * The class can also be used to create a new RTP packet according to the parameters specified by * the user. */ type RTPPacket struct { receivetime *RTPTim...
/** Sets the extended sequence number of this packet to \c seq. */ // func (this *RTPPacket) SetExtendedSequenceNumber(seq uint32) { // this.extseqnr = seq // } /** Returns the timestamp of this packet. */ func (this *RTPPacket) GetTimestamp() uint32 { return this.header.timestamp } /** Returns the SSRC identifie...
{ return this.header.sequencenumber //uint16(this.extseqnr & 0x0000FFFF) }
identifier_body
pxer.js
// +---------------------------------------------------------------------- // | Pxer核心行为文件 // +---------------------------------------------------------------------- // | Copyright (c) 2006-2015 http://nutjs.co All rights reserved. // +---------------------------------------------------------------------- // | Author: ...
w Pxer(); myPxer.initialize(); nutjs.addEve(myPxer.px.bn_run,'click',function(){ if(myPxer.just_get()){ nutjs.ll("将采用获取单图方式"); return; }else if(myPxer.read()){//可以批量get nutjs.ll("将采用批量获取方式"); myPxer.px.pxer_showState.style.display="block"; }else{ nutjs.le("Pxer不知道该怎么做"); }; }); if(bn === true...
myPxer=ne
identifier_name
pxer.js
// +---------------------------------------------------------------------- // | Pxer核心行为文件 // +---------------------------------------------------------------------- // | Copyright (c) 2006-2015 http://nutjs.co All rights reserved. // +---------------------------------------------------------------------- // | Author: ...
multiple/.test(arr[2])){ obj.type="ids"; }else if(/manga/.test(arr[2])){ obj.type="sids"; }else if(/^\s*work\s*_work\s*$/.test(arr[2])){ obj.type="pic"; }else{ nutjs.le("函数getWorkqueue无法判断作品类型!class【"+arr[2]+"】,href【"+arr[1]+"】"); continue; } this.queue.push(obj); }; }; /*--- PxGet --- 获取单个页面的...
mp_arr=html.match(reg); for(var i=0;i<temp_arr.length;i++){ var obj=new Object(); var arr=reg.exec(temp_arr[i]); if(! /^\//.test(arr[1]))arr[1]="/"+arr[1]; obj.url="http://www.pixiv.net"+arr[1]; reg.lastIndex=0;//因为启用全局调用了exec if(/ugoku\-illust/.test(arr[2])){ obj.type="zip"; }else if(/
identifier_body
pxer.js
// +---------------------------------------------------------------------- // | Pxer核心行为文件 // +---------------------------------------------------------------------- // | Copyright (c) 2006-2015 http://nutjs.co All rights reserved. // +---------------------------------------------------------------------- // | Author: ...
[^\{\}<>]*?)"[^<>]*class[^<>]*original-image/mi; try{ this.address=reg.exec(this.workHtml)[1]; }catch(e){ ePxer.push(this); nutjs.le("函数get_address_from_workHtml,未知的workHtml!回滚操作,并添加当前PxGet对象 $ePxer["+(ePxer.length-1)+"]"); this.workHtml=null; }; }; /*ids专用*/ PxGet.prototype. get_workId_from_workHtml=functio...
ion(){ var reg=/<img[^<>]*data-src[^"]"(
conditional_block
pxer.js
// +---------------------------------------------------------------------- // | Pxer核心行为文件 // +---------------------------------------------------------------------- // | Copyright (c) 2006-2015 http://nutjs.co All rights reserved. // +---------------------------------------------------------------------- // | Author: ...
this.thread=this.px.config_thread.value; this.maxThread = +(this.queue.length>this.thread?this.thread:this.queue.length); //显示效果 this.px.show_wait.innerHTML=this.wait; this.px.show_thread.innerHTML=this.maxThread; /*显示结果*/ this.queue_show_update(); return true; } }; return false; }; Pxer.pro...
this.queue.push(document.URL+"&p="+(i+1)); }; /*初始化线程数,不允许线程超过页数*/
random_line_split
value.rs
// Copyright 2019 The Starlark in Rust Authors // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
} } fn get_hash(&self) -> Result<u64, ValueError> { Ok(self .content .iter() .map(|v| v.precomputed_hash) .map(Wrapping) .fold(Wrapping(0_u64), |acc, v| acc + v) .0) } not_supported!(mul, set_at); not_supported...
} else { Err(ValueError::IncorrectParameterType)
random_line_split
value.rs
// Copyright 2019 The Starlark in Rust Authors // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
else { let mut v = v.clone(); v.downcast_apply_mut(|x: &mut Set| -> ValueResult { x.mutability.test()?; f(&mut x.content) }) } } pub fn compare<Return>( v1: &Value, v2: &Value, f: &Fn( &LinkedHashSe...
{ Err(ValueError::IncorrectParameterType) }
conditional_block
value.rs
// Copyright 2019 The Starlark in Rust Authors // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
fn is_descendant(&self, other: &TypedValue) -> bool { self.content .iter() .any(|x| x.value.same_as(other) || x.value.is_descendant(other)) } fn slice( &self, start: Option<Value>, stop: Option<Value>, stride: Option<Value>, ) -> ValueRe...
{ Ok(Value::new( self.content.contains(&ValueWrapper::new(other.clone())?), )) }
identifier_body
value.rs
// Copyright 2019 The Starlark in Rust Authors // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
() -> Self { Set { mutability: IterableMutability::Mutable, content: LinkedHashSet::new(), } } } impl Set { pub fn empty() -> Value { Value::new(Set::default()) } pub fn from<V: Into<Value>>(values: Vec<V>) -> Result<Value, ValueError> { let mut ...
default
identifier_name
dsp.py
from scipy.ndimage.filters import gaussian_filter1d from numpy import abs, arange, linspace, zeros from math import log import numpy as np class DSP(): def __init__(self, config, device_config=None): self._config = config self._device_config = device_config # Initialise filters etc. I've ...
self.fft_plot_filter = ExpFilter(np.tile(1e-1, n_fft_bins), alpha_decay=0.5, alpha_rise=0.99) self.mel_gain = ExpFilter(np.tile(1e-1, n_fft_bins), alpha_decay=0.01, alpha_rise=0.99) self.mel_smoothing = ExpFilter(np.tile(1e-1, n_fft_bins), alpha_decay=0.5, alpha_rise=0.99) self.gain = ...
led_count = self._device_config["led_count"]
conditional_block
dsp.py
from scipy.ndimage.filters import gaussian_filter1d from numpy import abs, arange, linspace, zeros from math import log import numpy as np class DSP(): def __init__(self, config, device_config=None): self._config = config self._device_config = device_config # Initialise filters etc. I've ...
(self, num_bands, freq_min, freq_max, num_fft_bands): """ Returns centerfrequencies and band edges for a mel filter bank Parameters ---------- num_bands : int Number of mel bands. freq_min : scalar Minimum frequency for the first band. freq...
melfrequencies_mel_filterbank
identifier_name
dsp.py
from scipy.ndimage.filters import gaussian_filter1d from numpy import abs, arange, linspace, zeros from math import log import numpy as np class DSP(): def __init__(self, config, device_config=None):
def update(self, audio_samples): """ Return processed audio data. Returns mel curve, x/y data. This method is called every time there is a microphone update. Returns: ------- audio_data: dict Dict containing "mel", "vol", "x", and "y". ""...
self._config = config self._device_config = device_config # Initialise filters etc. I've no idea what most of these are for but I imagine I won't be getting rid of them soon. n_fft_bins = self._config["general_settings"]["n_fft_bins"] min_volume_threshold = self._config["general_setting...
identifier_body
dsp.py
from scipy.ndimage.filters import gaussian_filter1d from numpy import abs, arange, linspace, zeros from math import log import numpy as np class DSP(): def __init__(self, config, device_config=None): self._config = config self._device_config = device_config # Initialise filters etc. I've ...
An example is shown in the following figure: .. plot:: from pylab import plt import melbank f1, f2 = 1000, 8000 melmat, (melfreq, fftfreq) = melbank.compute_melmat(6, f1, f2, num_fft_bands=4097) fig, ax = plt.subplots(figsize=(8, 3)) ax.plot(fftfreq, melmat.T) ...
"""This class implements a Mel Filter Bank. In other words it is a filter bank with triangular shaped bands arranged on the mel frequency scale.
random_line_split
taskGraph.py
import warnings import copy import traceback import cloudpickle import base64 from types import ModuleType from collections import OrderedDict import ruamel.yaml from ._node_flow import _CLEANUP from .task import Task from .taskSpecSchema import TaskSpecSchema from .portsSpecSchema import PortsSpecSchema from .util im...
'desired profile option then call run.', RuntimeWarning) # Reset visited status to run the taskgraph. This is done during # build, but since not building need to reset here. for inode in self.__node_dict.values(): inode.visited...
random_line_split
taskGraph.py
import warnings import copy import traceback import cloudpickle import base64 from types import ModuleType from collections import OrderedDict import ruamel.yaml from ._node_flow import _CLEANUP from .task import Task from .taskSpecSchema import TaskSpecSchema from .portsSpecSchema import PortsSpecSchema from .util im...
(object): def __init__(self, values): self.values = tuple([i[1] for i in values]) self.__keys = tuple([i[0] for i in values]) self.__dict = OrderedDict(values) def __iter__(self): return iter(self.values) def __getitem__(self, key): if isinstance(key, int): ...
Results
identifier_name
taskGraph.py
import warnings import copy import traceback import cloudpickle import base64 from types import ModuleType from collections import OrderedDict import ruamel.yaml from ._node_flow import _CLEANUP from .task import Task from .taskSpecSchema import TaskSpecSchema from .portsSpecSchema import PortsSpecSchema from .util im...
def start_labwidget(self): from IPython.display import display display(self.draw()) @staticmethod def register_lab_node(module_name, class_obj): """ Register the node class for the Greenflowlab. It put the class_obj into a sys.modules with `module_name`. It will re...
inode = node_in['from_node'] self.__find_roots(inode, inputs, consider_load)
conditional_block
taskGraph.py
import warnings import copy import traceback import cloudpickle import base64 from types import ModuleType from collections import OrderedDict import ruamel.yaml from ._node_flow import _CLEANUP from .task import Task from .taskSpecSchema import TaskSpecSchema from .portsSpecSchema import PortsSpecSchema from .util im...
def __len__(self): return len(self.__task_list) def __iter__(self): self.__index = 0 self.__tlist = list(self.__task_list.values()) return self def __next__(self): idx = self.__index if idx is None or idx == len(self.__tlist): self.__index = No...
return True if task_id in self.__task_list else False
identifier_body
1.cifar10_classification_lightmodel.py
# -*- coding: utf-8 -*- """ Last amended: 17th June, 2019 a. Myfolder: C:\Users\ashokharnal\OneDrive\Documents\deep_learning\cifar10 image classification b. Ref: https://cambridgespark.com/content/tutorials/convolutional-neural-networks-with-keras/index.html https://nextjournal.com/mpd/image-classific...
# exp(xi)/Sigma(exp(xk)) """ Softmax If we take an input of [1, 2, 3, 4, 1, 2, 3], the softmax of that is [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175]. The output has most of its weight where the '4' was in the original input. This is what the function is normally used for: to highlight...
# 7.2.2 Final output layer; softmax # About softmax: https://en.wikipedia.org/wiki/Softmax_function
random_line_split
1.cifar10_classification_lightmodel.py
# -*- coding: utf-8 -*- """ Last amended: 17th June, 2019 a. Myfolder: C:\Users\ashokharnal\OneDrive\Documents\deep_learning\cifar10 image classification b. Ref: https://cambridgespark.com/content/tutorials/convolutional-neural-networks-with-keras/index.html https://nextjournal.com/mpd/image-classific...
(): val_acc = history.history['val_acc'] tr_acc=history.history['acc'] epochs = range(1, len(val_acc) +1) plt.plot(epochs,val_acc, 'b', label = "Validation accu") plt.plot(epochs, tr_acc, 'r', label = "Training accu") plt.title("Training and validation accuracy") plt.legend() plt...
plot_history
identifier_name
1.cifar10_classification_lightmodel.py
# -*- coding: utf-8 -*- """ Last amended: 17th June, 2019 a. Myfolder: C:\Users\ashokharnal\OneDrive\Documents\deep_learning\cifar10 image classification b. Ref: https://cambridgespark.com/content/tutorials/convolutional-neural-networks-with-keras/index.html https://nextjournal.com/mpd/image-classific...
# 8.5 plot_history() # 9. Evaluate the trained model on the test set! # Returns the loss value & metrics values for # the model in test mode. model.evaluate(X_test, Y_test, verbose=1) # Accuracy is just 10% # 10.0 Make predictions # Generates output predictions for the input sampl...
val_acc = history.history['val_acc'] tr_acc=history.history['acc'] epochs = range(1, len(val_acc) +1) plt.plot(epochs,val_acc, 'b', label = "Validation accu") plt.plot(epochs, tr_acc, 'r', label = "Training accu") plt.title("Training and validation accuracy") plt.legend() plt.show()
identifier_body
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains Maya DCC plugin specific implementation """ from __future__ import print_function, division, absolute_import import os import json import logging import maya.cmds as cmds import maya.mel as mel import artella from artella import dcc from artel...
# This can happen when local root path cannot be retrieved from Artella Drive if isinstance(artella_local_root_path, dict): return artella_local_root_path = utils.clean_path(artella_local_root_path) if utils.is_python2(): artella_local_root_path = artella_local...
logger.warning('No Project Path to setup. Skipping setup project ...') return
conditional_block
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains Maya DCC plugin specific implementation """ from __future__ import print_function, division, absolute_import import os import json import logging import maya.cmds as cmds import maya.mel as mel import artella from artella import dcc from artel...
def __init__(self, artella_drive_client): super(ArtellaMayaPlugin, self).__init__(artella_drive_client=artella_drive_client) self._references_found = list() def get_version(self, force_update=False): """ Returns current DCC plugin version :param bool force_update: Where or...
identifier_body
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains Maya DCC plugin specific implementation """ from __future__ import print_function, division, absolute_import import os import json import logging import maya.cmds as cmds import maya.mel as mel import artella from artella import dcc from artel...
:param bool create_callbacks: Whether or not DCC callbacks should be created :return: True if the initialization was successful; False otherwise. :rtype: bool """ # Force Maya MEL stack trace on before we start using the plugin maya_utils.force_mel_stack_trace_on() ...
:param bool show_dialogs: Whether dialogs should appear during plugin initialization or not :param bool create_menu: Whether menu should be created or not
random_line_split
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains Maya DCC plugin specific implementation """ from __future__ import print_function, division, absolute_import import os import json import logging import maya.cmds as cmds import maya.mel as mel import artella from artella import dcc from artel...
(self, *args): """ Internal callback function that is called after a Maya reference is loaded :param args: """ if not self.is_artella_path(): return self.validate_environment_for_callback('AfterLoadReference') def _before_reference_check(self, maya_fil...
_after_load_reference
identifier_name
model.py
import torch from torch import nn from torch.nn import functional as F import functools import math from torch.nn.utils import spectral_norm class AdaptiveBatchNorm(nn.BatchNorm2d): """ Adaptive batch normalization layer (4 points) Args: num_features: number of features in batch normalization laye...
def forward(self, noise, labels): # TODO if self.use_class_condition: noise = torch.cat((self.embed(labels), noise), dim=-1) outputs = self.sp_norm_lin(noise).view(-1, self.max_channels, 4, 4) outputs = self.parb1(outputs, noise) outputs = self.parb2(outputs...
super(Generator, self).__init__() self.output_size = 4 * 2**num_blocks # TODO self.max_channels = max_channels self.use_class_condition = use_class_condition self.embed = torch.nn.Embedding(num_classes, noise_channels) if self.use_class_condition: noise_chan...
identifier_body
model.py
import torch from torch import nn from torch.nn import functional as F import functools import math from torch.nn.utils import spectral_norm class AdaptiveBatchNorm(nn.BatchNorm2d): """ Adaptive batch normalization layer (4 points) Args: num_features: number of features in batch normalization laye...
return outputs class Generator(nn.Module): """ Generator network (8 points) TODO: - Implement an option to condition the synthesis on trainable class embeddings (use nn.Embedding module with noise_channels as the size of each embed) - Concatenate input noise with class ...
outputs = self.down(outputs)
conditional_block
model.py
import torch from torch import nn from torch.nn import functional as F import functools import math from torch.nn.utils import spectral_norm class AdaptiveBatchNorm(nn.BatchNorm2d): """ Adaptive batch normalization layer (4 points) Args: num_features: number of features in batch normalization laye...
(self, in_channels: int, out_channels: int, embed_channels: int = None, batchnorm: bool = False, upsample: bool = False, downsample: bool = False): super(PreActResBlock, self).__init__() # TODO: define ...
__init__
identifier_name
model.py
import torch from torch import nn from torch.nn import functional as F import functools import math from torch.nn.utils import spectral_norm class AdaptiveBatchNorm(nn.BatchNorm2d): """ Adaptive batch normalization layer (4 points) Args: num_features: number of features in batch normalization laye...
TODO: - Define a convolutional part of the discriminator similarly to the generator blocks, but in the inverse order, with downsampling, and without batch normalization - At the end of the convolutional part apply ReLU and sum pooling TODO: implement projection discrim...
""" Discriminator network (8 points)
random_line_split
simpleLSTM.py
# -*- coding: utf-8 -*- from collections import OrderedDict import numpy import theano import theano.tensor as T import time import sys import matplotlib.pyplot as plt SEED = 123 numpy.random.seed(SEED) def numpy_floatX(data): return numpy.asarray(data, dtype=theano.config.floatX) def _p(pp, name): return '...
preact = T.dot(h_, tparams[_p(prefix, 'U')]) # (4*dim) preact += x_ # h 延时后加权的目标维数 和 Wx+b的维数相同,都是LSTM单元的个数的4倍,可以直接相加 i = T.nnet.sigmoid(_slice(preact, 0, dim_proj)) # input gate f = T.nnet.sigmoid(_slice(preact, 1, dim_proj)) # forget gate o = T.nnet.sigm...
c_ : 前一时刻单元的Cell值 '''
conditional_block
simpleLSTM.py
# -*- coding: utf-8 -*- from collections import OrderedDict import numpy import theano import theano.tensor as T import time import sys import matplotlib.pyplot as plt SEED = 123 numpy.random.seed(SEED) def numpy_floatX(data): return numpy.asarray(data, dtype=theano.config.floatX) def _p(pp, name): return '...
proj = lstm_layer(tparams, x, options, prefix=options['encoder']) proj = theano.tensor.reshape(proj, (proj.shape[0], proj.shape[2])) # pred = T.tanh(T.dot(proj, tparams['U']) + tparams['b']) pred = T.dot(proj, tparams['U']) + tparams['b'] f_pred_prob...
random_line_split