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
ACPF_ExportMuRaster.py
] + "*" currentWS = env.workspace env.workspace = logFolder logList = arcpy.ListFiles(logFile) for lg in logList: arcpy.Delete_management(lg) env.workspace = currentWS return True except: errorMsg() False ## =======...
if arcpy.Exists(outputRaster): time.sleep(1)
random_line_split
get_sheet.py
3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])''' ) #一整个 #return d2_1, d2_2, d2_3, d3 #df, df_woe, use_lst, cal_iv, type_train,cal_psi ,lr def get_2_1_imp(self, df): d1 = DataFrame(index=self.use_lst) cover_dic = dict(df[use_lst].notnull().sum()) d1['...
.use_lst).reset_index() d2_3.index = range(1, d2_3.shape[0]+1) return d2_3 #df_bin, use_lst, #type_lst#, type_train, woe_dic def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']): res = [] for loc, i in enumerate(type_lst): lst = [] df_tmp = self...
df_data_des = df_data_des.reset_index() df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(cover_dic[x]/df.shape[0], 4)) df_data_des.index = df_data_des['index'] df_data_des.drop(columns=['index', 'count'], inplace=True) d2_2 = df_data_des.reset_index() d2_2....
identifier_body
get_sheet.py
= self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])''' ) #一整个 #return d2_1, d2_2, d2_3, d3 #df, df_woe, use_lst, cal_iv, type_train,cal_psi ,lr def get_2_1_imp(self, df): d1 = DataFrame(index=self.use_lst) cover_dic = dict(df[use_lst].notnull().sum()) d1['a...
]].fillna(0) #添加几行用来画画 # #n = len(Counter(df_tmp[cate])) #length = df.shape[0]//n #for i in range(n): # #df[:length] #print(df) # df.index = range(1, df.shape[0]+1) return df def ks_calc_cross(self,data,pred,y_label): ...
, 'count', 'bad_rate', 'ks'
conditional_block
get_sheet.py
e_lst = use_lst self.woe_dic = woe_dic self.type_train = type_train self.model = lr self.y = y def main(self): print('d2_1 = self.get_2_1_imp()',#依次放好, 'd2_2 = self.get_2_2_des()', 'd2_3 = self.get_2_3_corr()', '''d3 = self.get_bin_ins_oo...
self.us
identifier_name
get_sheet.py
3 = self.get_bin_ins_oot(type_lst=['ins', 'oot', 'oot2'])''' ) #一整个 #return d2_1, d2_2, d2_3, d3 #df, df_woe, use_lst, cal_iv, type_train,cal_psi ,lr def get_2_1_imp(self, df): d1 = DataFrame(index=self.use_lst) cover_dic = dict(df[use_lst].notnull().sum()) d1['...
split_name = str(type_lst[loc-1])+'<-->'+str(i) d[split_name] = [split_name for i in range(d.shape[0])] d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe' ]] lst.append(d) res.append(lst) return pd.conca...
split_name = '<-->'+str(i) else:
random_line_split
instance_list.py
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 langu...
def _get_marker_instance(ctx, marker): """Get the marker instance from its cell. This returns the marker instance from the cell in which it lives """ try: im = objects.InstanceMapping.get_by_instance_uuid(ctx, marker) except exception.InstanceMappingNotFound: raise exception.Mar...
"""Wrap an instance object from the database so it is sortable. We use heapq.merge() below to do the merge sort of things from the cell databases. That routine assumes it can use regular python operators (> and <) on the contents. Since that won't work with instances from the database (and depends on t...
identifier_body
instance_list.py
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 langu...
return db_inst def get_instances_sorted(ctx, filters, limit, marker, columns_to_join, sort_keys, sort_dirs): """Get a cross-cell list of instances matching filters. This iterates cells in parallel generating a unified and sorted list of instances as efficiently as possible. ...
raise exception.MarkerNotFound(marker=marker)
conditional_block
instance_list.py
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 langu...
(ctx): """Generate InstanceWrapper(Instance) objects from a cell. We do this inside the thread (created by scatter_gather_all_cells()) so that we return wrappers and avoid having to iterate the combined result list in the caller again. This is run against each cell by the scatte...
do_query
identifier_name
instance_list.py
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # 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 lan...
def compare_instances(self, inst1, inst2): """Implements cmp(inst1, inst2) for the first key that is different Adjusts for the requested sort direction by inverting the result as needed. """ for skey, sdir in zip(self._sort_keys, self._sort_dirs): resultflag = 1 ...
random_line_split
youtube.rs
/* [ { title: String, videoId: String, author: String, authorId: String, authorUrl: String, videoThumbnails: [ { quality: String, url: String, width: Int32, height: Int32 } ], description: String, descriptionHtml: String, viewCoun...
{ #[cfg(test)] let prefix: &str = &mockito::server_url(); #[cfg(not(test))] let prefix: &str = "https://invidio.us"; prefix.into() }
identifier_body
youtube.rs
lengthSeconds: Int32 paid: Bool, premium: Bool } ] */ #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] struct YTVideoInfo { title: String, video_id: String, video_thumbnails: Vec<YTThumbnailInfo>, description: String, length_seconds: i32, paid: bool,...
/// Important info about channel #[derive(Debug)] pub struct ChannelMetadata { pub title: String, pub thumbnail: String, pub description: String, } /// Important info about a video pub struct VideoInfo { pub id: String, pub url: String, pub title: String, pub description: String, pub th...
random_line_split
youtube.rs
lengthSeconds: Int32 paid: Bool, premium: Bool } ] */ #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] struct YTVideoInfo { title: String, video_id: String, video_thumbnails: Vec<YTThumbnailInfo>, description: String, length_seconds: i32, paid: bool,...
Ok(new_items) => { if new_items.len() == 0 { // No more items, stop iterator None } else { current_items.extend(new_items); Some(Ok(current...
{ // Error state, prevent future iteration completed = true; // Return error Some(Err(e)) }
conditional_block
youtube.rs
lengthSeconds: Int32 paid: Bool, premium: Bool } ] */ #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] struct YTVideoInfo { title: String, video_id: String, video_thumbnails: Vec<YTThumbnailInfo>, description: String, length_seconds: i32, paid: bool,...
(&self) -> Result<ChannelMetadata> { let url = format!( "{prefix}/api/v1/channels/{chanid}", prefix = api_prefix(), chanid = self.chan_id.id ); let d: YTChannelInfo = request_data(&url)?; Ok(ChannelMetadata { title: d.author.clone(), ...
get_metadata
identifier_name
x25519.rs
} /// A short-lived Diffie-Hellman secret key that can only be used to compute a single /// [`SharedSecret`]. /// /// This type is identical to the [`StaticSecret`] type, except that the /// [`EphemeralSecret::diffie_hellman`] method consumes and then wipes the secret key, and there /// are no serialization methods d...
{ self.0.as_bytes() }
identifier_body
x25519.rs
(bytes: [u8; 32]) -> PublicKey { PublicKey(MontgomeryPoint(bytes)) } } impl PublicKey { /// Convert this public key to a byte array. #[inline] pub fn to_bytes(&self) -> [u8; 32] { self.0.to_bytes() } /// View this public key as a byte array. #[inline] pub fn as_bytes(&s...
from
identifier_name
x25519.rs
be*). /// /// Some protocols, such as Noise, already handle the static/ephemeral distinction, so the /// additional guarantees provided by [`EphemeralSecret`] are not helpful or would cause duplicate /// code paths. In this case, it may be useful to /// ```rust,ignore /// use x25519_dalek::StaticSecret as SecretKey; ...
} #[test] #[cfg(feature = "serde")] fn serde_bincode_public_key_roundtrip() { use bincode; let public_key = PublicKey::from(X25519_BASEPOINT_BYTES); let encoded = bincode::serialize(&public_key).unwrap(); let decoded: PublicKey = bincode::deserialize(&encoded).unwrap()...
.to_bytes(); assert_eq!(result, expected); }
random_line_split
engine.rs
/// A sink. /// /// Note that dropping the handle doesn't delete the sink. You must call `stop` explicitely. pub struct Handle<'a> { engine: &'a Engine, source_id: usize, remaining_duration_ms: Arc<AtomicUsize>, samples_rate: u32, channels: u16, // Holds a pointer to the list of iterators to b...
size_hint
identifier_name
engine.rs
next_sounds, } } } /// A sink. /// /// Note that dropping the handle doesn't delete the sink. You must call `stop` explicitely. pub struct Handle<'a> { engine: &'a Engine, source_id: usize, remaining_duration_ms: Arc<AtomicUsize>, samples_rate: u32, channels: u16, // Holds a poin...
} }
random_line_split
geomodel.go
ArrayDoubleTuple struct { first []int second float64 } type ByDistanceIA []IntArrayDoubleTuple func (a ByDistanceIA) Len() int { return len(a) } func (a ByDistanceIA) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByDistanceIA) Less(i, j int) bool { return a[i].second < a[j].second } type ByDis...
isEven = !isEven if bit < 4 { bit = bit + 1 } else { cell[i] = GEOCELL_ALPHABET[ch] i = i + 1 bit = 0 ch = 0 } } cell = cell[:len(cell)-1] return string(cell) } func GeoCells(lat, lon float64, resolution int) []string { g := GeoCell(lat, lon, resolution) cells := make([]string, len(g), le...
} }
random_line_split
geomodel.go
ArrayDoubleTuple struct { first []int second float64 } type ByDistanceIA []IntArrayDoubleTuple func (a ByDistanceIA) Len() int { return len(a) } func (a ByDistanceIA) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByDistanceIA) Less(i, j int) bool { return a[i].second < a[j].second } type ByDis...
bbox = NewBoundingBox(90.0, 180.0, -90.0, -180.0) for len(cell) > 0 { var subcellLonSpan float64 = (bbox.lonNE - bbox.lonSW) / GEOCELL_GRID_SIZE var subcellLatSpan float64 = (bbox.latNE - bbox.latSW) / GEOCELL_GRID_SIZE var l []int = SubdivXY(rune(cell[0])) var x int = l[0] var y int = l[1] bbox = New...
{ return bbox }
conditional_block
geomodel.go
ArrayDoubleTuple struct { first []int second float64 } type ByDistanceIA []IntArrayDoubleTuple func (a ByDistanceIA) Len() int { return len(a) } func (a ByDistanceIA) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByDistanceIA) Less(i, j int) bool { return a[i].second < a[j].second } type ByDis...
(lat1, lon1, lat2, lon2 float64) float64 { var p1lat = DegToRad(lat1) var p1lon = DegToRad(lon1) var p2lat = DegToRad(lat2) var p2lon = DegToRad(lon2) return 6378135 * math.Acos(math.Sin(p1lat)*math.Sin(p2lat)+math.Cos(p1lat)*math.Cos(p2lat)*math.Cos(p2lon-p1lon)) } func DistanceSortedEdges(cells []string, lat, l...
Distance
identifier_name
geomodel.go
ArrayDoubleTuple struct { first []int second float64 } type ByDistanceIA []IntArrayDoubleTuple func (a ByDistanceIA) Len() int { return len(a) } func (a ByDistanceIA) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByDistanceIA) Less(i, j int) bool { return a[i].second < a[j].second } type ByDis...
ch |= bits[bit] west = mid } else { east = mid } } else { mid = (south + north) / 2 if lat > mid { ch |= bits[bit] south = mid } else { north = mid } } isEven = !isEven if bit < 4 { bit = bit + 1 } else { cell[i] = GEOCELL_ALPHABET[ch] i = i + 1 bit = 0 ...
{ resolution = resolution + 1 north := 90.0 south := -90.0 east := 180.0 west := -180.0 isEven := true mid := 0.0 ch := 0 bit := 0 bits := []int{16, 8, 4, 2, 1} cell := make([]byte, resolution, resolution) i := 0 for i = 0; i < resolution; { if isEven { mid = (west + east) / 2 if lon > mid {
identifier_body
gles2.rs
0..(BATCH_MAX / 4) as u16 { let index = index * 4; vertex_indices.push(index); vertex_indices.push(index + 1); vertex_indices.push(index + 3); vertex_indices.push(index + 1); vertex_indices.push(index + 2); vertex_indices.push(index + ...
{ tex: GLuint, vertices: Vec<TextVertex>, } impl Batch { fn new() -> Self { Self { tex: 0, vertices: Vec::with_capacity(BATCH_MAX) } } #[inline] fn len(&self) -> usize { self.vertices.len() } #[inline] fn capacity(&self) -> usize { BATCH_MAX } #[i...
Batch
identifier_name
gles2.rs
0..(BATCH_MAX / 4) as u16 { let index = index * 4; vertex_indices.push(index); vertex_indices.push(index + 1); vertex_indices.push(index + 3); vertex_indices.push(index + 1); vertex_indices.push(index + 2); vertex_indices.push(index +...
gl::VertexAttribPointer( index, $count, $gl_type, gl::FALSE, size_of::<TextVertex>() as i32, size as *const _, ); gl...
macro_rules! add_attr { ($count:expr, $gl_type:expr, $type:ty) => {
random_line_split
gles2.rs
0..(BATCH_MAX / 4) as u16 { let index = index * 4; vertex_indices.push(index); vertex_indices.push(index + 1); vertex_indices.push(index + 3); vertex_indices.push(index + 1); vertex_indices.push(index + 2); vertex_indices.push(index + ...
; let is_wide = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 }; let mut vertex = TextVertex { x, y: y + size_info.cell_height() as i16, glyph_x, glyph_y: glyph_y + glyph.height, u: glyph.uv_left, v: glyph.uv_bot + gly...
{ RenderingGlyphFlags::empty() }
conditional_block
gles2.rs
0..(BATCH_MAX / 4) as u16 { let index = index * 4; vertex_indices.push(index); vertex_indices.push(index + 1); vertex_indices.push(index + 3); vertex_indices.push(index + 1); vertex_indices.push(index + 2); vertex_indices.push(index + ...
} impl<'a> LoadGlyph for RenderApi<'a> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph
{ if !self.batch.is_empty() { self.render_batch(); } }
identifier_body
state.rs
Op, FrontFace}; use core::target::{ColorValue, Rect, Stencil}; use gl; pub fn bind_raster_method(gl: &gl::Gl, method: s::RasterMethod, offset: Option<s::Offset>) { let (gl_draw, gl_offset) = match method { RasterMethod::Point => (gl::POINT, gl::POLYGON_OFFSET_POINT), RasterMethod::Line(width) => {...
else {gl::TRUE}, if
{gl::FALSE}
conditional_block
state.rs
Op, FrontFace}; use core::target::{ColorValue, Rect, Stencil}; use gl; pub fn bind_raster_method(gl: &gl::Gl, method: s::RasterMethod, offset: Option<s::Offset>) { let (gl_draw, gl_offset) = match method { RasterMethod::Point => (gl::POINT, gl::POLYGON_OFFSET_POINT), RasterMethod::Line(width) => {...
(gl: &gl::Gl, color: s::Color) { match color.blend { Some(b) => unsafe { gl.Enable(gl::BLEND); gl.BlendEquationSeparate( map_equation(b.color.equation), map_equation(b.alpha.equation) ); gl.BlendFuncSeparate( map...
bind_blend
identifier_name
state.rs
Op, FrontFace}; use core::target::{ColorValue, Rect, Stencil}; use gl; pub fn bind_raster_method(gl: &gl::Gl, method: s::RasterMethod, offset: Option<s::Offset>) { let (gl_draw, gl_offset) = match method { RasterMethod::Point => (gl::POINT, gl::POLYGON_OFFSET_POINT), RasterMethod::Line(width) => {...
}, } } pub fn bind_rasterizer(gl: &gl::Gl, r: &s::Rasterizer, is_embedded: bool) { unsafe { gl.FrontFace(match r.front_face { FrontFace::Clockwise => gl::CW, FrontFace::CounterClockwise => gl::CCW, }) }; match r.cull_face { CullFace::Nothing ...
random_line_split
state.rs
Op, FrontFace}; use core::target::{ColorValue, Rect, Stencil}; use gl; pub fn bind_raster_method(gl: &gl::Gl, method: s::RasterMethod, offset: Option<s::Offset>) { let (gl_draw, gl_offset) = match method { RasterMethod::Point => (gl::POINT, gl::POLYGON_OFFSET_POINT), RasterMethod::Line(width) => {...
pub fn bind_blend(gl: &gl::Gl, color: s::Color) { match color.blend { Some(b) => unsafe { gl.Enable(gl::BLEND); gl.BlendEquationSeparate( map_equation(b.color.equation), map_equation(b.alpha.equation) ); gl.BlendFuncSeparate( ...
{ match factor { s::Factor::Zero => gl::ZERO, s::Factor::One => gl::ONE, s::Factor::ZeroPlus(BlendValue::SourceColor) => gl::SRC_COLOR, s::Factor::OneMinus(BlendValue::SourceColor) => gl::ONE_MINUS_SRC_COLOR, s::Facto...
identifier_body
TestGAN.py
as sbs import pdb sbs.set() epsilon = 0.0000000001 def generate_sample(gen, batch_size, latent_dim): noise = np.random.normal(0, 1, (batch_size, latent_dim)) return gen.predict(noise) def show_images(imgs): cols = 8 rows = (len(imgs) // cols ) + (len(imgs) % cols) # Rescale images 0 - 1 ...
plt.savefig(filename) plt.close() def show_images(gan_imgs, orig_imgs, filename=None): n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(gan_imgs[i].reshape(28, 28)) ...
plt.show() else:
random_line_split
TestGAN.py
as sbs import pdb sbs.set() epsilon = 0.0000000001 def generate_sample(gen, batch_size, latent_dim): noise = np.random.normal(0, 1, (batch_size, latent_dim)) return gen.predict(noise) def show_images(imgs): cols = 8 rows = (len(imgs) // cols ) + (len(imgs) % cols) # Rescale images 0 - 1 ...
def plot_results(sizes, ddiff, dstd, control, graph_params, filename=None): plt.figure() carr = np.zeros(len(sizes)) carr.fill(control) plt.plot(sizes, carr, label=graph_params.control_legend) plt.errorbar(sizes, ddiff, yerr=dstd, label=graph_params.ddiff_legend) plt.grid(b=True) plt.xlabe...
def __init__(self, xlabel, ylabel, control_legend, ddiff_legend): self.xlabel = xlabel self.ylabel = ylabel self.control_legend = control_legend self.ddiff_legend = ddiff_legend
identifier_body
TestGAN.py
as sbs import pdb sbs.set() epsilon = 0.0000000001 def generate_sample(gen, batch_size, latent_dim): noise = np.random.normal(0, 1, (batch_size, latent_dim)) return gen.predict(noise) def show_images(imgs): cols = 8 rows = (len(imgs) // cols ) + (len(imgs) % cols) # Rescale images 0 - 1 ...
else: plt.savefig(filename) plt.close() def show_images(gan_imgs, orig_imgs, filename=None): n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(gan_imgs[i].reshape(...
plt.show()
conditional_block
TestGAN.py
as sbs import pdb sbs.set() epsilon = 0.0000000001 def generate_sample(gen, batch_size, latent_dim): noise = np.random.normal(0, 1, (batch_size, latent_dim)) return gen.predict(noise) def
(imgs): cols = 8 rows = (len(imgs) // cols ) + (len(imgs) % cols) # Rescale images 0 - 1 imgs = 0.5 * imgs + 0.5 fig, axs = plt.subplots(rows, cols) cnt = 0 for i in range(rows): for j in range(cols): if cnt < len(imgs): axs[i,j].imshow(imgs[cnt, :,:...
show_images
identifier_name
service.go
SpecID) (*graphql.Campaign, error) { var result struct { Campaign *graphql.Campaign `json:"applyCampaign"` } if ok, err := svc.newRequest(applyCampaignMutation, map[string]interface{}{ "campaignSpec": spec, }).Do(ctx, &result); err != nil || !ok { return nil, err } return result.Campaign, nil } const creat...
Data struct { CurrentUser struct { ID string `json:"id"` } `json:"currentUser"` } `json:"data"` } if ok, err := svc.client.NewRequest(usernameQuery, nil).DoRaw(ctx, &resp); err != nil || !ok { return "", errors.WithMessage(err, "failed to resolve namespace: no user logged in") } if resp.D...
func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (string, error) { if namespace == "" { // if no namespace is provided, default to logged in user as namespace var resp struct {
random_line_split
service.go
multierror.Error x.Start(ctx) specs, err := x.Wait() if progress != nil { x.LockedTaskStatuses(progress) done <- struct{}{} } if err != nil { if skipErrors { errs = multierror.Append(errs, err) } else { return nil, err } } // Add external changeset specs. for _, ic := range spec.ImportChangese...
{ repo := r.Repository repos = append(repos, &repo) ids[r.ID] = &repo }
conditional_block
service.go
SpecID) (*graphql.Campaign, error) { var result struct { Campaign *graphql.Campaign `json:"applyCampaign"` } if ok, err := svc.newRequest(applyCampaignMutation, map[string]interface{}{ "campaignSpec": spec, }).Do(ctx, &result); err != nil || !ok { return nil, err } return result.Campaign, nil } const creat...
(ctx context.Context, namespace, spec string, ids []ChangesetSpecID) (CampaignSpecID, string, error) { var result struct { CreateCampaignSpec struct { ID string ApplyURL string } } if ok, err := svc.client.NewRequest(createCampaignSpecMutation, map[string]interface{}{ "namespace": namespace, ...
CreateCampaignSpec
identifier_name
service.go
sid = strconv.FormatInt(reflect.ValueOf(id).Int(), 10) case uint, uint8, uint16, uint32, uint64: sid = strconv.FormatUint(reflect.ValueOf(id).Uint(), 10) case float32: sid = strconv.FormatFloat(float64(tid), 'f', -1, 32) case float64: sid = strconv.FormatFloat(tid, 'f', -1, 64) default: ...
{ var tn struct { Typename string `json:"__typename"` } if err := json.Unmarshal(data, &tn); err != nil { return err } switch tn.Typename { case "FileMatch": var result struct { Repository graphql.Repository File struct { Path string } } if err := json.Unmarshal(data, &result); err !...
identifier_body
debian.py
""" @attrs(eq=False, order=False, frozen=True, hash=False, slots=True, str=False) class Version(object): """ Rich comparison of Debian package versions as first-class Python objects. The :class:`Version` class is a subclass of the built in :class:`str` type that implements rich comparison according t...
else: upstream = version revision = "0" return cls(epoch=epoch, upstream=upstream, revision=revision) def compare(self, other_version): return compare_versions(self, other_version) def to_dict(self): return asdict(self) def tuple(self): ret...
upstream, _, revision = version.rpartition("-")
conditional_block
debian.py
""" @attrs(eq=False, order=False, frozen=True, hash=False, slots=True, str=False) class Version(object): """ Rich comparison of Debian package versions as first-class Python objects. The :class:`Version` class is a subclass of the built in :class:`str` type that implements rich comparison according t...
p2 = get_non_digit_prefix(v2) if p1 != p2: logger.debug("Comparing non-digit prefixes %r and %r ..", p1, p2) for c1, c2 in zip_longest(p1, p2, fillvalue=""): logger.debug( "Performing lexical comparison between characters %r and %r ..", c1, c2 ...
""" Compare two version strings (upstream or revision) using Debain semantics and return one of the following integer numbers: - -1 means version1 sorts before version2 - 0 means version1 and version2 are equal - 1 means version1 sorts after version2 """ logger.debug("Comparing D...
identifier_body
debian.py
""" @attrs(eq=False, order=False, frozen=True, hash=False, slots=True, str=False) class Version(object): """ Rich comparison of Debian package versions as first-class Python objects. The :class:`Version` class is a subclass of the built in :class:`str` type that implements rich comparison according t...
(self, other): return not self.__eq__(other) def __lt__(self, other): if type(self) is type(other): return eval_constraint(self, "<<", other) return NotImplemented def __le__(self, other): if type(self) is type(other): return eval_constraint(self, "<=", ...
__ne__
identifier_name
debian.py
""" @attrs(eq=False, order=False, frozen=True, hash=False, slots=True, str=False) class Version(object): """ Rich comparison of Debian package versions as first-class Python objects. The :class:`Version` class is a subclass of the built in :class:`str` type that implements rich comparison according t...
upstream = version revision = "0" return cls(epoch=epoch, upstream=upstream, revision=revision) def compare(self, other_version): return compare_versions(self, other_version) def to_dict(self): return asdict(self) def tuple(self): return self.epoch,...
upstream, _, revision = version.rpartition("-") else:
random_line_split
proxy.rs
)] pub enum Error { ForkingJail(minijail::Error), Io(io::Error), } pub type Result<T> = std::result::Result<T, Error>; impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { ForkingJail(e) => write!(f, "Failed to fork ja...
Ok(r) => Some(r), } } } impl BusDevice for ProxyDevice { fn debug_label(&self) -> String { self.debug_label.clone() } fn config_register_write(&mut self, reg_idx: usize, offset: u64, data: &[u8]) { let len = data.len() as u32; let mut buffer = [0u8; 4]; ...
{ error!( "failed to read result of {:?} from child device process {}: {}", cmd, self.debug_label, e, ); None }
conditional_block
proxy.rs
)] pub enum Error { ForkingJail(minijail::Error), Io(io::Error), } pub type Result<T> = std::result::Result<T, Error>; impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { ForkingJail(e) => write!(f, "Failed to fork ja...
(&mut self, info: BusAccessInfo, data: &[u8]) { let mut buffer = [0u8; 8]; let len = data.len() as u32; buffer[0..data.len()].clone_from_slice(data); self.send_no_result(&Command::Write { len, info, data: buffer, }); } } impl Drop for Prox...
write
identifier_name
proxy.rs
)] pub enum Error { ForkingJail(minijail::Error), Io(io::Error), } pub type Result<T> = std::result::Result<T, Error>; impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { ForkingJail(e) => write!(f, "Failed to fork ja...
self.data = data[0]; } fn read(&mut self, _info: BusAccessInfo, data: &mut [u8]) { assert!(data.len() == 1); data[0] = self.data; } fn config_register_write(&mut self, _reg_idx: usize, _offset: u64, data: &[u8]) { assert!(data.len() == 1)...
"EchoDevice".to_owned() } fn write(&mut self, _info: BusAccessInfo, data: &[u8]) { assert!(data.len() == 1);
random_line_split
client.rs
Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OT...
.map_err(|_| ClientError::VersionParseError(s.to_string()))?; } } let version = Version { version: s.to_string(), major, minor, patch, }; Ok(version) } pub fn as_u64(&self) -> u64 { (self.maj...
patch = part .parse::<u64>()
random_line_split
client.rs
Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OT...
(&mut self, yes: bool) -> &Self { self.disable_certificate_validation = yes; self } pub fn with_username(&mut self, username: &str) -> &Self { self.username = Some(username.to_string()); self } pub fn with_password(&mut self, password: &str) -> &Self { self.pass...
disable_certificate_validation
identifier_name
client.rs
#[error("json: {0}")] JsonError(serde_json::error::Error), #[error("failed to parse version: {0}")] VersionParseError(String), #[error("{0}")] StringError(String), } impl From<reqwest::Error> for ClientError { fn from(err: reqwest::Error) -> Self { ClientError::ReqwestError(err) ...
{ if !self.has_error() { return None; } if let Some(error) = &self.error { return Some(error.to_string()); } if let Some(items) = &self.items { for item in items { if let serde_json::Value::String(err) = &item["index"]["error"][...
identifier_body
client.rs
. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABI...
; Ok(request) } pub fn post(&self, path: &str) -> Result<reqwest::RequestBuilder, reqwest::Error> { let url = format!("{}/{}", self.url, path); let request = self .get_http_client()? .post(&url) .header("Content-Type", "application/json"); let...
{ request }
conditional_block
interactive.rs
the selection process struct State<'s, 't> where 't: 's, { /// Which suggestion is operated upon. pub suggestion: &'s Suggestion<'t>, /// The content the user provided for the suggestion, if any. pub custom_replacement: String, /// Which index to show as highlighted. pub pick_idx: usize, ...
pub fn to_bandaid(&self) -> BandAid { if self.is_custom_entry() { BandAid::from(( self.custom_replacement.clone(), self.suggestion.span.clone(), )) } else { BandAid::try_from((self.suggestion, self.pick_idx)) .expe...
{ self.pick_idx + 1 == self.n_items }
identifier_body
interactive.rs
{ Replacement(BandAid), /// Skip this suggestion and move on to the next suggestion. Skip, /// Jump to the previous suggestion. Previous, /// Print the help message and exit. Help, /// Skip the remaining fixes for the current file. SkipFile, /// Stop execution. Quit, ///...
Pick
identifier_name
interactive.rs
use crossterm; use crossterm::{ cursor, event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}, terminal, QueueableCommand, }; use std::convert::TryFrom; use std::io::{stdin, stdout}; use std::path::Path; const HELP: &...
//! //! The result of that pick is a bandaid. use super::*;
random_line_split
WebGlCanvas.ts
return tex; } private resizeTexture(texture: WebGLTexture, width: number, height: number) { if (this.checkContextLoss()) return; const gl = this.gl; const textureType = this.textureTypes.get(texture); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, textureType, width...
getBlob
identifier_name
WebGlCanvas.ts
private frameBuffer: WebGLFramebuffer; private textureTypes = new Map<WebGLTexture, number>(); private textureSizes = new Map<WebGLTexture, { width: number, height: number }>(); private frameBufferTextures = new Map<WebGLFramebuffer, WebGLTexture>(); private refs: ResourceMap = { programs: [], shader...
const bufferInfo = createBufferInfoFromArrays(this.gl, { position: { numComponents: 2, data: positions }, texcoord: { numComponents: 2, data: texCoords }, indices: indices }); // collect references to buffer objects for (let name in bufferIn...
{ for (let x = 0; x < xSubdivs; x++) { // triangle 1 indices[indicesPtr++] = (y + 0) * numVertsAcross + x; indices[indicesPtr++] = (y + 1) * numVertsAcross + x; indices[indicesPtr++] = (y + 0) * numVertsAcross + x + 1; // triangle 2 indices[indicesPtr++] = (y + 0) *...
conditional_block
WebGlCanvas.ts
private frameBuffer: WebGLFramebuffer; private textureTypes = new Map<WebGLTexture, number>(); private textureSizes = new Map<WebGLTexture, { width: number, height: number }>(); private frameBufferTextures = new Map<WebGLFramebuffer, WebGLTexture>(); private refs: ResourceMap = { programs: [], shader...
private createProgram(vertexShaderSource: string, fragmentShaderSource: string) { if (this.checkContextLoss()) return; const gl = this.gl; const vert = this.createShader(gl.VERTEX_SHADER, vertexShaderSource); const frag = this.createShader(gl.FRAGMENT_SHADER, fragmentShaderSource); const program...
{ this.setCanvasSize(this.width, this.height); const gl = this.gl; if (this.checkContextLoss()) return; this.layerProgram = this.createProgram(vertShaderLayer, fragShaderLayer); this.upscaleProgram = this.createProgram(vertShaderUpscale, fragShaderUpscale); this.quadBuffer = this.createScreenQua...
identifier_body
WebGlCanvas.ts
CanvasStereoscopicMode.Dual, // CanvasStereoscopicMode.Anaglyph, // couldn't get this working, despite spending lots of time on it :/ ]; /** */ stereoscopeMode = CanvasStereoscopicMode.None; /** */ stereoscopeStrength = 0; private options: WebglCanvasOptions; private layerProgram: ProgramInfo; //...
/** */ frameIndex: number; /** */ supportedStereoscopeModes = [ CanvasStereoscopicMode.None,
random_line_split
tables.py
Parameters... none # CRITICAL for multiple input ports def FillInputPortInformation(self, port, info): """Used by pipeline. Necessary when dealing with multiple input ports """ # all are tables so no need to check port info.Set(self.INPUT_REQUIRED_DATA_TYPE(), "vtkTable") ...
def Apply(self, inputDataObject, arrayName): self.SetInputDataObject(inputDataObject) arr, field = _helpers.searchForArray(inputDataObject, arrayName) self.SetInputArrayToProcess(0, 0, 0, field, arrayName) self.Update() return self.GetOutput() ############################...
return 1
random_line_split
tables.py
Parameters... none # CRITICAL for multiple input ports def FillInputPortInformation(self, port, info): """Used by pipeline. Necessary when dealing with multiple input ports """ # all are tables so no need to check port info.Set(self.INPUT_REQUIRED_DATA_TYPE(), "vtkTable") ...
def SetNumberOfRows(self, nrows): """Set the number of rows for the output ``vtkTable`` """ if isinstance(nrows, float): nrows = int(nrows) if self.__nrows != nrows: self.__nrows = nrows self.Modified() def SetOrder(self, order): """...
"""Set the number of columns for the output ``vtkTable`` """ if isinstance(ncols, float): ncols = int(ncols) if self.__ncols != ncols: self.__ncols = ncols self.Modified()
identifier_body
tables.py
Parameters... none # CRITICAL for multiple input ports def FillInputPortInformation(self, port, info): """Used by pipeline. Necessary when dealing with multiple input ports """ # all are tables so no need to check port info.Set(self.INPUT_REQUIRED_DATA_TYPE(), "vtkTable") ...
(self, **kwargs): FilterBase.__init__(self, nInputPorts=1, inputType='vtkTable', nOutputPorts=1, outputType='vtkTable') # Parameters self.__nrows = kwargs.get('nrows', 1) self.__ncols = kwargs.get('ncols', 1) self.__names = kwargs.get('names', []) ...
__init__
identifier_name
tables.py
Parameters... none # CRITICAL for multiple input ports def FillInputPortInformation(self, port, info): """Used by pipeline. Necessary when dealing with multiple input ports """ # all are tables so no need to check port info.Set(self.INPUT_REQUIRED_DATA_TYPE(), "vtkTable") ...
else: self.__names = ['Field %d' % i for i in range(self.__ncols)] # Make a 2D numpy array and fill with data from input table data = np.empty((rows,cols)) for i in range(cols): c = pdi.GetColumn(i) data[:,i] = interface.convertArray(c) if (...
raise _helpers.PVGeoError('Too many array names. `ncols` specified as %d and %d names given.' % (self.__ncols, num))
conditional_block
testdriver.py
664 /target/testdriver.log') def log(msg=""): """ Logs the given text message to stdout AND the logfile """ print(msg) sys.stdout.flush() f = open("/target/testdriver.log", "a") f.write('{:%Y-%m-%d %H:%M:%S.%s} :: '.format(datetime.datetime.now())) f.write(f"{msg}\n") f.close() def is_...
(): """Launch a cluster. This function creates a folder .cluster/ where everything related to the cluster is stored. In the cluster definition, the 'publicKeys' section is extended with a generated public key. The according private key is used to access the cluster later. If the cluster laun...
launch
identifier_name
testdriver.py
not contain a valid 'publicKeys' section.") exit(1) cluster_definition_yaml["publicKeys"].append(public_key) with open (f"{CLUSTER_FOLDER}/cluster.yaml", "w") as f: f.write(yaml.dump(cluster_definition_yaml, default_flow_style=False)) f.close() start_time = time.time() ...
log("Interactive mode. The testdriver will be open for business until you stop it by creating a file /cluster_lock") while not os.path.exists('/cluster_lock'): time.sleep(5)
conditional_block
testdriver.py
664 /target/testdriver.log') def log(msg=""): """ Logs the given text message to stdout AND the logfile """ print(msg) sys.stdout.flush() f = open("/target/testdriver.log", "a") f.write('{:%Y-%m-%d %H:%M:%S.%s} :: '.format(datetime.datetime.now())) f.write(f"{msg}\n") f.close() def is_...
def get_cluster(t2_url, t2_token, id): """Get the cluster information using T2 REST API Returns: - JSON representing cluster (REST response) """ response = requests.get(f"{t2_url}/api/clusters/{id}", headers={ "t2-token": t2_token }) if(response.status_code != 200): log(f"API call to...
"""Create a cluster using T2 REST API Returns: - JSON representing cluster (REST response) """ response = requests.post(f"{t2_url}/api/clusters", data=cluster_definition, headers={ "t2-token": t2_token, "Content-Type": "application/yaml" }) if(response.status_code != 200): log(f"API call to...
identifier_body
testdriver.py
664 /target/testdriver.log') def log(msg=""): """ Logs the given text message to stdout AND the logfile """ print(msg) sys.stdout.flush() f = open("/target/testdriver.log", "a") f.write('{:%Y-%m-%d %H:%M:%S.%s} :: '.format(datetime.datetime.now())) f.write(f"{msg}\n") f.close() def is_...
def run_test_script(): if os.path.isfile("/test.sh"): os.system('rm -rf /target/stackable-versions.txt || true') os.system('rm -rf /target/test_output.log || true') os.system('touch /target/test_output.log') os.system(f"chown {uid_gid_output} /target/test_output.log") os.syst...
return 'INTERACTIVE_MODE' in os.environ and os.environ['INTERACTIVE_MODE']=='true'
random_line_split
hackc.rs
32 MiB"))] stack_size: Byte, /// Instead of printing the unit, print a list of the decls requested during compilation. /// (only used by --test-compile-with-decls) #[clap(long)] pub(crate) log_decls_requested: bool, /// Use serialized decl instead of decl pointer as the decl provider API /...
{ use std::io::Write; for line in std::io::stdin().lock().lines() { let mut buf = Vec::new(); f(Path::new(&line?).to_path_buf(), &mut buf)?; // Account for utf-8 encoding and text streams with the python test runner: // https://stackoverflow.com/questions/3586923/counting-unicode...
identifier_body
hackc.rs
; use std::path::Path; use std::path::PathBuf; /// Hack Compiler #[derive(Parser, Debug, Default)] struct Opts { #[clap(subcommand)] command: Option<Command>, /// Runs in daemon mode for testing purposes. Do not rely on for production #[clap(long)] daemon: bool, #[clap(flatten)] flag_comm...
{ /// Input file(s) filenames: Vec<PathBuf>, /// Read a list of files (one-per-line) from this file #[clap(long)] input_file_list: Option<PathBuf>, } #[derive(Parser, Debug)] enum Command { /// Assemble HHAS file(s) into HackCUnit. Prints those HCUs' HHAS representation. Assemble(assemble...
FileOpts
identifier_name
hackc.rs
; use std::path::Path; use std::path::PathBuf; /// Hack Compiler #[derive(Parser, Debug, Default)] struct Opts { #[clap(subcommand)] command: Option<Command>, /// Runs in daemon mode for testing purposes. Do not rely on for production #[clap(long)] daemon: bool, #[clap(flatten)] flag_comm...
// Test Decls-in-Compilation None if opts.daemon && opts.flag_commands.test_compile_with_decls => { compile::test_decl_compile_daemon(&mut opts) } None if opts.flag_commands.test_compile_with_decls => { compile::test_decl_compile(&mut
{ facts::run_flag(&mut opts, &mut std::io::stdout()) }
conditional_block
hackc.rs
Read; use std::path::Path; use std::path::PathBuf; /// Hack Compiler #[derive(Parser, Debug, Default)] struct Opts { #[clap(subcommand)] command: Option<Command>, /// Runs in daemon mode for testing purposes. Do not rely on for production #[clap(long)] daemon: bool, #[clap(flatten)] flag_...
for_debugger_eval: bool, #[clap(long, default_value("0"))] emit_class_pointers: i32, #[clap(long, default_value("0"))] check_int_overflow: i32, /// Number of parallel worker threads for subcommands that support parallelism, /// otherwise ignored. If 0, use available parallelism, typically...
#[clap(long)] disable_toplevel_elaboration: bool, /// Mutate the program as if we're in the debugger repl #[clap(long)]
random_line_split
conductor.go
chan error au audition prErrCh <-chan error pr prompter colErrCh <-chan error col collector spotErrCh <-chan error spm spotMgr } func (ap *app) makeTheater(ctx context.Context) (th theater) { prompterAndAuditiontoCollectorCh := make(chan collectorEvent, 10) prompterAndSpotlightsToAudit...
{ continue }
conditional_block
conductor.go
} }() // Start the spotlights. var wgspot sync.WaitGroup allSpotsDone := th.spm.startSpotlights(ctx, &wgspot) // Start the prompter. var wgPrompt sync.WaitGroup promptDone := th.pr.startPrompter(ctx, &wgPrompt) // The shutdown sequence without cancellation/stopper is: // - prompter exits, this closes spot...
interrupt = false } wgau.Wait() auDone() // in case not called before. // Fourth stage: wait for the collector to finish. finalErr = combineErrors(ignCancel(<-th.colErrCh), finalErr) wgcol.Wait() colDone() // in case not called before. return finalErr } type theater struct { auErrCh <-chan error au ...
log.Info(ctx, "something went wrong after spotlights terminated, cancelling audience and collector") auDone() finalErr = combineErrors(ignCancel(<-th.auErrCh), finalErr) colDone() finalErr = combineErrors(ignCancel(<-th.colErrCh), finalErr)
random_line_split
conductor.go
finalErr = combineErrors(err, finalErr) interrupt = true case err := <-th.auErrCh: finalErr = combineErrors(err, finalErr) interrupt = true case err := <-th.colErrCh: finalErr = combineErrors(err, finalErr) interrupt = true } if interrupt { log.Info(ctx, "something went wrong other than prompter, canc...
runCleanup
identifier_name
conductor.go
() // in case not called before. // Second stage: wait for the spotlights to finish. select { case err := <-th.spotErrCh: finalErr = combineErrors(err, finalErr) // ok case err := <-th.auErrCh: finalErr = combineErrors(err, finalErr) interrupt = true case err := <-th.colErrCh: finalErr = combineErrors(e...
{ // errCh collects the errors from the concurrent actors. errCh := make(chan error, len(ap.cfg.actors)+1) defer func() { if r := recover(); r != nil { panic(r) } // At the end of the scene, make runScene() return the collected // errors. err = collectErrors(ctx, nil, errCh, prefix) }() var wg sync....
identifier_body
creat_model_save.py
..] doc = {} # bestN = 4 # result = np.array([0, 0, 0, 0]) # maxDepth = 5 avgDepth = 0 # If the values are supplied as command line arguments if len(sys.argv) == 3: branches = int(sys.argv[1]) maxDepth = int(sys.argv[2]) model = MiniBatchKM...
(F, M1, M2, M3, M4): a = [0, 0, 0, 0] group = int(F / 4) if int(M1 / 4) == group: a[0] = 1 if int(M2 / 4) == group: a[1] = 1 if int(M3 / 4) == group: a[2] = 1 if int(M4 / 4) == group: a[3] = 1 return np.array(a) # Finds 4 best matches for the query def matc...
accuracy
identifier_name
creat_model_save.py
..] doc = {} # bestN = 4 # result = np.array([0, 0, 0, 0]) # maxDepth = 5 avgDepth = 0 # If the values are supplied as command line arguments if len(sys.argv) == 3: branches = int(sys.argv[1]) maxDepth = int(sys.argv[2]) model = MiniBatchKM...
# ------------------------------------------------------------------------------------------------------------ start = t.time() print("Extracting Features: " + rootDir + " ...") # dump all features as array features = dumpFeatures(rootDir) end = t.time() print("Time Taken: ", str(round((end - start) / 60, 2))) sta...
return int((re.findall("\d+", s))[0])
identifier_body
creat_model_save.py
..] doc = {} # bestN = 4 # result = np.array([0, 0, 0, 0]) # maxDepth = 5 avgDepth = 0 # If the values are supplied as command line arguments if len(sys.argv) == 3: branches = int(sys.argv[1]) maxDepth = int(sys.argv[2]) model = MiniBatchKM...
# Returns the scores of the images in the dataset def getScores(q): scores = {} n = 0 curr = [float("inf"), float("inf"), float("inf"), float("inf")] currimg = ["", "", "", ""] for fname in fileList: img = dirName + "/" + fname scores[img] = 0 for leafID in imagesInLeaves: ...
# This function returns the weight of a leaf node def weight(leafID): return math.log1p(N / 1.0 * len(imagesInLeaves[leafID]))
random_line_split
creat_model_save.py
..] doc = {} # bestN = 4 # result = np.array([0, 0, 0, 0]) # maxDepth = 5 avgDepth = 0 # If the values are supplied as command line arguments if len(sys.argv) == 3: branches = int(sys.argv[1]) maxDepth = int(sys.argv[2]) model = MiniBatchKM...
elif scores[img] > curr[0] and scores[img] <= curr[1]: currimg[3], curr[3] = currimg[2], curr[2] currimg[2], curr[2] = currimg[1], curr[1] currimg[1], curr[1] = img, scores[img] elif scores[img] > curr[1] and scores[img] <= curr[2]: currimg[3], curr[3] = ...
currimg[3], curr[3] = currimg[2], curr[2] currimg[2], curr[2] = currimg[1], curr[1] currimg[1], curr[1] = currimg[0], curr[0] currimg[0], curr[0] = img, scores[img]
conditional_block
pipeline_v2.py
## Part 2: explore data def take_sample(df, fraction): return df.sample(frac = fraction) def show_columns(df): return df.columns def descrip_stats(df): return df.describe() def counts_per_variable(df, x): return df.groupby(x).size() def group_and_describe(df, x): return df.groupby(x).describe() de...
if filetype == "csv": return pd.read_csv(fn) if filetype == "excel": return pd.read_excel(fn) if filetype == "sql": return pd.read_sql(fn, con=conn) else: return print("I only have CSVs at the moment!")
identifier_body
pipeline_v2.py
): return pd.crosstab(df.loc[:, x], df.loc[:,y]) def basic_hist(df, x, title_text): sns.distplot(df[x]).set_title(title_text) plt.show() return def basic_scatter(df, x, y, title_text): g = sns.lmplot(x, y, data= df) g = (g.set_axis_labels(x, y).set_title(title_text)) plt.show() return def correlation_heatmap...
(df): num_cols = len(df.columns) for i in range(0, num_cols): df.iloc[:,i] = fill_col_with_mean(df.iloc[:,i]) return def fill_allNA_mode(df): num_col = len(df.columns.tolist()) for i in range(0,num_col): df_feats.iloc[:,i] = df_feats.iloc[:,i].fillna(df_feats.iloc[:,i].mode()[0]) ...
fill_whole_df_with_mean
identifier_name
pipeline_v2.py
left_merge(df_left, df_right, merge_column): return pd.merge(df_left, df_right, how = 'left', on = merge_column) # generating features def generate_dummy(df, colname, attach = False): # generate dummy variables from a categorical variable # if attach == True, then attach the dummy variables to the origin...
correct_pred +=1
conditional_block
pipeline_v2.py
y): return pd.crosstab(df.loc[:, x], df.loc[:,y]) def basic_hist(df, x, title_text): sns.distplot(df[x]).set_title(title_text) plt.show() return def basic_scatter(df, x, y, title_text): g = sns.lmplot(x, y, data= df) g = (g.set_axis_labels(x, y).set_title(title_text)) plt.show() return def correlation_heatm...
'loss': ["deviance", "exponential"], 'learning_rate': [0.01, 0.1, 0.2, 0.3], 'n_estimators': [3, 6, 10, 20, 100, 200, 500] } } def classifier_comparison(model_params, x_train, y_train, eva_metric, cv_num): comparison_results = {} for model, param_grid in model_params.items(): # initia...
"C": [10**-5, 10**-2, 10**-1, 1, 10, 10**2, 10**5] }, GradientBoostingClassifier:{
random_line_split
xfdemo.py
len: {str(len(self.__keywords))}") return 0 # turn language argument into reuqest parameters def loadLanguage(self, language="zh"): # input arguments -> request parameters if language == "zh": self.__language = "cn" else: self.__language = language ...
return 0
random_line_split
xfdemo.py
1:] break else: ch = ch[:j] + 'a' + ch[j+1:] j = j -1 self.__ch = ch return self.__ch class xfdemo(object): def __
return 0 def loadKeywords(self, keywordfile = "keywords.txt"): # load keywords from text file and convert into string with open(keywordfile, encoding='utf8') as fi: keyword_str = fi.read() self.__keywords = keyword_str.replace('\n', ',') stg_log(f"keywords loade...
init__(self, audio_file_name, time_offset=0): from pathlib import PurePath self.__file_path = audio_file_name pathobj = PurePath(self.__file_path) self.__file_name = pathobj.parts[-1] self.__file_size = 0 self.__slice_num = 1 self.__time_offset = time_offset ...
identifier_body
xfdemo.py
keywords))}") return 0 # turn language argument into reuqest parameters def loadLanguage(self, language="zh"): # input arguments -> request parameters if language == "zh": self.__language = "cn" else: self.__language = language return 0 # ch...
gs():
identifier_name
xfdemo.py
:] break else: ch = ch[:j] + 'a' + ch[j+1:] j = j -1 self.__ch = ch return self.__ch class xfdemo(object): def __init__(self, audio_file_name, time_offset=0): from pathlib import PurePath self.__file_path = audio_file_name...
# headers not required # headers = {"Content-Type": "multipart/form-data"} headers = None req_data = {"app_id": self.__appid, "signa": sign, "ts": stamp, "task_id": self.__task_id, "slice_id": current_slice_id } # be ...
g(f"reqFileSlice file ends") break
conditional_block
crea_cig_esiti_senza_duplicati.py
n_OS2B= n_OS2B+1 elif categoria =='OS3': n_OS3= n_OS3+1 elif categoria =='OS4': n_OS4= n_OS4+1 elif categoria =='OS5': n_OS5= n_OS5+1 elif categoria =='OS6': n_OS6= n_OS6+1 elif categoria =='OS7': n_OS7= n_OS7+1 elif categoria =='OS8': n_OS8= n_OS...
(data): data=data.replace(u'\xa0', '') if data: d = datetime.strptime(data, '%d/%m/%Y') day_string = d.strftime('%Y-%m-%d') else: day_string = "1900-01-01" return day_string def prendi_provincia_regione2(comun): try: sql_co...
data_per_db
identifier_name
crea_cig_esiti_senza_duplicati.py
n_OS2B= n_OS2B+1 elif categoria =='OS3': n_OS3= n_OS3+1 elif categoria =='OS4': n_OS4= n_OS4+1 elif categoria =='OS5': n_OS5= n_OS5+1 elif categoria =='OS6': n_OS6= n_OS6+1 elif categoria =='OS7': n_OS7= n_OS7+1 elif categoria =='OS8': n_OS8= n_OS...
elif categoria =='OS11': n_OS11= n_OS11+1 elif categoria =='OS12-A': n_OS12A= n_OS12A+1 elif categoria =='OS12-B': n_OS12B= n_OS12B+1 elif categoria =='OS13': n_OS13= n_OS13+1 elif categoria =='OS14': n_OS14= n_OS14+1 elif categoria =='OS15': n_OS...
n_OS10= n_OS10+1
conditional_block
crea_cig_esiti_senza_duplicati.py
n_OS3=0 n_OS4=0 n_OS5=0 n_OS6=0 n_OS7=0 n_OS8=0 n_OS9=0 n_OS10=0 n_OS11=0 n_OS12A=0 n_OS12B=0 n_OS13=0 n_OS14=0 n_OS15=0 n_OS16=0 n_OS17=0 n_OS18A=0 n_OS18B=0 n_OS19=0 n_OS20A=0 n_OS20B=0 n_OS21=0 n_OS22=0 n_OS23=0 n_OS2...
cursore = conn.cursor() cursore.execute("SELECT * FROM gare.cpv_to_cat where CPV = '"+CPV+"'") CPV_trovati = cursore.fetchall() n_OG1= 0 n_OG2 = 0 n_OG3 = 0 n_OG4 = 0 n_OG5=0 n_OG6=0 n_OG7=0 n_OG8=0 n_OG9=0 n_OG10=0 n_OG11=0 n_OG12=0 n_OG13=0 n_OS1=0 ...
identifier_body
crea_cig_esiti_senza_duplicati.py
n_OS12B=0 n_OS13=0 n_OS14=0 n_OS15=0 n_OS16=0 n_OS17=0 n_OS18A=0 n_OS18B=0 n_OS19=0 n_OS20A=0 n_OS20B=0 n_OS21=0 n_OS22=0 n_OS23=0 n_OS24=0 n_OS25=0 n_OS26=0 n_OS27=0 n_OS28=0 n_OS29=0 n_OS30=0 n_OS31=0 n_OS32=0 n_OS33=0 ...
n_OS9=0 n_OS10=0 n_OS11=0 n_OS12A=0
random_line_split
neuralnet.py
umsamples (N) x Outputs (No CLasses) # an array containing the size of the output of all of the laye of the neural net """ # Hidden layer DxHLS weights_L1,bias_L1,weights_L2,bias_L2 = self._extract_weights(W) # Output layer HLSxOUT #...
if patience <= iter: done_looping = True break # for the graph self.error_testing[epoch*self._batch_number + batch] = self.calculate_zero_one_loss() print "Error in ...
if this_validation_loss < best_validation_loss * improvement_threshold: patience = max(patience, iter * patience_increase) best_params = np.copy(self._betas) best_validation_loss = this_validation_loss
conditional_block
neuralnet.py
_weight_no += self._hidden_layer_size * self._output_size + self._output_size self._betas = np.random.normal(0, 0.1, network_weight_no) #layer 2: hidden layer * no_classes + no_classes for the biases def _traing_mini_sgd(self,learning_rate=0.2,batch_number=10,epochs=1,rm...
random_line_split
neuralnet.py
umsamples (N) x Outputs (No CLasses) # an array containing the size of the output of all of the laye of the neural net """ # Hidden layer DxHLS weights_L1,bias_L1,weights_L2,bias_L2 = self._extract_weights(W) # Output layer HLSxOUT #...
def visualize_receptive_fields(self): import sys beta_set = cPickle.load(open(self._weights_filename,"r")) beta_set = beta_set.reshape(self._D,self._hidden_layer_size).T #print beta_set.shape plt.figure(9) sys.stdout.write('Writing visualizations of rece...
f = open(self._weights_filename, 'w') cPickle.dump(self._betas[0:self._D*self._hidden_layer_size],f) f.close()
identifier_body
neuralnet.py
(self,W): """ This will extract the weights from we big W array. in a 1-hidden layer network. this can be easily generalized. """ wl1_size = self._D*self._hidden_layer_size bl1_size = self._hidden_layer_size wl2_size = self._hidden_layer_size*self._output...
_extract_weights
identifier_name
fiber.rs
. /// /// This kind of waiting is more convenient than going into a loop and periodically checking the status; /// however, it works only if the fiber was created with [fiber.new()](#method.new) and was made joinable with /// [fiber.set_joinable()](#method.set_joinable). /// /// The fiber must n...
/// - `None` - the latch is locked.
random_line_split
fiber.rs
fiber.cancel()](struct.Fiber.html#method.cancel) sends an asynchronous wakeup event to the fiber, /// and [is_cancelled()](fn.is_cancelled.html) is checked whenever such a wakeup event occurs. /// /// Example: /// ```rust /// use tarantool::fiber::Fiber; /// let mut fiber = Fiber::new("test_fiber", &mut |_| { /// p...
{ unsafe { ffi::fiber_wakeup(self.inner) } } /// Wait until the fiber is dead and then move its execution status to the caller. /// /// “Join” a joinable fiber. That is, let the fiber’s function run and wait until the fiber’s status is **dead** /// (normally a status becomes **dead** when ...
&self)
identifier_name
fiber.rs
able). /// /// The fiber must not be detached (See also: [fiber.set_joinable()](#method.set_joinable)). /// /// Return: fiber function return code pub fn join(&self) -> i32 { unsafe { ffi::fiber_join(self.inner) } } /// Set fiber to be joinable (false by default). /// /// - ...
e } } } impl Dr
conditional_block
fiber.rs
} /// Create a new fiber with defined attributes. /// /// Can fail only if there is not enough memory for the fiber structure or fiber stack. /// /// The created fiber automatically returns itself to the fiber cache if has default stack size /// when its `main` function completes. The initi...
{ ffi::fiber_cond_broadcast(self.inner) } } /// Suspend
identifier_body
renderer.js
mongodPath; }; const TESS_HOME = path.join(os.homedir(), "tesserae"); // application home const MONGOD_PATH = getMongodPath(); const MONGORESTORE_PATH = getMongorestorePath(); const MONGODB_DBPATH = path.join(TESS_HOME, "tessdb"); /** * Initialize the loading screen * @returns {Promise<null>} * * The loading sc...
}; /** * Write an error message to the loading screen * @param {string} msg an error message to display on the loading screen * @param {*} err the error object that was thrown * * If an error occurs during application initialization, all resources the * application has taken so far should be freed, the error s...
{ startupWindow.webContents.send('update', msg); }
conditional_block
renderer.js
return mongodPath; }; const TESS_HOME = path.join(os.homedir(), "tesserae"); // application home const MONGOD_PATH = getMongodPath(); const MONGORESTORE_PATH = getMongorestorePath(); const MONGODB_DBPATH = path.join(TESS_HOME, "tessdb"); /** * Initialize the loading screen * @returns {Promise<null>} * * The loa...
// startupWindow.webContents.openDevTools(); startupWindow.on("closed", () => { startupWindow = null }); startupWindow.webContents.once("dom-ready", (event, msg) => { resolve(); }); }); }; /** * @param {string} msg a message to display on the loading screen */ const writeStartupMess...
preload: path.join(__dirname, "preloadStartup.js") } }); startupWindow.loadFile(path.join(__dirname, "startup.html"));
random_line_split
sampleMultiMCTSAgentTrajectory.py
Buffer import SampleBatchFromBuffer, SaveToBuffer from exec.preProcessing import AccumulateMultiAgentRewards, AddValuesToTrajectory, RemoveTerminalTupleFromTrajectory, \ ActionToOneHot, ProcessTrajectoryForPolicyValueNet from src.algorithms.mcts import ScoreChild, SelectChild, InitializeChildren, Expand, MCTS, back...
def main(): #check file exists or not dirName = os.path.dirname(__file__) trajectoriesSaveDirectory = os.path.join(dirName, '..', '..', 'data', 'multiAgentTrain', 'multiMCTSAgent', 'trajectories') if not os.path.exists(trajectoriesSaveDirectory): o...
def __init__(self, composeSingleAgentGuidedMCTS, approximatePolicy, MCTSAgentIds): self.composeSingleAgentGuidedMCTS = composeSingleAgentGuidedMCTS self.approximatePolicy = approximatePolicy self.MCTSAgentIds = MCTSAgentIds def __call__(self, multiAgentNNModel): multiAgentApproximat...
identifier_body
sampleMultiMCTSAgentTrajectory.py
Buffer import SampleBatchFromBuffer, SaveToBuffer from exec.preProcessing import AccumulateMultiAgentRewards, AddValuesToTrajectory, RemoveTerminalTupleFromTrajectory, \ ActionToOneHot, ProcessTrajectoryForPolicyValueNet from src.algorithms.mcts import ScoreChild, SelectChild, InitializeChildren, Expand, MCTS, back...
(self, multiAgentNNModel): multiAgentApproximatePolicy = np.array([self.approximatePolicy(NNModel) for NNModel in multiAgentNNModel]) otherAgentPolicyForMCTSAgents = np.array([np.concatenate([multiAgentApproximatePolicy[:agentId], multiAgentApproximatePolicy[agentId + 1:]]) ...
__call__
identifier_name