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 |
|---|---|---|---|---|
lib.rs | //! ## clickhouse-rs
//! Asynchronous [Yandex ClickHouse](https://clickhouse.yandex/) client library for rust programming language.
//!
//! ### Installation
//! Library hosted on [crates.io](https://crates.io/crates/clickhouse-rs/).
//!
//! ```toml
//! [dependencies]
//! clickhouse-rs = "*"
//! ```
//!
//! ### Supporte... | ns: Options) -> Result<ClientHandle> {
let source = options.into_options_src();
Self::open(source, None).await
}
pub(crate) async fn open(source: OptionsSource, pool: Option<Pool>) -> Result<ClientHandle> {
let options = try_opt!(source.get());
let compress = options.compression... | t(optio | identifier_name |
lib.rs | //! ## clickhouse-rs
//! Asynchronous [Yandex ClickHouse](https://clickhouse.yandex/) client library for rust programming language.
//!
//! ### Installation
//! Library hosted on [crates.io](https://crates.io/crates/clickhouse-rs/).
//!
//! ```toml
//! [dependencies]
//! clickhouse-rs = "*"
//! ```
//!
//! ### Supporte... |
/// Check connection and try to reconnect if necessary.
pub async fn check_connection(&mut self) -> Result<()> {
self.pool.detach();
let source = self.context.options.clone();
let pool = self.pool.clone();
let (send_retries, retry_timeout) = {
let options = try_op... | Box::pin(f(self))
}
} | conditional_block |
git_ftp.js | /*
* grunt-git-ftp
* https://github.com/robertomarte/grunt-git-ftp
*
* Copyright (c) 2013 Roberto Carlos Marte
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt){
//Extend array function, remove matching values from array
Array.prototype.remove = function(deleteMatchingValues... |
log.ok('Uploaded from: ' + filepath + ' >> ' + host.blue + '@' + path.normalize(remoteRootPath + '/' + filepath).green);
ftp.end();
nextArray();
});
},function(err){
cb(null);
});
}else{
cb(true,'error while uploading file');... | {
cb(true,err);
throw err;
} | conditional_block |
git_ftp.js | /*
* grunt-git-ftp
* https://github.com/robertomarte/grunt-git-ftp
*
* Copyright (c) 2013 Roberto Carlos Marte
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt){
//Extend array function, remove matching values from array
Array.prototype.remove = function(deleteMatchingValues... | gruntGitFtpApp.localDirectories[path.normalize(path.dirname(remoteRootPath + '/' + filepath) + '/')] = null;
//only return file OR files that start with (.)
return (path.extname(filepath) || filepath[0] === '.' ? true : false);
}else{
... | random_line_split | |
main.rs | //! A cargo subcommand for displaying line counts of source code in projects,
//! including a niave `unsafe` counter for Rust source files. This subcommand
//! was originally based off and inspired by the project
//! [tokei](https://github.com/aaronepower/tokei) by
//! [Aaronepower](https://github.com/aaronepower)
//!
... |
fn single_char(s: String) -> Result<(), String> {
if s.len() == 1 {
Ok(())
} else {
Err(format!(
"the --separator argument option only accepts a single character but found '{}'",
Format::Warning(s)
))
}
}
| {
debugln!("executing; cmd=execute;");
verboseln!(cfg, "{}: {:?}", Format::Warning("Excluding"), cfg.exclude);
verbose!(
cfg,
"{}",
if cfg.exts.is_some() {
format!(
"{} including files with extension: {}\n",
Format::Warning("Only"),
... | identifier_body |
main.rs | //! A cargo subcommand for displaying line counts of source code in projects,
//! including a niave `unsafe` counter for Rust source files. This subcommand
//! was originally based off and inspired by the project
//! [tokei](https://github.com/aaronepower/tokei) by
//! [Aaronepower](https://github.com/aaronepower)
//!
... | extern crate clap;
#[cfg(feature = "color")]
extern crate ansi_term;
extern crate gitignore;
extern crate glob;
extern crate regex;
extern crate tabwriter;
#[cfg(feature = "debug")]
use std::env;
use clap::{App, AppSettings, Arg, SubCommand};
use config::Config;
use count::Counts;
use error::{CliError, CliResult};
u... | )]
#[macro_use] | random_line_split |
main.rs | //! A cargo subcommand for displaying line counts of source code in projects,
//! including a niave `unsafe` counter for Rust source files. This subcommand
//! was originally based off and inspired by the project
//! [tokei](https://github.com/aaronepower/tokei) by
//! [Aaronepower](https://github.com/aaronepower)
//!
... | else {
Err(format!(
"the --separator argument option only accepts a single character but found '{}'",
Format::Warning(s)
))
}
}
| {
Ok(())
} | conditional_block |
main.rs | //! A cargo subcommand for displaying line counts of source code in projects,
//! including a niave `unsafe` counter for Rust source files. This subcommand
//! was originally based off and inspired by the project
//! [tokei](https://github.com/aaronepower/tokei) by
//! [Aaronepower](https://github.com/aaronepower)
//!
... | (s: String) -> Result<(), String> {
if s.len() == 1 {
Ok(())
} else {
Err(format!(
"the --separator argument option only accepts a single character but found '{}'",
Format::Warning(s)
))
}
}
| single_char | identifier_name |
route.rs | use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use proc_macro::{TokenStream, Span};
use crate::proc_macro2::TokenStream as TokenStream2;
use devise::{syn, Spanned, SpanWrapped, Result, FromMeta, ext::TypeExt};
use indexmap::IndexSet;
use crate::proc_macro_ext::{Diagnostics, StringLit};
... | #[allow(non_snake_case, unreachable_patterns, unreachable_code)]
let #ident: #ty = #expr;
}
}
fn data_expr(ident: &syn::Ident, ty: &syn::Type) -> TokenStream2 {
define_vars_and_mods!(req, data, FromData, Outcome, Transform);
let span = ident.span().unstable().join(ty.span()).unwrap().into()... | };
quote! { | random_line_split |
route.rs | use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use proc_macro::{TokenStream, Span};
use crate::proc_macro2::TokenStream as TokenStream2;
use devise::{syn, Spanned, SpanWrapped, Result, FromMeta, ext::TypeExt};
use indexmap::IndexSet;
use crate::proc_macro_ext::{Diagnostics, StringLit};
... | {
#[meta(naked)]
method: SpanWrapped<Method>,
path: RoutePath,
data: Option<SpanWrapped<DataSegment>>,
format: Option<MediaType>,
rank: Option<isize>,
}
/// The raw, parsed `#[method]` (e.g, `get`, `put`, `post`, etc.) attribute.
#[derive(Debug, FromMeta)]
struct MethodRouteAttribute {
#[m... | RouteAttribute | identifier_name |
route.rs | use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use proc_macro::{TokenStream, Span};
use crate::proc_macro2::TokenStream as TokenStream2;
use devise::{syn, Spanned, SpanWrapped, Result, FromMeta, ext::TypeExt};
use indexmap::IndexSet;
use crate::proc_macro_ext::{Diagnostics, StringLit};
... |
dup_check(&mut segments, attr.path.path.iter().cloned(), &mut diags);
attr.path.query.as_ref().map(|q| dup_check(&mut segments, q.iter().cloned(), &mut diags));
dup_check(&mut segments, attr.data.clone().map(|s| s.value.0).into_iter(), &mut diags);
// Check the validity of function arguments.
let... | {
for segment in iter.filter(|s| s.kind != Kind::Static) {
let span = segment.span;
if let Some(previous) = set.replace(segment) {
diags.push(span.error(format!("duplicate parameter: `{}`", previous.name))
.span_note(previous.span, "previous parameter ... | identifier_body |
sendmail.rs |
use libc;
use libc::alarm;
use libc::atoi;
use libc::free;
use libc::getenv;
use libc::getuid;
use libc::printf;
use libc::sleep;
use libc::strchr;
use libc::strcpy;
use libc::strrchr;
extern "C" {
#[no_mangle]
static ptr_to_globals: *mut globals;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
... |
unsafe extern "C" fn smtp_check(
mut fmt: *const libc::c_char,
mut code: libc::c_int,
) -> libc::c_int {
return smtp_checkp(fmt, 0 as *const libc::c_char, code);
}
// strip argument of bad chars
unsafe extern "C" fn sane_address(mut str: *mut libc::c_char) -> *mut libc::c_char {
let mut s: *mut libc::c_char = ... | {
let mut answer: *mut libc::c_char = 0 as *mut libc::c_char;
let mut msg: *mut libc::c_char = send_mail_command(fmt, param);
loop
// read stdin
// if the string has a form NNN- -- read next string. E.g. EHLO response
// parse first bytes to a number
// if code = -1 then just return this number
// if co... | identifier_body |
sendmail.rs |
use libc;
use libc::alarm;
use libc::atoi;
use libc::free;
use libc::getenv;
use libc::getuid;
use libc::printf;
use libc::sleep;
use libc::strchr;
use libc::strcpy;
use libc::strrchr;
extern "C" {
#[no_mangle]
static ptr_to_globals: *mut globals;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
... | else {
current_block = 228501038991332163;
}
loop {
match current_block {
228501038991332163 =>
// odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
// N.B. after reenter code will be > 0
{
if !(code == 0) {
... | {
current_block = 16252544171633782868;
} | conditional_block |
sendmail.rs |
use libc;
use libc::alarm;
use libc::atoi;
use libc::free;
use libc::getenv;
use libc::getuid;
use libc::printf;
use libc::sleep;
use libc::strchr;
use libc::strcpy;
use libc::strrchr;
extern "C" {
#[no_mangle]
static ptr_to_globals: *mut globals;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
... | (mut list: *const libc::c_char) {
let mut free_me: *mut libc::c_char = xstrdup(list);
let mut str: *mut libc::c_char = free_me;
let mut s: *mut libc::c_char = free_me;
let mut prev: libc::c_char = 0i32 as libc::c_char;
let mut in_quote: libc::c_int = 0i32;
while *s != 0 {
let fresh0 = s;
s = s.offse... | rcptto_list | identifier_name |
sendmail.rs | use libc;
use libc::alarm;
use libc::atoi;
use libc::free;
use libc::getenv;
use libc::getuid;
use libc::printf;
use libc::sleep;
use libc::strchr;
use libc::strcpy;
use libc::strrchr;
extern "C" {
#[no_mangle]
static ptr_to_globals: *mut globals;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
s... | {
rcptto_list(s.offset(4));
free(s as *mut libc::c_void);
last_hdr = HDR_BCC;
continue 's_369;
// Bcc: header adds blind copy (hidden) recipient
// N.B. Bcc: vanishes from headers!
}
}... | b"Bcc:\x00" as *const u8 as *const libc::c_char,
s,
4i32 as libc::c_ulong,
) | random_line_split |
replicaset.go | package experiments
import (
"context"
"encoding/json"
"fmt"
"time"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
patchtypes "k8s... | (rs *appsv1.ReplicaSet, newScale int32, scalingOperation string) (bool, *appsv1.ReplicaSet, error) {
ctx := context.TODO()
oldScale := *(rs.Spec.Replicas)
sizeNeedsUpdate := oldScale != newScale
scaled := false
var err error
if sizeNeedsUpdate {
rsCopy := rs.DeepCopy()
*(rsCopy.Spec.Replicas) = newScale
rs,... | scaleReplicaSet | identifier_name |
replicaset.go | package experiments
import (
"context"
"encoding/json"
"fmt"
"time"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors" | "github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
"github.com/argoproj/argo-rollouts/utils/conditions"
"github.com/argoproj/argo-rollouts/utils/defaults"
experimentutil "github.com/argoproj/argo-rollouts/utils/experiment"
"github.com/argoproj/argo-rollouts/utils/hash"
logutil "github.com/argoproj/arg... | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
patchtypes "k8s.io/apimachinery/pkg/types"
labelsutil "k8s.io/kubernetes/pkg/util/labels"
| random_line_split |
replicaset.go | package experiments
import (
"context"
"encoding/json"
"fmt"
"time"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
patchtypes "k8s... |
func newReplicaSetAnnotations(experimentName, templateName string) map[string]string {
return map[string]string{
v1alpha1.ExperimentNameAnnotationKey: experimentName,
v1alpha1.ExperimentTemplateNameAnnotationKey: templateName,
}
}
| {
ctx := context.TODO()
oldScale := *(rs.Spec.Replicas)
sizeNeedsUpdate := oldScale != newScale
scaled := false
var err error
if sizeNeedsUpdate {
rsCopy := rs.DeepCopy()
*(rsCopy.Spec.Replicas) = newScale
rs, err = ec.kubeclientset.AppsV1().ReplicaSets(rsCopy.Namespace).Update(ctx, rsCopy, metav1.UpdateOpt... | identifier_body |
replicaset.go | package experiments
import (
"context"
"encoding/json"
"fmt"
"time"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
patchtypes "k8s... |
if templateDefined(templateName) {
templateToRS[templateName] = rs
logCtx := log.WithField(logutil.ExperimentKey, experiment.Name).WithField(logutil.NamespaceKey, experiment.Namespace)
logCtx.Infof("Claimed ReplicaSet '%s' for template '%s'", rs.Name, templateName)
}
}
}
return templateToRS, nil... | {
return nil, fmt.Errorf("multiple ReplicaSets match single experiment template: %s", templateName)
} | conditional_block |
TongitzApi.ts | //helper
import mapper = require("../tongitz.common/mapper")
//services
import {TongitzService,ITongitzService} from "../tongitz.services/TongitzService"
//models.resource
import resource = require("../tongitz.models/resource/_resource")
//models.domain
import domain = require("../tongitz.models/domain/_domain")
//mo... | let gameDiscards = this._svc.getDiscards(gameId);
proposedHand.push(gameDiscards[gameDiscards.length-1]);//last discard
gamePlayer.hand.filter(x => playerCardIds.indexOf(x.id) != -1).forEach(x => proposedHand.push(x));//hand card to combine
// playerCardIds.map(x => gamePlayer.hand[game... | //get lastDiscard as card | random_line_split |
TongitzApi.ts | //helper
import mapper = require("../tongitz.common/mapper")
//services
import {TongitzService,ITongitzService} from "../tongitz.services/TongitzService"
//models.resource
import resource = require("../tongitz.models/resource/_resource")
//models.domain
import domain = require("../tongitz.models/domain/_domain")
//mo... | (gameId?:number,...p: string[]) : void//: gameStateResource {
{
gameId = gameId || 1;
if(p.length < 2 || p.length > 3) throw "500","error";
//set gameId, turn, phase
this._svc.addGame(gameId,1,domain.turnPhaseEnum.play);
//make players, set name,turn,id , store in var
... | NewGame | identifier_name |
TongitzApi.ts | //helper
import mapper = require("../tongitz.common/mapper")
//services
import {TongitzService,ITongitzService} from "../tongitz.services/TongitzService"
//models.resource
import resource = require("../tongitz.models/resource/_resource")
//models.domain
import domain = require("../tongitz.models/domain/_domain")
//mo... |
public Play(gameId:number, playerId: number, playCards: resource.playRequestResource){
this.validateGameOnGoing(this._svc.getWinMethod(gameId));
//discard is required
if(!(playCards ? !isNaN(playCards.discard) ? true : false : false))
return;
let gameTurn = this._s... | {
this.validateGameOnGoing(this._svc.getWinMethod(gameId));
if(playerCardIds.length < 2) //check if there are at least 2 cards
{
throw "badRequest:can't form a house with less than 3 cards"
}
let gameTurn = this._svc.getTurn(gameId);
let gamePhase = this._svc.... | identifier_body |
TongitzApi.ts | //helper
import mapper = require("../tongitz.common/mapper")
//services
import {TongitzService,ITongitzService} from "../tongitz.services/TongitzService"
//models.resource
import resource = require("../tongitz.models/resource/_resource")
//models.domain
import domain = require("../tongitz.models/domain/_domain")
//mo... |
this._svc.applyState(gameId);
}
public Play(gameId:number, playerId: number, playCards: resource.playRequestResource){
this.validateGameOnGoing(this._svc.getWinMethod(gameId));
//discard is required
if(!(playCards ? !isNaN(playCards.discard) ? true : false : false))
... | {
this._svc.setWinner(gameId,playerId,domain.winMethodEnum.noHand);
} | conditional_block |
cookie_article_parser.py | from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import time
import datetime
import re
import argparse
# Without this we get an error"ascii codec cant encode charact... |
def load_creds_login():
fname="wsjcreds.dat"
f = open(fname,"r")
uname = f.readline().split(' ')[1]
pw = f.readline().split(' ')[1]
f.close()
# Input username
loginID = browser.find_element_by_id("username").send_keys(uname)
# Input password
loginPass = browser.find_el... | db.close() | identifier_body |
cookie_article_parser.py | from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import time
import datetime
import re
import argparse
# Without this we get an error"ascii codec cant encode charact... | ():
options = Options()
#options.add_argument("--headless")
browser = webdriver.Firefox(firefox_options=options, executable_path='/home/shelbyt/geckodriver')
return browser
def profile_comment_load(browser):
#for i in range(0,3):
# print "range"
# load_more = browser.find_element_... | sel_init | identifier_name |
cookie_article_parser.py | from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import time
import datetime
import re
import argparse
# Without this we get an error"ascii codec cant encode charact... |
return len(profile_url)
def insert_article_user_comments(browser, db, cursor):
login_flag = 0
for profile in profile_url:
print "Trying to load = " + profile
browser.get(profile)
if login_flag == 0:
load_creds_login()
login_flag = 1
profile_comment... | if user not in profile_url:
# Get the actual users profile url here
# TODO(shelbyt): Fix bad naming user is a userblock
match = re.search('.*\/(.*)\?',user.get_attribute("href"))
# Returns a user_id which we can match with the database list
article_user_id = s... | conditional_block |
cookie_article_parser.py | from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import time
import datetime
import re
import argparse
# Without this we get an error"ascii codec cant encode charact... | db_date = datetime.datetime(int(real_t_arr[2]),
int(month_to_num(real_t_arr[0])),int(real_t_arr[1])).date().strftime("%Y-%m-%d")
db_time=t_format
# without this str encoding i get a 'latin-1 codec cant encode character'
# use ascii ignore to remove any weird characters
... | ################## INSERT EVERYTHING INTO THE GLOBAL DB STRINGS ##############
# just use the date part of date_time | random_line_split |
pylon.go | /*
A simple reverse proxy and load balancer
supported balancing strategies:
- Round Robin
- Random
- Least Connected
Example of a json config:
{
"servers": [
{
"name": "server1",
"port": 7777,
"services": [
{
"route_prefix": "/microservice/",
"... | // Least Connected returns the least loaded instance, which is
// computed by the current request count divided by the weight of the instance
func getLeastConInstIdx(instances []*Instance) int {
minLoad := maxFloat32
idx := 0
for i, inst := range instances {
if inst == nil {
continue
}
load := fl... | random_line_split | |
pylon.go | /*
A simple reverse proxy and load balancer
supported balancing strategies:
- Round Robin
- Random
- Least Connected
Example of a json config:
{
"servers": [
{
"name": "server1",
"port": 7777,
"services": [
{
"route_prefix": "/microservice/",
"... |
if idx >= instCount {
idx = 0
}
}
return idx, nil
}
// getLeastConInstIdx returns the index of the Instance that should be
// picked according to the least connected rules and a given slice of Instance
// Least Connected returns the least loaded instance, which is
// computed by the current reques... | {
if lastNonNil != -1 {
return lastNonNil, nil
}
return -1, ErrFailedRoundRobin
} | conditional_block |
pylon.go | /*
A simple reverse proxy and load balancer
supported balancing strategies:
- Round Robin
- Random
- Least Connected
Example of a json config:
{
"servers": [
{
"name": "server1",
"port": 7777,
"services": [
{
"route_prefix": "/microservice/",
"... |
// getRandomInstIdx returns the index of an Instance that is picked
// Randomly from the given slice of Instance. Weights of Instances
// are taken into account
func getRandomInstIdx(instances []*Instance) int {
var weightSum float32 = 0.0
for _, inst := range instances {
if inst == nil {
continue
... | {
minLoad := maxFloat32
idx := 0
for i, inst := range instances {
if inst == nil {
continue
}
load := float32(len(inst.ReqCount)) / inst.Weight
if load < minLoad {
minLoad = load
idx = i
}
}
return idx
} | identifier_body |
pylon.go | /*
A simple reverse proxy and load balancer
supported balancing strategies:
- Round Robin
- Random
- Least Connected
Example of a json config:
{
"servers": [
{
"name": "server1",
"port": 7777,
"services": [
{
"route_prefix": "/microservice/",
"... | () RouteType {
return Prefix
}
func (p PrefixRoute) Data() interface{} {
return p.Prefix
}
// ListenAndServe tries to parse the config at the given path and serve it
func ListenAndServe(p string) error {
jsonParser := JSONConfigParser{}
c, err := jsonParser.ParseFromPath(p)
if err != nil {
return ... | Type | identifier_name |
trial_purpose.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
trialPurpose
A QGIS plugin
tp
-------------------
begin : 2019-04-20
git sha : $Format:%H$
copyrig... |
def onClickBtn3(self):
# Reuse the path to DB to set database name
uri = QgsDataSourceURI()
uri.setDatabase('F:/UTA/SEM 5/Adv DB/UTA_Final_DB/test.sqlite')
db = QSqlDatabase.addDatabase('QSPATIALITE');
db.setDatabaseName(uri.database())
FromL = self.dlg.q3combo1.current... | return shortest
| random_line_split |
trial_purpose.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
trialPurpose
A QGIS plugin
tp
-------------------
begin : 2019-04-20
git sha : $Format:%H$
copyrig... | (self):
print('onClickBtn2')
aptName = self.dlg.q2combo.currentText()
# Reuse the path to DB to set database name
uri = QgsDataSourceURI()
uri.setDatabase('F:/UTA/SEM 5/Adv DB/UTA_Final_DB/test.sqlite')
db = QSqlDatabase.addDatabase('QSPATIALITE');
... | onClickBtn2 | identifier_name |
trial_purpose.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
trialPurpose
A QGIS plugin
tp
-------------------
begin : 2019-04-20
git sha : $Format:%H$
copyrig... |
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path ... | """Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspe... | identifier_body |
trial_purpose.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
trialPurpose
A QGIS plugin
tp
-------------------
begin : 2019-04-20
git sha : $Format:%H$
copyrig... |
def find_shortest_path(self,graph, start, end, path =[]):
path = path + [start]
if start == end:
return path
shortest = None
for node in graph[start]:
if node not in path:
newpath = self.find_shortest_path(graph, node, end, path)
... | query = db.exec_("Select id from Final_poly where name='{0}'".format(aptName));
while query.next():
record = query.record()
myList.append(record.value(0))
print(myList)
selectedLayerIndex = "final_poly"
self.iface.setActiveLayer(QgsMapLaye... | conditional_block |
key_bundle_v2.go | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package kbfsmd
import (
"fmt"
"github.com/keybase/client/go/kbfs/kbfscodec"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/protocol/k... | () DevicePublicKeys {
publicKeys := make(DevicePublicKeys, len(dkimV2))
for kid := range dkimV2 {
publicKeys[kbfscrypto.MakeCryptPublicKey(kid)] = true
}
return publicKeys
}
// UserDeviceKeyInfoMapV2 maps a user's keybase UID to their
// DeviceKeyInfoMapV2.
type UserDeviceKeyInfoMapV2 map[keybase1.UID]DeviceKeyI... | toPublicKeys | identifier_name |
key_bundle_v2.go | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package kbfsmd
import (
"fmt"
"github.com/keybase/client/go/kbfs/kbfscodec"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/protocol/k... | }
return wkbV2, wkbV3, nil
}
// TLFReaderKeyBundleV2 stores all the reader keys with reader
// permissions on a TLF.
type TLFReaderKeyBundleV2 struct {
RKeys UserDeviceKeyInfoMapV2
// M_e as described in § 4.1.1. Because devices can be added
// into the key generation after it is initially created (so
// those... | if err != nil {
return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{}, err
} | random_line_split |
key_bundle_v2.go | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package kbfsmd
import (
"fmt"
"github.com/keybase/client/go/kbfs/kbfscodec"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/protocol/k... | / IsReader returns whether or not the user+device is an authorized reader
// for the latest generation.
func (rkg TLFReaderKeyGenerationsV2) IsReader(user keybase1.UID, deviceKey kbfscrypto.CryptPublicKey) bool {
keyGen := rkg.LatestKeyGeneration()
if keyGen < 1 {
return false
}
return rkg[keyGen-1].IsReader(user... | return KeyGen(len(rkg))
}
/ | identifier_body |
key_bundle_v2.go | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package kbfsmd
import (
"fmt"
"github.com/keybase/client/go/kbfs/kbfscodec"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/protocol/k... | infoCopy.EPubKeyIndex = newIndex
case ReaderEPubKeys:
// Use the real index in the reader list.
infoCopy.EPubKeyIndex = index
default:
return TLFReaderKeyBundleV3{}, fmt.Errorf("Unknown key location %s", keyLocation)
}
dkimV3[kbfscrypto.MakeCryptPublicKey(kid)] = infoCopy
}
rkbV3.Keys[uid]... | rkbV3.TLFEphemeralPublicKeys =
append(rkbV3.TLFEphemeralPublicKeys, ePubKey)
// TODO: This index depends on
// map iteration order, which
// varies. Impose a consistent
// order on these indices.
newIndex = len(rkbV3.TLFEphemeralPublicKeys) - 1
pubKeyIndicesMap[index] = newIndex
... | conditional_block |
redisstore.go | package modules
import (
"github.com/garyburd/redigo/redis"
"github.com/pnegahdar/sporedock/types"
"github.com/pnegahdar/sporedock/utils"
"strings"
"sync"
"time"
)
const CheckinEveryMs = 1000 //Delta between these two indicate how long it takes for something to be considered gone.
const CheckinExpireMs = 5000
c... | }
}()
exit, _ := sm.Exit.Listen()
for {
select {
case <-exit:
return
case dat := <-data:
switch v := dat.(type) {
case redis.Message:
go func() {
select {
case sm.Messages <- string(v.Data):
default:
return
}
}()
case redis.Subscription:
co... | return
} | random_line_split |
redisstore.go | package modules
import (
"github.com/garyburd/redigo/redis"
"github.com/pnegahdar/sporedock/types"
"github.com/pnegahdar/sporedock/utils"
"strings"
"sync"
"time"
)
const CheckinEveryMs = 1000 //Delta between these two indicate how long it takes for something to be considered gone.
const CheckinExpireMs = 5000
c... | (server string) *redis.Pool {
return &redis.Pool{
MaxIdle: 10,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do(... | newRedisConnPool | identifier_name |
redisstore.go | package modules
import (
"github.com/garyburd/redigo/redis"
"github.com/pnegahdar/sporedock/types"
"github.com/pnegahdar/sporedock/utils"
"strings"
"sync"
"time"
)
const CheckinEveryMs = 1000 //Delta between these two indicate how long it takes for something to be considered gone.
const CheckinExpireMs = 5000
c... |
func (rs RedisStore) typeKey(runContext *types.RunContext, v interface{}, parts ...string) string {
meta, err := types.NewMeta(v)
utils.HandleError(err)
parts = append([]string{meta.TypeName}, parts...)
return rs.keyJoiner(runContext, parts...)
}
func (rs *RedisStore) runLeaderElection() {
config := rs.runConte... | {
items := append(runContext.NamespacePrefixParts(), parts...)
return strings.Join(items, ":")
} | identifier_body |
redisstore.go | package modules
import (
"github.com/garyburd/redigo/redis"
"github.com/pnegahdar/sporedock/types"
"github.com/pnegahdar/sporedock/utils"
"strings"
"sync"
"time"
)
const CheckinEveryMs = 1000 //Delta between these two indicate how long it takes for something to be considered gone.
const CheckinExpireMs = 5000
c... |
wasSet, err := redis.Int(conn.Do(op, typeKey, id, data))
if err != nil {
return wrapError(err)
}
if wasSet == 1 || update {
meta, err := types.NewMeta(v)
utils.HandleError(err)
action := types.StoreActionUpdate
if !update {
action = types.StoreActionCreate
}
types.StoreEvent(action, meta).EmitAll(... | {
op = "HSETNX"
} | conditional_block |
InteractiveFormsTest.go | //---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
package main
... | else{
fmt.Println("Field search failed")
}
// Regenerate field appearances.
doc.RefreshFieldAppearances()
doc.Save(outputPath + "forms_test_edit.pdf", uint(0))
doc.Close()
fmt.Println("Done.")
//----------------------------------------------------------------------------------... | {
fmt.Println("Field search for " + f.GetName() + " was successful")
} | conditional_block |
InteractiveFormsTest.go | //---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
package main
... | (){
PDFNetInitialize()
// The map (vector) used to store the name and count of all fields.
// This is used later on to clone the fields
fieldNames:= make(map[string]int)
//----------------------------------------------------------------------------------
// Example 1: Programatically create ne... | main | identifier_name |
InteractiveFormsTest.go | //---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
package main
... | radiobutton1.RefreshAppearance()
radiobutton2 := radioGroup.Add(NewRect(310.0, 410.0, 360.0, 460.0))
radiobutton2.SetBackgroundColor(NewColorPt(0.0, 1.0, 0.0), 3)
radiobutton2.RefreshAppearance()
radiobutton3 := radioGroup.Add(NewRect(480.0, 410.0, 530.0, 460.0))
// Enable the third radio button... | // RadioButton Widget Creation
// Create a radio button group and Add three radio buttons in it.
radioGroup := RadioButtonGroupCreate(doc, "RadioGroup")
radiobutton1 := radioGroup.Add(NewRect(140.0, 410.0, 190.0, 460.0))
radiobutton1.SetBackgroundColor(NewColorPt(1.0, 1.0, 0.0), 3) | random_line_split |
InteractiveFormsTest.go | //---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
package main
... |
func main(){
PDFNetInitialize()
// The map (vector) used to store the name and count of all fields.
// This is used later on to clone the fields
fieldNames:= make(map[string]int)
//----------------------------------------------------------------------------------
// Example 1: Programatic... | {
// Create a button appearance stream ------------------------------------
build := NewElementBuilder()
writer := NewElementWriter()
writer.Begin(doc.GetSDFDoc())
// Draw background
element := build.CreateRect(0.0, 0.0, 101.0, 37.0)
element.SetPathFill(true)
element.SetPathStroke(f... | identifier_body |
agollo.go | package agollo
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"sync"
"time"
)
var (
defaultConfigFilePath = "app.properties"
defaultConfigType = "properties"
defaultNotificationID = -1
defaultWatchTimeout = 500 * time.Millisecond
defaultAgollo Agollo
)
type Ago... | err
}
return notifications, nil
}
func (a *agollo) getLocalNotifications() []Notification {
var notifications []Notification
a.notificationMap.Range(func(key, val interface{}) bool {
k, _ := key.(string)
v, _ := val.(int)
notifications = append(notifications, Notification{
NamespaceName: k,
Notifica... | req, "ServerResponseStatus", status,
"Error", err, "Action", "LongPoll")
return nil, | conditional_block |
agollo.go | package agollo
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"sync"
"time"
)
var (
defaultConfigFilePath = "app.properties"
defaultConfigType = "properties"
defaultNotificationID = -1
defaultWatchTimeout = 500 * time.Millisecond
defaultAgollo Agollo
)
type Ago... |
func Init(configServerURL, appID string, opts ...Option) (err error) {
defaultAgollo, err = New(configServerURL, appID, opts...)
return
}
func InitWithConfigFile(configFilePath string, opts ...Option) (err error) {
defaultAgollo, err = NewWithConfigFile(configFilePath, opts...)
return
}
func InitWithDefaultConfi... | random_line_split | |
agollo.go | package agollo
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"sync"
"time"
)
var (
defaultConfigFilePath = "app.properties"
defaultConfigType = "properties"
defaultNotificationID = -1
defaultWatchTimeout = 500 * time.Millisecond
defaultAgollo Agollo
)
type Ago... | : notifications,
Namespace: namespace,
Err: err,
}
select {
case a.errorsCh <- longPollerError:
default:
}
}
func (a *agollo) log(kvs ...interface{}) {
a.opts.Logger.Log(
append([]interface{}{
"[Agollo]", "",
"AppID", a.opts.AppID,
"Cluster", a.opts.Cluster,
},
kvs...,
... | RL有点蛋疼
func (a *agollo) sendErrorsCh(configServerURL string, notifications []Notification, namespace string, err error) {
longPollerError := &LongPollerError{
ConfigServerURL: configServerURL,
AppID: a.opts.AppID,
Cluster: a.opts.Cluster,
Notifications | identifier_body |
agollo.go | package agollo
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"sync"
"time"
)
var (
defaultConfigFilePath = "app.properties"
defaultConfigType = "properties"
defaultNotificationID = -1
defaultWatchTimeout = 500 * time.Millisecond
defaultAgollo Agollo
)
type Ago... | identifier_name | ||
main.js | // Global variables
var stages = {};
var groups = {};
var stadiums = {};
var matches = {};
//Months
var monthsEN = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var monthsPT = ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ"];
$(document).rea... | element.append($match);
}
}
//Dialog
function messageDialog(type, message) {
switch(type) {
case "success":
$("#dialog-message")
.removeClass("error")
.text(message)
.addClass("success");
$(".bs-example-modal-sm").modal("show");
break;
case "error":
$("#dialog-message")
.removeClass("success"... | random_line_split | |
main.js | // Global variables
var stages = {};
var groups = {};
var stadiums = {};
var matches = {};
//Months
var monthsEN = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var monthsPT = ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ"];
$(document).rea... |
}
}
function initializeInput(input, isValid) {
if (input.parent().parent().parent().children().hasClass("error")) {
if (isValid) {
input.parent().addClass("has-success");
input.siblings().fadeIn();
} else {
input.parent().prev().show();
input.parent().addClass('has-error');
input.siblings().fadeO... | {
input.parent().prev().html(message);
input.parent().prev().fadeIn();
} | conditional_block |
main.js | // Global variables
var stages = {};
var groups = {};
var stadiums = {};
var matches = {};
//Months
var monthsEN = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var monthsPT = ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ"];
$(document).rea... |
// Returns boolean whether the input has the minimum size required
function inBounds(actual, min) {
if (actual < min)
return false;
else
return true;
}
function confirmPass(actual, current) {
if (actual != current || current == "")
return false;
else
return true;
}
//Fills options with flags only
funct... | {
if (input.parent().parent().parent().children().hasClass("error")) {
if (isValid) {
input.parent().addClass("has-success");
input.siblings().fadeIn();
} else {
input.parent().prev().show();
input.parent().addClass('has-error');
input.siblings().fadeOut();
}
}
} | identifier_body |
main.js | // Global variables
var stages = {};
var groups = {};
var stadiums = {};
var matches = {};
//Months
var monthsEN = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var monthsPT = ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ"];
$(document).rea... | (element) {
var ddData = [];
for (var i in teams) {
if (teams[i].id == 7)
ddData.push( { text: teams[i].name, value: teams[i].id, imageSrc: "assets/images/external/flags/" + teams[i].logo, selected: true } );
else
ddData.push( { text: teams[i].name, value: teams[i].id, imageSrc: "assets/images/external/fla... | teamOptionLabel | identifier_name |
atm.py | # TUGAS BESAR KU1102 PENGENALAN KOMPUTASI 2019/2020 - PROGRAM ATM
# 16519097 Reynaldo Averill
# 16519117 Allief Nuriman
# 16519207 Theodore Maximillan Jonathan
# 16519217 Mohammad Sheva
# PROGRAM SIMULASI_ATM
# Deksripsi : Program akan mensimulasikan ATM
# KAMUS
# jumlahorang, jeniskartu, regisulang, ModeT... | # Pembayaran listrik, air, pendidikan, pulsa(Allief Nuriman)
elif transaksi == 2 :
print("1. Listrik")
print("2. Air")
print("3. Pendidikan")
print("4. Pulsa")
tujuantrf = int(input("Masukkan kode tujuan transfer : "))
#Pembayaran Listrik
if tujuantrf == 1 :
norek = int(input("Silakan masuk... | print(history[indeksorang][i][j],end=' | ' )
print()
| random_line_split |
atm.py | # TUGAS BESAR KU1102 PENGENALAN KOMPUTASI 2019/2020 - PROGRAM ATM
# 16519097 Reynaldo Averill
# 16519117 Allief Nuriman
# 16519207 Theodore Maximillan Jonathan
# 16519217 Mohammad Sheva
# PROGRAM SIMULASI_ATM
# Deksripsi : Program akan mensimulasikan ATM
# KAMUS
# jumlahorang, jeniskartu, regisulang, ModeT... | (data):
#Registrasi digunakan untuk menambahkan user baru pada database
#KAMUS LOKAL
#databaru : array of integer
#ALGORITMA FUNGSI
databaru=[0 for i in range (3)]
databaru[0]=input('Masukkan nama: ')
databaru[1]=input('Masukkan PIN anda (Terdiri dari 6 digit angka): ')
while((databaru[1].isdigit()==False)or(... | registrasi | identifier_name |
atm.py | # TUGAS BESAR KU1102 PENGENALAN KOMPUTASI 2019/2020 - PROGRAM ATM
# 16519097 Reynaldo Averill
# 16519117 Allief Nuriman
# 16519207 Theodore Maximillan Jonathan
# 16519217 Mohammad Sheva
# PROGRAM SIMULASI_ATM
# Deksripsi : Program akan mensimulasikan ATM
# KAMUS
# jumlahorang, jeniskartu, regisulang, ModeT... |
# ALGORITMA UTAMA
jumlahorang=4
data=[[0 for j in range (3)] for i in range (jumlahorang)]
history=[[[0 for j in range (2)] for i in range (3)] for k in range(jumlahorang)]
atmbarunyala=True
#Kolom pertama berisi nama
#Kolom kedua berisi PIN
#Kolom ketiga berisi saldo
#Deklarasi database awal
data[0][0]='Theodore J... | print('Anda akan mengisi pulsa kartu',namakartu)
print('Pilih nominal yang anda inginkan')
print('1. 50.000')
print('2. 100.000')
print('3. 150.000')
print('4. 200.000')
kodepulsa=int(input())
print('Masukkan nomor HP Anda')
nohp=int(input())
for i in range (4):
if i+1==kodepulsa :
saldo=konfirmasipulsa(s... | identifier_body |
atm.py | # TUGAS BESAR KU1102 PENGENALAN KOMPUTASI 2019/2020 - PROGRAM ATM
# 16519097 Reynaldo Averill
# 16519117 Allief Nuriman
# 16519207 Theodore Maximillan Jonathan
# 16519217 Mohammad Sheva
# PROGRAM SIMULASI_ATM
# Deksripsi : Program akan mensimulasikan ATM
# KAMUS
# jumlahorang, jeniskartu, regisulang, ModeT... |
if(pinangkasemua==False)and (coba<2):
print('Pin harus berupa kombinasi dari 6 digit angka')
print('Silahkan masukkan ulang PIN anda')
elif((pinadadidatabase==False)and(coba<2)):
print('Pin anda salah, silahkan masukkan ulang PIN anda')
coba+=1
if((coba==3)and(pinangkasemua!=True)and(pinadadidat... | if(int(data[indeksorang][1])==int(pin)):
pinadadidatabase=True | conditional_block |
service.go | // Copyright 2022-2023 The NATS 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
return addEndpoint(g.service, name, endpointSubject, handler, options.metadata)
}
func (g *group) AddGroup(name string) Group {
parts := make([]string, 0, 2)
if g.prefix != "" {
parts = append(parts, g.prefix)
}
if name != "" {
parts = append(parts, name)
}
prefix := strings.Join(parts, ".")
return &grou... | {
endpointSubject = subject
} | conditional_block |
service.go | // Copyright 2022-2023 The NATS 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | service: s,
prefix: name,
}
}
// dispatch is responsible for calling any async callbacks
func (ac *asyncCallbacksHandler) run() {
for {
f := <-ac.cbQueue
if f == nil {
return
}
f()
}
}
// dispatch is responsible for calling any async callbacks
func (ac *asyncCallbacksHandler) push(f func()) {
ac.c... | }
func (s *service) AddGroup(name string) Group {
return &group{ | random_line_split |
service.go | // Copyright 2022-2023 The NATS 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | (endpointSubject, literalSubject string) bool {
subjectTokens := strings.Split(literalSubject, ".")
endpointTokens := strings.Split(endpointSubject, ".")
if len(endpointTokens) > len(subjectTokens) {
return false
}
for i, et := range endpointTokens {
if i == len(endpointTokens)-1 && et == ">" {
return true
... | matchEndpointSubject | identifier_name |
service.go | // Copyright 2022-2023 The NATS 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
// addVerbHandlers generates control handlers for a specific verb.
// Each request generates 3 subscriptions, one for the general verb
// affecting all services written with the framework, one that handles
// all services of a particular kind, and finally a specific service instance.
func (svc *service) addVerbHandle... | {
subjectTokens := strings.Split(literalSubject, ".")
endpointTokens := strings.Split(endpointSubject, ".")
if len(endpointTokens) > len(subjectTokens) {
return false
}
for i, et := range endpointTokens {
if i == len(endpointTokens)-1 && et == ">" {
return true
}
if et != subjectTokens[i] && et != "*" {... | identifier_body |
game_tree.rs | //! This file contains code that represents the GameState at any point
//! during the game, in a lazily-evaluated tree structure.
use crate::common::gamestate::GameState;
use crate::common::action::Move;
use std::collections::HashMap;
/// Represents an entire game of Fish, starting from the given GameState
/// passed ... | (&self) -> &GameState {
match self {
GameTree::Turn { state, .. } => state,
GameTree::End(state) => state,
}
}
/// Returns a mutable reference to the GameState of the current node of the GameTree
pub fn get_state_mut(&mut self) -> &mut GameState {
match self ... | get_state | identifier_name |
game_tree.rs | //! This file contains code that represents the GameState at any point
//! during the game, in a lazily-evaluated tree structure.
use crate::common::gamestate::GameState;
use crate::common::action::Move;
use std::collections::HashMap;
/// Represents an entire game of Fish, starting from the given GameState
/// passed ... | GameTree::Turn { valid_moves, .. } => {
valid_moves.get_mut(&move_).map(|lazy_game| lazy_game.get_evaluated())
},
GameTree::End(_) => None,
}
}
/// Returns the `GameTree` that would be produced as a result of taking the given Move.
/// If the move... | /// If the move is invalid (not in valid_moves or self is `End`) then None is returned
pub fn get_game_after_move(&mut self, move_: Move) -> Option<&mut GameTree> {
match self { | random_line_split |
game_tree.rs | //! This file contains code that represents the GameState at any point
//! during the game, in a lazily-evaluated tree structure.
use crate::common::gamestate::GameState;
use crate::common::action::Move;
use std::collections::HashMap;
/// Represents an entire game of Fish, starting from the given GameState
/// passed ... |
#[test]
fn test_new() {
// valid_moves generated correctly
// - have expected moves, check if same as generated
// starting gamestate is same as one passed to new
let game = start_game();
let mut valid_moves = game.get_state().get_valid_moves();
let mut expec... | {
let mut expected_valid_moves = vec![];
let state = game.get_state();
let occupied_tiles = state.get_occupied_tiles();
for penguin in state.current_player().penguins.iter() {
let current_tile = state.get_tile(penguin.tile_id.unwrap()).unwrap();
for tile in curre... | identifier_body |
fundvalue.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
import ast
import time
import json
import random
import decimal
import sqlite3
import logging
import datetime
import argparse
import requests
import operator
import contextlib
import collections
import concurrent.futures
import bs4
HEADERS = {
"A... | for kh, val in zip(
('holder_company', 'holder_individual', 'holder_internal'), row):
d_finfo[k][kh] = cfloat(val)
if js['ishb']:
jsgraph = js['Data_assetAllocationCurrency']
else:
jsgraph = js['Data_assetAllocation']
for k, row in zi... | 'data'] for r in jsgraph['series']))):
| conditional_block |
fundvalue.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
import ast
import time
import json
import random
import decimal
import sqlite3
import logging
import datetime
import argparse
import requests
import operator
import contextlib
import collections
import concurrent.futures
import bs4
HEADERS = {
"A... | (d):
keys, values = zip(*d.items())
return ' AND '.join(k + '=?' for k in keys), values
def update_partial(cursor, table, keys, values):
inskeys, qms, vals = make_insert(keys)
cursor.execute("INSERT OR IGNORE INTO %s (%s) VALUES (%s)" % (
table, inskeys, qms), vals)
setkeys, vals1 = make_up... | make_where | identifier_name |
fundvalue.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
import ast
import time
import json
import random
import decimal
import sqlite3
import logging
import datetime
import argparse
import requests
import operator
import contextlib
import collections
import concurrent.futures
import bs4
HEADERS = {
"A... | 'manager INTEGER,'
'updated TEXT,'
'PRIMARY KEY (fid, manager)'
')')
cur.execute('CREATE TABLE IF NOT EXISTS fund_simrank ('
'fid TEXT,'
'date TEXT,'
'rank INTEGER,'
'total INTEGER,'
'PRIMARY KEY (fid, date)'... | 'perf_time REAL,' # 择时能力
'pic TEXT'
')')
cur.execute('CREATE TABLE IF NOT EXISTS fund_managers ('
'fid TEXT,' | random_line_split |
fundvalue.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
import ast
import time
import json
import random
import decimal
import sqlite3
import logging
import datetime
import argparse
import requests
import operator
import contextlib
import collections
import concurrent.futures
import bs4
HEADERS = {
"A... | , ftype = fc.fund_name(fid)
print(fid, fname, ftype)
retry = 3
while 1:
try:
fc.fund_info(fid)
fc.fund_history(fid)
break
except Exception:
retry -= 1
if not retry:
raise
| f __init__(self, db='funds.db'):
self.db = sqlite3.connect(db)
self.init_db()
self.session = requests.Session()
self.session.headers.update(HEADERS)
self.executor = concurrent.futures.ThreadPoolExecutor(6)
def init_db(self):
cur = self.db.cursor()
cur.execute... | identifier_body |
ej4.py | """
date: 4-11-2020
File: ej4.py
Author : Francesco Camussoni
Email: camussonif@gmail.com francesco.camussoni@ib.edu.ar
GitHub: https://github.com/francescocamussoni
GitLab: https://gitlab.com/francescocamussoni
Description:
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
... | (img):
# Normalize array: center on 0., ensure variance is 0.15
img -= img.mean()
img /= img.std() + 1e-5
img *= 0.15
# Center crop
img = img[25:-25, 25:-25, :]
# Clip to [0, 1]
img += 0.5
img = np.clip(img, 0, 1)
# Convert to RGB array
img *= 255
img = ... | deprocess_image | identifier_name |
ej4.py | """
date: 4-11-2020
File: ej4.py
Author : Francesco Camussoni
Email: camussonif@gmail.com francesco.camussoni@ib.edu.ar
GitHub: https://github.com/francescocamussoni
GitLab: https://gitlab.com/francescocamussoni
Description:
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
... | e:
print('invalid selection of learning')
return
return loss, img
def initialize_image():
# We start from a gray image with some random noise
img = tf.random.uniform((1, img_width, img_height, 1))
# ResNet50V2 expects inputs in the range [-1, +1].
# Here we scale our random... | arning_rate * grads
els | conditional_block |
ej4.py | """
date: 4-11-2020
File: ej4.py
Author : Francesco Camussoni
Email: camussonif@gmail.com francesco.camussoni@ib.edu.ar
GitHub: https://github.com/francescocamussoni
GitLab: https://gitlab.com/francescocamussoni
Description:
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
... |
@tf.function
def gradient_ascent_step(img, index, learning_rate, layer, max_or_min):
with tf.GradientTape() as tape:
tape.watch(img)
loss = compute_loss(img, index, layer)
# Compute gradients.
grads = tape.gradient(loss, img)
# Normalize gradients.
grads = tf.math.l2_no... | activation = feature_extractor(input_image)
if layer=='filter':
filter_activation = activation[:, 2:-2, 2:-2, index]
elif layer=='class':
filter_activation = activation[:, index]
print(filter_activation)
else:
print('invalid class')
return
print(tf.reduce... | identifier_body |
ej4.py | """
date: 4-11-2020
File: ej4.py
Author : Francesco Camussoni
Email: camussonif@gmail.com francesco.camussoni@ib.edu.ar
GitHub: https://github.com/francescocamussoni
GitLab: https://gitlab.com/francescocamussoni
Description:
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
... | img -= img.mean()
img /= img.std() + 1e-5
img *= 0.15
# Center crop
img = img[1:-1, 1:-1, :]
# Clip to [0, 1]
img += 0.5
img = np.clip(img, 0, 1)
# Convert to RGB array
img *= 255
img = np.clip(img, 0, 255).astype("uint8")
return img
fig = plt.figure(f... | return loss, img
def deprocess_image(img):
# Normalize array: center on 0., ensure variance is 0.15
| random_line_split |
admission.go | package requiredrouteannotations
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/... |
func NewRequiredRouteAnnotations() *requiredRouteAnnotations {
return &requiredRouteAnnotations{
Handler: admission.NewHandler(admission.Create, admission.Update),
}
}
func (o *requiredRouteAnnotations) SetOpenShiftRouteInformers(informers routeinformers.SharedInformerFactory) {
o.cachesToSync = append(o.caches... | {
if o.ingressLister == nil {
return fmt.Errorf(pluginName + " plugin needs an ingress lister")
}
if o.routeLister == nil {
return fmt.Errorf(pluginName + " plugin needs a route lister")
}
if o.nsLister == nil {
return fmt.Errorf(pluginName + " plugin needs a namespace lister")
}
if len(o.cachesToSync) < 3... | identifier_body |
admission.go | package requiredrouteannotations
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/... |
}
return nil
}
// Check if the route matches the required domain/namespace in the HSTS Policy
func requiredNamespaceDomainMatchesRoute(requirement configv1.RequiredHSTSPolicy, route *routeapi.Route, namespace *corev1.Namespace) (bool, error) {
matchesNamespace, err := matchesNamespaceSelector(requirement.Namespac... | {
return fmt.Errorf(HSTSIncludeSubDomainsMustNotError)
} | conditional_block |
admission.go | package requiredrouteannotations
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/... | (ctx context.Context) bool {
syncCtx, cancelFn := context.WithTimeout(ctx, timeToWaitForCacheSync)
defer cancelFn()
if !o.cacheSyncLock.hasSynced() {
if !cache.WaitForCacheSync(syncCtx.Done(), o.cachesToSync...) {
return false
}
o.cacheSyncLock.setSynced()
}
return true
}
func (o *requiredRouteAnnotation... | waitForSyncedStore | identifier_name |
admission.go | package requiredrouteannotations
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/... | return nil
}
type hstsConfig struct {
maxAge int32
preload bool
includeSubDomains bool
}
const (
HSTSMaxAgeMissingOrWrongError = "HSTS max-age must be set correctly in HSTS annotation"
HSTSMaxAgeGreaterError = "HSTS max-age is greater than maximum age %ds"
HSTSMaxAgeLessThan... | }
// None of the requirements matched this route's domain/namespace, it is automatically allowed | random_line_split |
netlink_linux.go | package ipvs
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"os/exec"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"
)
// For Quick Reference IPVS related netlink message is described at ... |
func (f *ipvsFlags) Serialize() []byte {
return (*(*[unsafe.Sizeof(*f)]byte)(unsafe.Pointer(f)))[:]
}
func (f *ipvsFlags) Len() int {
return int(unsafe.Sizeof(*f))
}
func setup() {
ipvsOnce.Do(func() {
var err error
if out, err := exec.Command("modprobe", "-va", "ip_vs").CombinedOutput(); err != nil {
log... | {
return int(unsafe.Sizeof(*hdr))
} | identifier_body |
netlink_linux.go | package ipvs
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"os/exec"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"
)
// For Quick Reference IPVS related netlink message is described at ... |
}
return 0, fmt.Errorf("no family id in the netlink response")
}
func rawIPData(ip net.IP) []byte {
family := nl.GetIPFamily(ip)
if family == nl.FAMILY_V4 {
return ip.To4()
}
return ip
}
func newIPVSRequest(cmd uint8) *nl.NetlinkRequest {
return newGenlRequest(ipvsFamily, cmd)
}
func newGenlRequest(family... | {
switch int(attr.Attr.Type) {
case genlCtrlAttrFamilyID:
return int(native.Uint16(attr.Value[0:2])), nil
}
} | conditional_block |
netlink_linux.go | package ipvs
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"os/exec"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"
)
// For Quick Reference IPVS related netlink message is described at ... | (cmd uint8) ([][]byte, error) {
req := newIPVSRequest(cmd)
req.Seq = atomic.AddUint32(&i.seq, 1)
return execute(i.sock, req, 0)
}
func assembleDestination(attrs []syscall.NetlinkRouteAttr) (*Destination, error) {
var d Destination
var addressBytes []byte
for _, attr := range attrs {
attrType := int(attr.Attr... | doCmdWithoutAttr | identifier_name |
netlink_linux.go | package ipvs
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"os/exec"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink/nl"
"github.com/vishvananda/netns"
)
// For Quick Reference IPVS related netlink message is described at ... |
func newGenlRequest(familyID int, cmd uint8) *nl.NetlinkRequest {
req := nl.NewNetlinkRequest(familyID, syscall.NLM_F_ACK)
req.AddData(&genlMsgHdr{cmd: cmd, version: 1})
return req
}
func execute(s *nl.NetlinkSocket, req *nl.NetlinkRequest, resType uint16) ([][]byte, error) {
if err := s.Send(req); err != nil {
... | random_line_split | |
sgr.go | package ansi
import (
"fmt"
"strconv"
"strings"
)
// SGR Set Graphics Rendition (affects character attributes)
const (
SGRCodeClear = 0 // clear all special attributes
SGRCodeBold = 1 // bold or increased intensity
SGRCodeDim = 2 // dim or secondary color on gigi
SGRCodeItalic = 3 // ital... | (other SGRAttr) SGRAttr {
if other&SGRAttrClear != 0 {
return other
}
const (
fgMask = sgrAttrFGSet | (sgrColorMask << sgrFGShift)
bgMask = sgrAttrBGSet | (sgrColorMask << sgrBGShift)
)
var (
attrFlags = attr & SGRAttrMask
otherFlags = other & SGRAttrMask
changedFlags = attrFlags ^ otherFlags
... | Diff | identifier_name |
sgr.go | package ansi
import (
"fmt"
"strconv"
"strings"
)
// SGR Set Graphics Rendition (affects character attributes)
const (
SGRCodeClear = 0 // clear all special attributes
SGRCodeBold = 1 // bold or increased intensity
SGRCodeDim = 2 // dim or secondary color on gigi
SGRCodeItalic = 3 // ital... | SGRCube23
SGRCube24
SGRCube25
SGRCube26
SGRCube27
SGRCube28
SGRCube29
SGRCube30
SGRCube31
SGRCube32
SGRCube33
SGRCube34
SGRCube35
SGRCube36
SGRCube37
SGRCube38
SGRCube39
SGRCube40
SGRCube41
SGRCube42
SGRCube43
SGRCube44
SGRCube45
SGRCube46
SGRCube47
SGRCube48
SGRCube49
SGRCube50
SGRCube51
... | SGRCube22 | random_line_split |
sgr.go | package ansi
import (
"fmt"
"strconv"
"strings"
)
// SGR Set Graphics Rendition (affects character attributes)
const (
SGRCodeClear = 0 // clear all special attributes
SGRCodeBold = 1 // bold or increased intensity
SGRCodeDim = 2 // dim or secondary color on gigi
SGRCodeItalic = 3 // ital... |
return RGB(c.RGB())
}
func (c SGRColor) appendFGTo(p []byte) []byte {
switch {
case c&sgrColor24 != 0:
return c.appendRGB(append(p, "38;2"...)) // TODO support color space identifier?
case c <= SGRWhite:
return append(p, '3', '0'+uint8(c))
case c <= SGRBrightWhite:
return append(p, '9', '0'+uint8(c)-8)
ca... | {
return c
} | conditional_block |
sgr.go | package ansi
import (
"fmt"
"strconv"
"strings"
)
// SGR Set Graphics Rendition (affects character attributes)
const (
SGRCodeClear = 0 // clear all special attributes
SGRCodeBold = 1 // bold or increased intensity
SGRCodeDim = 2 // dim or secondary color on gigi
SGRCodeItalic = 3 // ital... |
// To24Bit converts the color to 24-bit mode, so that it won't encode as a
// legacy 3, 4, or 8-bit color.
func (c SGRColor) To24Bit() SGRColor {
if c&sgrColor24 != 0 {
return c
}
return RGB(c.RGB())
}
func (c SGRColor) appendFGTo(p []byte) []byte {
switch {
case c&sgrColor24 != 0:
return c.appendRGB(append... | {
if c&sgrColor24 == 0 {
c = Palette8Colors[c&0xff]
}
return uint8(c), uint8(c >> 8), uint8(c >> 16)
} | identifier_body |
async_queue.js | /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
/**
* Adds a new operation to the queue. Returns a promise that will be resolved
* when the promise returned by the new operation is (with its value).
*/
AsyncQueue.prototype.enqueue = function (op) {
var _this = this;
this.verifyNotFailed();
var newTail = this.tail.then(... | {
// The last promise in the queue.
this.tail = Promise.resolve();
// Operations scheduled to be queued in the future. Operations are
// automatically removed after they are run or canceled.
this.delayedOperations = [];
// Flag set while there's an outstanding AsyncQueue ... | identifier_body |
async_queue.js | /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
};
/**
* Verifies there's an operation currently in-progress on the AsyncQueue.
* Unfortunately we can't verify that the running code is in the promise chain
* of that operation, so this isn't a foolproof check, but it should be enough
* to catch some bugs.
*/
AsyncQueue.prototype.... | {
fail('AsyncQueue is already failed: ' +
(this.failure.stack || this.failure.message));
} | conditional_block |
async_queue.js | /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | // Operations scheduled to be queued in the future. Operations are
// automatically removed after they are run or canceled.
this.delayedOperations = [];
// Flag set while there's an outstanding AsyncQueue operation, used for
// assertion sanity-checks.
this.operationInPro... | function AsyncQueue() {
// The last promise in the queue.
this.tail = Promise.resolve(); | random_line_split |
async_queue.js | /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | () {
// The last promise in the queue.
this.tail = Promise.resolve();
// Operations scheduled to be queued in the future. Operations are
// automatically removed after they are run or canceled.
this.delayedOperations = [];
// Flag set while there's an outstanding AsyncQue... | AsyncQueue | identifier_name |
daemon.go | package daemon
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/fluxcd/flux/pkg/api"
"github.com/fluxcd/flux/pkg/api/v10"
"github.com/fluxcd/flux/pkg/api/v11"
"github.com/fluxcd/flux/pkg/api/v6"
"github.com/fluxcd/flux/pkg/api/v9"
... | (ctx context.Context, repo *git.Repo, syncState sync.State, gitVerifySignaturesMode sync.VerifySignaturesMode) (string, git.Commit, error) {
var invalidCommit = git.Commit{}
newRevision, err := repo.BranchHead(ctx)
if err != nil {
return "", invalidCommit, err
}
// Validate sync state and retrieve the revision ... | latestValidRevision | identifier_name |
daemon.go | package daemon
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/fluxcd/flux/pkg/api"
"github.com/fluxcd/flux/pkg/api/v10"
"github.com/fluxcd/flux/pkg/api/v11"
"github.com/fluxcd/flux/pkg/api/v6"
"github.com/fluxcd/flux/pkg/api/v9"
... |
var res []v6.ControllerStatus
for _, workload := range clusterWorkloads {
readOnly := v6.ReadOnlyOK
repoIsReadonly := d.Repo.Readonly()
var policies policy.Set
if resource, ok := resources[workload.ID.String()]; ok {
policies = resource.Policies()
}
switch {
case policies == nil:
readOnly = mis... | {
return nil, err
} | conditional_block |
daemon.go | package daemon
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/fluxcd/flux/pkg/api"
"github.com/fluxcd/flux/pkg/api/v10"
"github.com/fluxcd/flux/pkg/api/v11"
"github.com/fluxcd/flux/pkg/api/v6"
"github.com/fluxcd/flux/pkg/api/v9"
... |
// latestValidRevision returns the HEAD of the configured branch if it
// has a valid signature, or the SHA of the latest valid commit it
// could find plus the invalid commit thereafter.
//
// Signature validation happens for commits between the revision of the
// sync tag and the HEAD, after the signature of the sy... | {
types := map[string]struct{}{}
for p := range u.Add {
switch {
case p == policy.Automated:
types[event.EventAutomate] = struct{}{}
case p == policy.Locked:
types[event.EventLock] = struct{}{}
default:
types[event.EventUpdatePolicy] = struct{}{}
}
}
for p := range u.Remove {
switch {
case p... | identifier_body |
daemon.go | package daemon
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/fluxcd/flux/pkg/api"
"github.com/fluxcd/flux/pkg/api/v10"
"github.com/fluxcd/flux/pkg/api/v11"
"github.com/fluxcd/flux/pkg/api/v6"
"github.com/fluxcd/flux/pkg/api/v9"
... | if err != nil {
return result, err
}
head, err := d.Repo.BranchHead(ctx)
if err != nil {
return result, err
}
if d.GitVerifySignaturesMode != sync.VerifySignaturesModeNone {
var latestValidRev string
if latestValidRev, _, err = latestValidRevision(ctx, d.Repo, d.SyncState, d.GitVerifySignaturesM... | err := d.Repo.Refresh(ctx) | random_line_split |
WSU-PDF_process_incoming_to_Fedora_152.py | #ABOUT
# this file is designed to process incmoing files from Abbyy for use in the eText Reader
# incoming folder = "/abbyyoutput/bookreader"
# processing folder = "/processing"
# output = "var/www/data"
#IMPROVEMENTS
# 1) Consider changing all "os.command" to "subprocess.call ( e.g. from subprocess import call --> ca... |
# change permissions en bulk
def permissionsChange(item_ID_list):
for item_ID in item_ID_list:
os.system(Template("chmod -R 755 /processing/$item_ID").substitute(item_ID=item_ID))
#try to get MODS file
# remove PDF artifacts (PNGs), renames images to match item_ID
def fileRename(item_ID):
#remove PNG files
... | pre_item_ID_list = os.listdir('/processing')
if len(pre_item_ID_list) == 0:
print "Nothing to do!"
else:
print "Processing these items: ",pre_item_ID_list
#prepare normalized list
item_ID_list = []
for item_ID in pre_item_ID_list:
#apostrophes
item_ID_handle = re.sub("'","\\'", item_ID)
n_item_ID = ... | identifier_body |
WSU-PDF_process_incoming_to_Fedora_152.py | #ABOUT
# this file is designed to process incmoing files from Abbyy for use in the eText Reader
# incoming folder = "/abbyyoutput/bookreader"
# processing folder = "/processing"
# output = "var/www/data"
#IMPROVEMENTS
# 1) Consider changing all "os.command" to "subprocess.call ( e.g. from subprocess import call --> ca... | im.thumbnail((max_width, max_height), Image.ANTIALIAS)
# converts to RGB if necessary...
if im.mode != "RGB":
im = im.convert("RGB")
im.save(Template('/processing/$item_ID/$image_basename.jpg').substitute(item_ID=item_ID, image_basename=image_basename))
print image,"resized to: ",im.size,",... | else:
print Template("Portait - resizing from $orig_width to 1700").substitute(orig_width=width) | random_line_split |
WSU-PDF_process_incoming_to_Fedora_152.py | #ABOUT
# this file is designed to process incmoing files from Abbyy for use in the eText Reader
# incoming folder = "/abbyyoutput/bookreader"
# processing folder = "/processing"
# output = "var/www/data"
#IMPROVEMENTS
# 1) Consider changing all "os.command" to "subprocess.call ( e.g. from subprocess import call --> ca... | (item_ID):
# get number of files
images = os.listdir("/processing/"+item_ID+"/images")
leaf_count = len(images) - 1 #accounts for /thumbs directory in there
# get dimensions of cover and create cover image
cover_path = Template('/processing/$item_ID/images/$item_ID').substitute(item_ID=item_ID) + "00001.jpg"
i... | createMetadata | identifier_name |
WSU-PDF_process_incoming_to_Fedora_152.py | #ABOUT
# this file is designed to process incmoing files from Abbyy for use in the eText Reader
# incoming folder = "/abbyyoutput/bookreader"
# processing folder = "/processing"
# output = "var/www/data"
#IMPROVEMENTS
# 1) Consider changing all "os.command" to "subprocess.call ( e.g. from subprocess import call --> ca... |
except:
print "<body> tag is empty, skipping. Adding page_ID anyway."
continue
#closes page_ID / div
html_concat = html_concat + "</div>"
html_count = html_count + 1
fhand.close()
#create concatenated file
fwrite = open(Template('/processing/$item_ID/OCR/$item_ID').substitute(item_ID=item_ID)+... | html_concat = html_concat + unicode(block) | conditional_block |
render.py | import collections
import random
import pyglet
from entity import Component
from fov import InFOV
from generator import LayoutGenerator
from hud import HUD
from light import LightOverlay
from message import LastMessagesView
from position import Position
from temp import floor_tex, get_wall_tex, dungeon_te... | tile = renderable.tile
break
else:
continue
# always add floor, because we wanna draw walls above floor
vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2))
tex_coords.extend(floor_te... | for entity in self._level.position_system.get_entities_at(x, y):
renderable = entity.get(LayoutRenderable)
if renderable:
| random_line_split |
render.py | import collections
import random
import pyglet
from entity import Component
from fov import InFOV
from generator import LayoutGenerator
from hud import HUD
from light import LightOverlay
from message import LastMessagesView
from position import Position
from temp import floor_tex, get_wall_tex, dungeon_te... |
def remove_entity(self, entity):
sprite = self._sprites.pop(entity)
sprite.delete()
entity.unlisten('image_change', self._on_image_change)
entity.unlisten('move', self._on_move)
def _on_image_change(self, entity):
self._sprites[entity].image = entity.get(Rende... | image = entity.get(Renderable).image
pos = entity.get(Position)
group = pyglet.graphics.OrderedGroup(pos.order, self._level_group)
sprite = pyglet.sprite.Sprite(image, pos.x * 8, pos.y * 8, batch=self._batch, group=group)
self._sprites[entity] = sprite
entity.listen('image_c... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.