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 |
|---|---|---|---|---|
main.js | var mainJs = function() {
if ( !Detector.webgl ) {
container = document.createElement( 'div' );
container =
$('<div class="addGetWebGLMessage">' +
'あなたのブラウザは最新ではありませんので、インターネット上にあるイケてる技術をみることはできません。<br>' +
'Your browser does not seem to support WebGL. Take a step to the future.' +
'<di... | reventDefault();
mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
... | seX - mouseXOnMouseDown ) * 0.02;
}
function onDocumentTouchStart( event ) {
if ( event.touches.length === 1 ) {
event.p | identifier_body |
main.js | var mainJs = function() {
if ( !Detector.webgl ) {
container = document.createElement( 'div' );
container =
$('<div class="addGetWebGLMessage">' +
'あなたのブラウザは最新ではありませんので、インターネット上にあるイケてる技術をみることはできません。<br>' +
'Your browser does not seem to support WebGL. Take a step to the future.' +
'<di... |
lightness += 0.0003 * delta;
if ( lightness > 0.05 ) lightness -= 0.05;
// TODO Create a PointOnShape Action/Zone in the particle engine
timeOnShapePath += 0.00035 * delta;
if ( timeOnShapePath > 1 ) timeOnShapePath -= 1;
var pointOnShape = circleShape.getPointAt( tim... |
hue += 0.0003 * delta;
if ( hue > 0.1 ) hue -= 0.1; | random_line_split |
main.js | var mainJs = function() {
if ( !Detector.webgl ) {
container = document.createElement( 'div' );
container =
$('<div class="addGetWebGLMessage">' +
'あなたのブラウザは最新ではありませんので、インターネット上にあるイケてる技術をみることはできません。<br>' +
'Your browser does not seem to support WebGL. Take a step to the future.' +
'<di... | = speed * clock.getDelta();
particleCloud.geometry.verticesNeedUpdate = true;
attributes.size.needsUpdate = true;
attributes.pcolor.needsUpdate = true;
// Pretty cool effect if you enable this
// particleCloud.rotation.y += 0.05;
group.rotation.y += ( targetRotation - group.rotation.y ) * 0.... | delta | identifier_name |
main.js | var mainJs = function() {
if ( !Detector.webgl ) {
container = document.createElement( 'div' );
container =
$('<div class="addGetWebGLMessage">' +
'あなたのブラウザは最新ではありませんので、インターネット上にあるイケてる技術をみることはできません。<br>' +
'Your browser does not seem to support WebGL. Take a step to the future.' +
'<di... | if ( target ) {
// Hide the particle
values_color[ target ].setRGB( 0, 0, 0 );
particles.vertices[ target ].set( Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY );
// Mark particle system as available by returning to pool
Pool.add( particle.tar... | * delta;
if ( lightness > 0.05 ) lightness -= 0.05;
// TODO Create a PointOnShape Action/Zone in the particle engine
timeOnShapePath += 0.00035 * delta;
if ( timeOnShapePath > 1 ) timeOnShapePath -= 1;
var pointOnShape = circleShape.getPointAt( timeOnShapePath );
if (!... | conditional_block |
roles.go | package model
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v2"
)
// RoleType is the type of the role; see the constants below
type RoleType string
// These are the types of roles available
const (
RoleTypeBoshTask = RoleType("bosh-task") // A role ... |
hasher := sha1.New()
hasher.Write([]byte(roleSignature))
return hex.EncodeToString(hasher.Sum(nil))
}
// HasTag returns true if the role has a specific tag
func (r *Role) HasTag(tag string) bool {
for _, t := range r.Tags {
if t == tag {
return true
}
}
return false
}
func (r *Role) calculateRoleConfi... | {
roleSignature = fmt.Sprintf("%s\n%s", roleSignature, pkg.SHA1)
} | conditional_block |
roles.go | package model
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v2"
)
// RoleType is the type of the role; see the constants below
type RoleType string
// These are the types of roles available
const (
RoleTypeBoshTask = RoleType("bosh-task") // A role ... | (roleName string) *Role {
return m.rolesByName[roleName]
}
// GetScriptPaths returns the paths to the startup / post configgin scripts for a role
func (r *Role) GetScriptPaths() map[string]string {
result := map[string]string{}
for _, scriptList := range [][]string{r.EnvironScripts, r.Scripts, r.PostConfigScripts}... | LookupRole | identifier_name |
roles.go | package model
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v2"
)
// RoleType is the type of the role; see the constants below
type RoleType string
// These are the types of roles available
const (
RoleTypeBoshTask = RoleType("bosh-task") // A role ... |
// RoleManifest represents a collection of roles
type RoleManifest struct {
Roles Roles `yaml:"roles"`
Configuration *Configuration `yaml:"configuration"`
manifestFilePath string
rolesByName map[string]*Role
}
// Role represents a collection of jobs that are colocated on a container
type Ro... | FlightStagePostFlight = FlightStage("post-flight") // A role that runs after the main jobs are up
FlightStageManual = FlightStage("manual") // A role that only runs via user intervention
) | random_line_split |
roles.go | package model
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v2"
)
// RoleType is the type of the role; see the constants below
type RoleType string
// These are the types of roles available
const (
RoleTypeBoshTask = RoleType("bosh-task") // A role ... |
// LoadRoleManifest loads a yaml manifest that details how jobs get grouped into roles
func LoadRoleManifest(manifestFilePath string, releases []*Release) (*RoleManifest, error) {
manifestContents, err := ioutil.ReadFile(manifestFilePath)
if err != nil {
return nil, err
}
mappedReleases := map[string]*Release{... | {
roles[i], roles[j] = roles[j], roles[i]
} | identifier_body |
autoComplete.js |
var search_box;
var search_option;
var m_now = 0, s_now = 0, shl = 0, a_now = 0, a_on = 0, arr_on = 0, frm_on = 0;
var cn_use = "use_ac";
var wi_len = 2;
var wi_int = 500;
var max_row = 4;
var B = "block", I = "inline", N = "none", UD = "undefined";
var bak = "", old = "";
var qs_ac_list = "", qs_ac_id = "", qs_q = ""... | ); }
}
old = now;
setTimeout("wi()", wi_int);
}
function set_mouseon(f) {
if (f == 1) arr_on = 1;
else if (f == 2) frm_on = 1;
}
function set_mouseoff(f) {
if (f == 1) arr_on = 0;
else if (f == 2) frm_on = 0;
}
//검색어입력창의 자동완성 화살표를 위, 아래로 변경한다.
//type 0 : 창이 닫혔을때 화살표 아래로.
//type 1 : 창이 펼처졌... | , me = 1;
o = get_cc(me);
if (o && o[1][0] != "") { ac_show(o[0], o[1], o[2], me); }
else { reqAC(me | identifier_body |
autoComplete.js | var search_box;
var search_option;
var m_now = 0, s_now = 0, shl = 0, a_now = 0, a_on = 0, arr_on = 0, frm_on = 0;
var cn_use = "use_ac";
var wi_len = 2;
var wi_int = 500;
var max_row = 4;
var B = "block", I = "inline", N = "none", UD = "undefined";
var bak = "", old = "";
var qs_ac_list = "", qs_ac_id = "", qs_q = "",... | function js_strlen(s) {
var i, l = 0;
for (i = 0; i < s.length; i++)
if (s.charCodeAt(i) > 127) l += 2;
else l++;
return l;
}
function js_substring(s, start, len) {
var i, l = 0; d = "";
for (i = start; i < s.length && l < len; i++) {
if (s.charCodeAt(i) > 127) l += 2;
... | random_line_split | |
autoComplete.js |
var search_box;
var search_option;
var m_now = 0, s_now = 0, shl = 0, a_now = 0, a_on = 0, arr_on = 0, frm_on = 0;
var cn_use = "use_ac";
var wi_len = 2;
var wi_int = 500;
var max_row = 4;
var B = "block", I = "inline", N = "none", UD = "undefined";
var bak = "", old = "";
var qs_ac_list = "", qs_ac_id = "", qs_q = ""... | rn;
}
if (arr_on) {
return;
}
if (frm_on) {
return;
}
alw = 0;
ac_hide();
}
function req_ac2(me) {
if (search_box.value == "" || acuse == 0) return;
if (a_on && dnc) {
ac_hide();
return;
}
var o = get_cc(me);
if (o && o[1][0] != "") { ... | tu | identifier_name |
autoComplete.js |
var search_box;
var search_option;
var m_now = 0, s_now = 0, shl = 0, a_now = 0, a_on = 0, arr_on = 0, frm_on = 0;
var cn_use = "use_ac";
var wi_len = 2;
var wi_int = 500;
var max_row = 4;
var B = "block", I = "inline", N = "none", UD = "undefined";
var bak = "", old = "";
var qs_ac_list = "", qs_ac_id = "", qs_q = ""... | tch_image(1);
}
}
//인풋박스의 세모 버튼을 눌렀을때 자동완성창을 보여준다.
function show_ac() {
if (acuse == 0) {
if ($j("#ac_body")[0].style.display == "block")
popup_ac(0);
else
popup_ac(2);
}
else {
if ($j("#schInput").val() == "") {
if ($j("#noquery_ac_body")[0]... | if (type == 3) {
$j("#ac_body").css("display", "none");
$j("#off_ac_body").css("display", "none");
$j("#noquery_ac_body")[0].style.display = "block";
swi | conditional_block |
Marriah_Lewis_Cinema_Project.py | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 18:52:17 2021
@author: lewis
"""
import csv
import pandas as pd
import re
import statistics
import matplotlib.pyplot as plt
import numpy as np
from bs4 import BeautifulSoup
from urllib.request import urlopen
#Creating a function that groups by, co... |
url = 'https://en.wikipedia.org/wiki/Film_series'
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
#Create a function to process the string into an integer by using re.sub()
def process_num(num):
return float(re.sub(r'[^\w\s.]','',num))
#test function
... | new_df = pd.DataFrame(df.groupby(groupby_column)[count_column].count())
new_df.columns = ['count']
new_df[groupby_column] = new_df.index.get_level_values(0)
new_df.reset_index(drop = True, inplace = True)
return(new_df) | identifier_body |
Marriah_Lewis_Cinema_Project.py | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 18:52:17 2021
@author: lewis
"""
import csv
import pandas as pd
import re
import statistics
import matplotlib.pyplot as plt
import numpy as np
from bs4 import BeautifulSoup
from urllib.request import urlopen
#Creating a function that groups by, co... | clean_TMDB_movies = clean_TMDB_movies[clean_TMDB_movies['budget'] != 0]
#Removing any movie with a revenue of 0
clean_TMDB_movies = clean_TMDB_movies[clean_TMDB_movies['revenue'] != 0]
#review the profit for each movie therefore a profit column was created
clean_TMDB_movies['profit'] = clean_TMDB_movies['revenue'... | clean_TMDB_movies.dropna(inplace= True)
#print(clean_TMDB_movies.isnull().sum())
#Removing any movie that has a budget of 0
| random_line_split |
Marriah_Lewis_Cinema_Project.py | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 18:52:17 2021
@author: lewis
"""
import csv
import pandas as pd
import re
import statistics
import matplotlib.pyplot as plt
import numpy as np
from bs4 import BeautifulSoup
from urllib.request import urlopen
#Creating a function that groups by, co... |
movies_discretized["main_production"] = production_company
#print(movies_discretized["main_production"].head())
movies_discretized_count = movies_discretized.groupby(["main_production", "percent_profit"])["main_production"].count()
movies_discretized_count_df= pd.DataFrame(movies_discretized_count)
#print(movie... | production_company.append("None") | conditional_block |
Marriah_Lewis_Cinema_Project.py | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 18:52:17 2021
@author: lewis
"""
import csv
import pandas as pd
import re
import statistics
import matplotlib.pyplot as plt
import numpy as np
from bs4 import BeautifulSoup
from urllib.request import urlopen
#Creating a function that groups by, co... | (df, groupby_column, count_column):
new_df = pd.DataFrame(df.groupby(groupby_column)[count_column].count())
new_df.columns = ['count']
new_df[groupby_column] = new_df.index.get_level_values(0)
new_df.reset_index(drop = True, inplace = True)
return(new_df)
url = 'https://en.wikipedia.org... | groupby_count | identifier_name |
trace_processing.py | import os, pickle
import data
DATA_DIR = os.path.join("traces_05_withmobs")
MODEL_DIR = os.path.join("models")
SCHEMA_LIB_FILE = 'schema_lib_3_gather_mobs.pkl'
##############################################################
# Load traces from disk
##############################################################
def lo... |
for j in range(i-1,-1,-1):
print("interaction: {} {}".format(interaction[j].agent_eid, tgt_eid))
if interaction[j].agent_eid == tgt_eid:
return interaction[j]
return None
def interaction_responses(interaction, i):
"""Return the dns that act on the agent of i during that behav... | return None | conditional_block |
trace_processing.py | import os, pickle
import data
DATA_DIR = os.path.join("traces_05_withmobs")
MODEL_DIR = os.path.join("models")
SCHEMA_LIB_FILE = 'schema_lib_3_gather_mobs.pkl'
##############################################################
# Load traces from disk
##############################################################
def lo... |
def continued_involvement(doing, eid, clock, step=0.01):
"""True if acting or targeted beyond the next frame."""
if eid in doing:
if doing[eid].end_clock > (clock+step): return True
for dn in active_target_of(doing, eid):
if dn.end_clock > (clock+step): return True
return False
######... | """True if acting or targeted in current doing set."""
if eid in doing: return True
for dn in active_target_of(doing, eid):
return True
return False | identifier_body |
trace_processing.py | import os, pickle
import data
DATA_DIR = os.path.join("traces_05_withmobs")
MODEL_DIR = os.path.join("models")
SCHEMA_LIB_FILE = 'schema_lib_3_gather_mobs.pkl'
##############################################################
# Load traces from disk
##############################################################
def lo... | return interaction[j]
return None
def interaction_responses(interaction, i):
"""Return the dns that act on the agent of i during that behavior."""
agent_eid = interaction[i].agent_eid
# no agent, no response (REM: that's not right, but is given how we're creating interactions right now)
... | for j in range(i-1,-1,-1):
print("interaction: {} {}".format(interaction[j].agent_eid, tgt_eid))
if interaction[j].agent_eid == tgt_eid: | random_line_split |
trace_processing.py | import os, pickle
import data
DATA_DIR = os.path.join("traces_05_withmobs")
MODEL_DIR = os.path.join("models")
SCHEMA_LIB_FILE = 'schema_lib_3_gather_mobs.pkl'
##############################################################
# Load traces from disk
##############################################################
def lo... | (doing, eid):
"""True if acting or targeted in current doing set."""
if eid in doing: return True
for dn in active_target_of(doing, eid):
return True
return False
def continued_involvement(doing, eid, clock, step=0.01):
"""True if acting or targeted beyond the next frame."""
if eid in d... | current_involvement | identifier_name |
label.go | package label
import (
"fmt"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/pluginhelp/externalplugins"
"k8s.io/test-infra/prow/plugins"
tiextern... | {
// Arrange prefixes in the format "sig|kind|priority|...",
// so that they can be used to create labelRegex and removeLabelRegex.
labelPrefixes := strings.Join(prefixes, "|")
labelRegex, err := regexp.Compile(fmt.Sprintf(labelRegexp, labelPrefixes))
if err != nil {
return err
}
removeLabelRegex, err := rege... | identifier_body | |
label.go | package label
import (
"fmt"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/pluginhelp/externalplugins"
"k8s.io/test-infra/prow/plugins"
tiextern... | noSuchLabelsOnIssue []string
labelsToAdd []string
labelsToRemove []string
)
// Get labels to add and labels to remove from the RegExp matches.
// Notice: The returned label is lowercase.
labelsToAdd = append(getLabelsFromREMatches(labelMatches),
getLabelsFromGenericMatches(customLabelMatches, ... |
var (
nonexistent []string
noSuchLabelsInRepo []string | random_line_split |
label.go | package label
import (
"fmt"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/pluginhelp/externalplugins"
"k8s.io/test-infra/prow/plugins"
tiextern... | (gc githubClient, log *logrus.Entry, additionalLabels,
prefixes, excludeLabels []string, e *github.IssueCommentEvent) error {
// Arrange prefixes in the format "sig|kind|priority|...",
// so that they can be used to create labelRegex and removeLabelRegex.
labelPrefixes := strings.Join(prefixes, "|")
labelRegex, e... | handle | identifier_name |
label.go | package label
import (
"fmt"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/pluginhelp/externalplugins"
"k8s.io/test-infra/prow/plugins"
tiextern... |
if opts.ExcludeLabels != nil {
excludeLabelsConfigMsg = fmt.Sprintf("%v labels cannot be added by command.\n",
opts.ExcludeLabels)
}
labelConfig[repo.String()] = prefixConfigMsg + additionalLabelsConfigMsg + excludeLabelsConfigMsg
}
yamlSnippet, err := plugins.CommentMap.GenYaml(&tiexternalplugi... | {
additionalLabelsConfigMsg = fmt.Sprintf("%v labels can be used with the `/[remove-]label` command.\n",
opts.AdditionalLabels)
} | conditional_block |
iphelper.go | package iphelper
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
)
const (
HEADER_LENGTH = 4
BODYLINE_LENGTH = 20
)
const (
AREA_COUNTRY = "country"
AREA_PROVINCE = "province"
AREA_CITY = "city"
AREA_ZONE ... | .searchIpRow(ipSearch)
if err != nil {
return 0, err
}
areacode := this.getGeocodeByRow(row)
codeUint64, err := strconv.ParseUint(areacode, 10, 64)
if err != nil {
return 0, err
}
return codeUint64, nil
}
func (this *IpStore) GetGeoByGeocode(areacode uint64) map[string]string {
result := map... | w, err := this | identifier_name |
iphelper.go | package iphelper
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
)
const (
HEADER_LENGTH = 4
BODYLINE_LENGTH = 20
)
const (
AREA_COUNTRY = "country"
AREA_PROVINCE = "province"
AREA_CITY = "city"
AREA_ZONE ... | uestip, ".")
if len(nowip) != 4 {
return 0
}
a, _ := strconv.ParseUint(nowip[0], 10, 64)
b, _ := strconv.ParseUint(nowip[1], 10, 64)
c, _ := strconv.ParseUint(nowip[2], 10, 64)
d, _ := strconv.ParseUint(nowip[3], 10, 64)
ipNum := a<<24 | b<<16 | c<<8 | d
return ipNum
}
func Num2IP(ipnum uint64) s... | art); err != nil {
goto fail
}
if err = binary.Read(buf, binary.BigEndian, &row.End); err != nil {
goto fail
}
if err = binary.Read(buf, binary.BigEndian, &row.Country); err != nil {
goto fail
}
if err = binary.Read(buf, binary.BigEndian, &row.Province); err != nil {
goto fail
}
if err = bin... | identifier_body |
iphelper.go | package iphelper
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
)
const (
HEADER_LENGTH = 4
BODYLINE_LENGTH = 20
)
const (
AREA_COUNTRY = "country"
AREA_PROVINCE = "province"
AREA_CITY = "city"
AREA_ZONE ... | return err
}
fmt.Println("amount ip range from ip source: ", count)
return nil
} | break
}
}
if err := output.writeFile(); err != nil {
| random_line_split |
iphelper.go | package iphelper
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
)
const (
HEADER_LENGTH = 4
BODYLINE_LENGTH = 20
)
const (
AREA_COUNTRY = "country"
AREA_PROVINCE = "province"
AREA_CITY = "city"
AREA_ZONE ... | il
}
func (this *IpStore) parseMeta(file *os.File) (err error) {
this.metaBuffer = make([]byte, this.metaLength)
if _, err := file.ReadAt(this.metaBuffer, int64(HEADER_LENGTH+HEADER_LENGTH+this.bodyLength)); err != nil {
panic("read meta error")
}
return json.Unmarshal(this.metaBuffer, &this.metaTable)
... | LENGTH
}
return n | conditional_block |
deeqlearning_atari.py | import copy
import gym
import os
import sys
import random
import numpy as np
from matplotlib import pyplot as plt
from gym import wrappers
from datetime import datetime
import tensorflow as tf
from tensorflow.keras import Model, layers, Sequential
from tensorflow.keras.activations import softmax, tanh
tf.keras.backend... | self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
return loss_value
def copy_from(self, other):
weights = other.get_weights()
self.set_weights(weights)
def predict(self, X):
X = np.atleast_2d(X)
return self(X)
def sample_action(self, X, eps... | with tf.GradientTape() as tape:
Y_hat = self(X)
# Loss value for this minibatch
loss_value = cost(G, Y_hat, actions, self.K)
grads = tape.gradient(loss_value, self.trainable_weights) | random_line_split |
deeqlearning_atari.py | import copy
import gym
import os
import sys
import random
import numpy as np
from matplotlib import pyplot as plt
from gym import wrappers
from datetime import datetime
import tensorflow as tf
from tensorflow.keras import Model, layers, Sequential
from tensorflow.keras.activations import softmax, tanh
tf.keras.backend... | (model, target_model, experience_replay_buffer, gamma, batch_size):
#sample experiences
states, actions, rewards, next_states, dones = experience_replay_buffer.get_minibatch()
#calculate targets
next_Qs = target_model.predict(next_states)
next_Q = np.amax(next_Qs, axis=1)
targets = rew... | learn | identifier_name |
deeqlearning_atari.py | import copy
import gym
import os
import sys
import random
import numpy as np
from matplotlib import pyplot as plt
from gym import wrappers
from datetime import datetime
import tensorflow as tf
from tensorflow.keras import Model, layers, Sequential
from tensorflow.keras.activations import softmax, tanh
tf.keras.backend... |
def sample_action(self, X, eps):
if np.random.random() < eps:
return np.random.choice(self.K)
else:
return np.argmax(self.predict([X])[0])
def learn(model, target_model, experience_replay_buffer, gamma, batch_size):
#sample experiences
states, actions, re... | X = np.atleast_2d(X)
return self(X) | identifier_body |
deeqlearning_atari.py | import copy
import gym
import os
import sys
import random
import numpy as np
from matplotlib import pyplot as plt
from gym import wrappers
from datetime import datetime
import tensorflow as tf
from tensorflow.keras import Model, layers, Sequential
from tensorflow.keras.activations import softmax, tanh
tf.keras.backend... |
if self.terminal_flags[index - self.agent_history_length : index].any():
#checks for done flag
continue
break
self.indices[i] = index
def get_minibatch(self):
'''Returns a minibatch of self.batch_size transitions'''
... | continue | conditional_block |
seasonal_cycle_utils.py | import glob
import sys
import cdms2 as cdms
import numpy as np
import MV2 as MV
import difflib
import scipy.stats as stats
global crunchy
import socket
if socket.gethostname().find("crunchy")>=0:
crunchy = True
else:
crunchy = False
#import peakfinder as pf
import cdtime,cdutil,genutil
from eofs.cdms import Eo... |
def get_semiannual_cycle(tas):
"""Helper function: get the magnitude and phase for the mode with period 6 """
return get_cycle(tas,period=6)
def get_cycle_map(tas,period = 12):
ntime,nlat,nlon = tas.shape
AMP = MV.zeros((nlat,nlon))
PHI = MV.zeros((nlat,nlon))
for i in range(nlat):
fo... | """Return the tangent of the phase associated with Fourier mode"""
L = len(tas)
freqs = np.fft.fftfreq(L)
closest = np.abs(freqs-1./period)
# i = np.where(freqs == 1./period)[0]
i = np.argmin(closest)
#print 1/freqs[i]
tas_fft = np.fft.fft(tas)/L
R = tas_fft.real
Im = tas_fft.imag
... | identifier_body |
seasonal_cycle_utils.py | import glob
import sys
import cdms2 as cdms
import numpy as np
import MV2 as MV
import difflib
import scipy.stats as stats
global crunchy
import socket
if socket.gethostname().find("crunchy")>=0:
crunchy = True
else:
crunchy = False
#import peakfinder as pf
import cdtime,cdutil,genutil
from eofs.cdms import Eo... |
if zonal_average:
if 'lon' in X.getAxisIds():
X = cdutil.averager(X,axis='x')
nyears = nt/12
newshape = (nyears, 12) + X.shape[1:]
yrs = X.reshape(newshape)
if semiann:
vec_cycle=broadcast(get_semiannual_cycle)
else:
vec_cycle = broadcast(get_cycle)
# pr... | nt, = X.shape
has_models = False | conditional_block |
seasonal_cycle_utils.py | import glob
import sys
import cdms2 as cdms
import numpy as np
import MV2 as MV
import difflib
import scipy.stats as stats
global crunchy
import socket
if socket.gethostname().find("crunchy")>=0:
crunchy = True
else:
crunchy = False
#import peakfinder as pf
import cdtime,cdutil,genutil
from eofs.cdms import Eo... | (X,debug=False,semiann=False,zonal_average=False):
if len(X.shape)==4:
nt,nlat,nlon,nmod = X.shape
has_models=True
elif len(X.shape)==3:
nt,nlat,nlon = X.shape
has_models = False
elif len(X.shape)==2:
nt,nlat = X.shape
has_models=False
elif len(X.shape)==... | fast_annual_cycle | identifier_name |
seasonal_cycle_utils.py | import glob
import sys
import cdms2 as cdms
import numpy as np
import MV2 as MV
import difflib
import scipy.stats as stats
global crunchy
import socket
if socket.gethostname().find("crunchy")>=0:
crunchy = True
else:
crunchy = False
#import peakfinder as pf
import cdtime,cdutil,genutil
from eofs.cdms import Eo... | PANOM[:,i,j] = pa(P[:,i,j],reference[i,j])
else:
nt,nlat = P.shape
for i in range(nlat):
PANOM[:,i] = pa(P[:,i],reference[i])
PANOM.setAxisList(P.getAxisList())
return MV.masked_where(np.isnan(PANOM),PANOM)
def phase_to_month(P):
## O is jan 1, 6 is july ... | nt,nlat,nlon = P.shape
for i in range(nlat):
for j in range(nlon): | random_line_split |
web.rs | use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::*;
use std::ffi::OsStr;
use std::sync::Arc;
use std::time::{Duration as SDuration, Instant};
use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2};
u... |
use crate::Shared;
use crate::DataLogEntry;
use crate::TSDataLogEntry;
use file_db::{create_intervall_filtermap, TimestampedMethods};
use hyper::StatusCode;
use hyper::server::{Http, NewService, Request, Response, Server, Service};
use hyper::header;
use futures::future::{FutureExt as _, TryFutureExt}; // for conver... | random_line_split | |
web.rs |
use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::*;
use std::ffi::OsStr;
use std::sync::Arc;
use std::time::{Duration as SDuration, Instant};
use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2};
... | <F>(result: F) -> HandlerResult
where
F: Future<Item = Response, Error = Error> + Sized + 'static,
{
Box::new(result.then(|result| {
let f = match result {
Ok(response) => response,
Err(err) => {
use std::fmt::Write;
let mut buf = String::with_capa... | box_and_convert_error | identifier_name |
web.rs |
use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::*;
use std::ffi::OsStr;
use std::sync::Arc;
use std::time::{Duration as SDuration, Instant};
use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2};
... | else {
Err(::failure::err_msg("Unknown asset"))
}
}))
}
None => make404(),
}
}
fn serve_history<'a>(&self, date: Option<&'a str>) -> HandlerResult {
match NaiveDate::parse_from_str(date.unwrap_or("nodate"), ... | {
let mut f = File::open(path).unwrap();
let mut buffer = String::new();
f.read_to_string(&mut buffer).unwrap();
Ok(buffer).map(str_to_response)
} | conditional_block |
web.rs |
use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::*;
use std::ffi::OsStr;
use std::sync::Arc;
use std::time::{Duration as SDuration, Instant};
use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2};
... |
fn box_and_convert_error<F>(result: F) -> HandlerResult
where
F: Future<Item = Response, Error = Error> + Sized + 'static,
{
Box::new(result.then(|result| {
let f = match result {
Ok(response) => response,
Err(err) => {
use std::fmt::Write;
let m... | {
Response::new()
.with_header(header::ContentLength(body.len() as u64))
.with_body(body)
} | identifier_body |
cmds.py | import discord
from collections import Counter
from db import readDB, writeDB
INFO_DB_SUCCESS = 'Database updated successfully!'
ERROR_DB_ERROR = 'Error: Unable to open database for writing'
ERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.'
ERROR_PLA... | winnerVal = int(rows[winnerIndex][1])
rows[winnerIndex][1] = str(winnerVal + 1)
# same as winner for each loser
for loser in losers:
loserIndex = getIndex(loser, rows)
loserVal = int(rows[loserIndex][2])
rows[loserIndex][2] = str(loserVal + 1)
# write the new data to the da... | # get index, get win count, increment and update
winnerIndex = getIndex(winner, rows) | random_line_split |
cmds.py | import discord
from collections import Counter
from db import readDB, writeDB
INFO_DB_SUCCESS = 'Database updated successfully!'
ERROR_DB_ERROR = 'Error: Unable to open database for writing'
ERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.'
ERROR_PLA... | (msgChannel, statsFile, sortType='WINRATE', player='ALL'):
# read database
data = readDB(statsFile)
# return an error if database not found
if data == 0:
return ERROR_DB_NOT_FOUND
rows = data.rows
print('[INFO] Sort type is %s' % sortType)
returnMsg = ''
if sortType == 'WINRATE'... | dumpStats | identifier_name |
cmds.py | import discord
from collections import Counter
from db import readDB, writeDB
INFO_DB_SUCCESS = 'Database updated successfully!'
ERROR_DB_ERROR = 'Error: Unable to open database for writing'
ERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.'
ERROR_PLA... |
# desc: function to display the stats
# args: msgChannel - the channel the invoking message was sent from
# statsFile - the name of the database file
# sortType - the order in which the results should be sorted.
# options are 'WINRATE', 'WINS', 'LOSSES', or 'NAME'.
# wil... | data = readDB(statsFile)
# return an error if database not found
if data == 0:
return ERROR_DB_NOT_FOUND
rows = data.rows
playerIndex = getIndex(player, rows)
# check if player is already in database
if editType == 'ADD':
if playerIndex > -1:
print('[ERROR] \"%s\" al... | identifier_body |
cmds.py | import discord
from collections import Counter
from db import readDB, writeDB
INFO_DB_SUCCESS = 'Database updated successfully!'
ERROR_DB_ERROR = 'Error: Unable to open database for writing'
ERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.'
ERROR_PLA... |
else:
rows[playerIndex] = [rows[playerIndex][0], wins, losses]
# write the new data to the database file
if writeDB(statsFile, data.headers, rows):
print('[INFO] %s\'s data changed' % player)
return INFO_DB_SUCCESS
else:
... | print('[ERROR] \"%s\" not found in database' % player)
print('[INFO] Database not updated')
return (ERROR_PLAYER_NOT_FOUND % player) | conditional_block |
jherax.js | //******************************
// Utils for validations
// Author: David Rivera
// Created: 26/06/2013
//******************************
// jherax.github.io
// github.com/jherax/js-utils
//******************************
;
// Essential JavaScript Namespacing Patterns
// http://addyosmani.com/blog/essential-js-namesp... | ------------------------
// Shows the loading overlay screen
function fnLoading(o) {
var d = $.extend({
show: true,
hide: false,
delay: 2600
}, o);
$("#loadingWrapper").remove();
if (d.hide) return true;
var blockG = [];
for (va... | M(_dom)) _dom = $(_dom);
_dom.on("blur", function () { $(".vld-tooltip").remove(); });
var vld = $('<span class="vld-tooltip">' + _msg + '</span>');
vld.appendTo(js.wrapper).position({
of: _dom,
at: "right center",
my: "left+6 center",
collision: "... | identifier_body |
jherax.js | //******************************
// Utils for validations
// Author: David Rivera
// Created: 26/06/2013
//******************************
// jherax.github.io
// github.com/jherax/js-utils
//******************************
;
// Essential JavaScript Namespacing Patterns
// http://addyosmani.com/blog/essential-js-namesp... | (i, value) {
var html = $("<div/>").text(value).html();
return $.trim(html);
}
//-----------------------------------
// Gets selected text in the document
function fnGetSelectedText() {
var _dom = document.activeElement;
var _sel = { text: "", slice: "", start: -1, end: -... | fnGetHtmlText | identifier_name |
jherax.js | //******************************
// Utils for validations
// Author: David Rivera
// Created: 26/06/2013
//******************************
// jherax.github.io
// github.com/jherax/js-utils
//******************************
;
// Essential JavaScript Namespacing Patterns
// http://addyosmani.com/blog/essential-js-namesp... | _text = _text.replace(/^\w/, _text.charAt(0).toUpperCase());
if (_isDOM) obj.value = _text;
return _text;
}
//-----------------------------------
// Sets the numeric format in es-CO culture.
// Places decimal "." and thousand "," separator
function fnNumericFormat(obj) {
var... | if (_type == "upper") _text = _text.toUpperCase();
if (_type == "lower" || _type == "word") _text = _text.toLowerCase();
if (_type == "title" || _type == "word") {
_text = _text.replace(/(?:^|-|:|;|\s|\.|\(|\/)[a-záéíóúüñ]/g, function (m) { return m.toUpperCase(); });
... | conditional_block |
jherax.js | //******************************
// Utils for validations
// Author: David Rivera
// Created: 26/06/2013
//******************************
// jherax.github.io
// github.com/jherax/js-utils
//******************************
;
// Essential JavaScript Namespacing Patterns
// http://addyosmani.com/blog/essential-js-namesp... | return "{" + arr.join(",") + "}";
};
//-----------------------------------
// Escaping user input to be treated as a literal string within a regular expression
function fnEscapeRegExp(txt){
if (typeof txt !== "string") return null;
return txt.replace(/([.*+?=!:${}()|\^\[\]\/\\])/... | (typeof val === "string" ? "\"" + val + "\"" : val));
arr.push(prop);
}); | random_line_split |
lib.rs | #[macro_use]
extern crate serde_derive;
extern crate argon2;
extern crate libc;
extern crate liner;
#[macro_use]
extern crate failure;
extern crate pkgutils;
extern crate rand;
extern crate redoxfs;
extern crate syscall;
extern crate termion;
mod config;
mod disk_wrapper;
pub use config::Config;
pub use config::file:... | )
}
pub fn install<P, S>(config: Config, output: P, cookbook: Option<S>, live: bool)
-> Result<()> where
P: AsRef<Path>,
S: AsRef<str>,
{
println!("Install {:#?} to {}", config, output.as_ref().display());
if output.as_ref().is_dir() {
install_dir(config, output, cookbook)
... | with_redoxfs(
disk_redoxfs,
password_opt,
callback | random_line_split |
lib.rs | #[macro_use]
extern crate serde_derive;
extern crate argon2;
extern crate libc;
extern crate liner;
#[macro_use]
extern crate failure;
extern crate pkgutils;
extern crate rand;
extern crate redoxfs;
extern crate syscall;
extern crate termion;
mod config;
mod disk_wrapper;
pub use config::Config;
pub use config::file:... |
pub fn with_redoxfs<D, T, F>(disk: D, password_opt: Option<&[u8]>, callback: F)
-> Result<T> where
D: Disk + Send + 'static,
F: FnOnce(&Path) -> Result<T>
{
let mount_path = if cfg!(target_os = "redox") {
"file/redox_installer"
} else {
"/tmp/redox_installer"
};
if... | {
//let mut context = liner::Context::new();
macro_rules! prompt {
($dst:expr, $def:expr, $($arg:tt)*) => (if config.general.prompt {
Err(io::Error::new(
io::ErrorKind::Other,
"prompt not currently supported"
))
// match unwrap_or_prom... | identifier_body |
lib.rs | #[macro_use]
extern crate serde_derive;
extern crate argon2;
extern crate libc;
extern crate liner;
#[macro_use]
extern crate failure;
extern crate pkgutils;
extern crate rand;
extern crate redoxfs;
extern crate syscall;
extern crate termion;
mod config;
mod disk_wrapper;
pub use config::Config;
pub use config::file:... | <P, F, T>(disk_path: P, bootloader_bios: &[u8], bootloader_efi: &[u8], password_opt: Option<&[u8]>, callback: F)
-> Result<T> where
P: AsRef<Path>,
F: FnOnce(&Path) -> Result<T>
{
let target = get_target();
let bootloader_efi_name = match target.as_str() {
"aarch64-unknown-redox" =>... | with_whole_disk | identifier_name |
verify.rs | //! The proof verifier itself.
//!
//! This is structured as an analysis pass, however it does not have any outputs
//! beyond the error indications. In particular, it does not generate parsed
//! proofs as a side effect; the proof parser will need to be a separate module.
//!
//! The majority of time spent verifying ... | <P: ProofBuilder>(state: &mut VerifyState<P>, label: TokenPtr) -> Result<()> {
// it's either an assertion or a hypothesis. $f hyps have pseudo-frames
// which this function can use, $e don't and need to be looked up in the
// local hyp list after the frame lookup fails
let frame = match state.scoper.g... | prepare_step | identifier_name |
verify.rs | //! The proof verifier itself.
//!
//! This is structured as an analysis pass, however it does not have any outputs
//! beyond the error indications. In particular, it does not generate parsed
//! proofs as a side effect; the proof parser will need to be a separate module.
//!
//! The majority of time spent verifying ... | state.builder.build(hyp.address(),
Default::default(),
&state.stack_buffer,
tos..ntos)));
}
/// Adds a named $e hypothesis to the prepared array. These are not kept in the
/// frame arra... | tos..ntos, | random_line_split |
verify.rs | //! The proof verifier itself.
//!
//! This is structured as an analysis pass, however it does not have any outputs
//! beyond the error indications. In particular, it does not generate parsed
//! proofs as a side effect; the proof parser will need to be a separate module.
//!
//! The majority of time spent verifying ... |
}
}
VerifySegment {
source: (*sref).clone(),
diagnostics: diagnostics,
scope_usage: state.scoper.into_usage(),
}
}
/// Calculates or updates the verification result for a database.
pub fn verify(result: &mut VerifyResult,
segments: &Arc<SegmentSet>,
... | {
state.cur_frame = frame;
if let Err(diag) = verify_proof(&mut state, stmt) {
diagnostics.insert(stmt.address(), diag);
}
} | conditional_block |
pat_fitting.py | """ Functionality to fit PAT models
For more details see: https://arxiv.org/abs/1803.10352
@author: diepencjv / eendebakpt
"""
import matplotlib.pyplot as plt
# %% Load packages
import numpy as np
import scipy.constants
import scipy.ndimage
import scipy.signal
from qtt.pgeometry import robustCost
# %%
ueV2Hz = sci... |
elif trans == 'two_ele':
model = two_ele_pat_model
ylfit, ymfit, yrfit = model(x_data, pp)
plt.plot(x_data, ylfit, '-g', label='S-T')
plt.plot(x_data, ymfit, '-r', label='S-S')
plt.plot(x_data, yrfit, '-b', label='T-S')
plt.ylim([np.min(y_data), np.max(y_data)])
# %%
... | model = one_ele_pat_model
yfit = model(x_data, pp)
plt.plot(x_data, yfit, '-g', label=label)
yfit_t0 = model(x_data, np.array([pp[0], pp[1], 0]))
plt.plot(x_data, yfit_t0, '--g') | conditional_block |
pat_fitting.py | """ Functionality to fit PAT models
For more details see: https://arxiv.org/abs/1803.10352
@author: diepencjv / eendebakpt
"""
import matplotlib.pyplot as plt
# %% Load packages
import numpy as np
import scipy.constants
import scipy.ndimage
import scipy.signal
from qtt.pgeometry import robustCost
# %%
ueV2Hz = sci... |
def fit_pat_to_peaks(pp, xd, yd, trans='one_ele', even_branches=[True, True, True], weights=None, xoffset=None, verbose=1, branch_reduction=None):
""" Core fitting function for PAT measurements, based on detected resonance
peaks (see detect_peaks).
Args:
pp (array): initial guess of fit parameters... | return detected_peaks, {'weights': weights, 'detected_peaks': detected_peaks}
# %%
| random_line_split |
pat_fitting.py | """ Functionality to fit PAT models
For more details see: https://arxiv.org/abs/1803.10352
@author: diepencjv / eendebakpt
"""
import matplotlib.pyplot as plt
# %% Load packages
import numpy as np
import scipy.constants
import scipy.ndimage
import scipy.signal
from qtt.pgeometry import robustCost
# %%
ueV2Hz = sci... |
# %%
class pat_score():
def __init__(self, even_branches=[True, True, True], branch_reduction=None):
""" Class to calculate scores for PAT fitting """
self.even_branches = even_branches
self.branch_reduction = branch_reduction
def pat_one_ele_score(self, xd, yd, pp, weights=None, t... | r""" Model for two electron pat
This is \phi = \pm \frac{leverarm}{2} (x - x0) +
\frac{1}{2} \sqrt{( leverarm (x - x0) )^2 + 8 t^2 }
Args:
x_data (array): detuning (mV)
pp (array): xoffset (mV), leverarm (ueV/mV) and t (ueV)
"""
if len(pp) == 1:
pp = pp[0]
xoffset ... | identifier_body |
pat_fitting.py | """ Functionality to fit PAT models
For more details see: https://arxiv.org/abs/1803.10352
@author: diepencjv / eendebakpt
"""
import matplotlib.pyplot as plt
# %% Load packages
import numpy as np
import scipy.constants
import scipy.ndimage
import scipy.signal
from qtt.pgeometry import robustCost
# %%
ueV2Hz = sci... | (pp, xd, yd, trans='one_ele', even_branches=[True, True, True], weights=None, xoffset=None, verbose=1, branch_reduction=None):
""" Core fitting function for PAT measurements, based on detected resonance
peaks (see detect_peaks).
Args:
pp (array): initial guess of fit parameters
xd (array): ... | fit_pat_to_peaks | identifier_name |
gpkg.go | // +build cgo
package gpkg
import (
"database/sql"
"fmt"
"os"
"strings"
"github.com/go-spatial/geom"
_ "github.com/mattn/go-sqlite3"
)
const (
// SQLITE3 is the database driver name
SQLITE3 = "sqlite3"
// ApplicationID is the required application id for the file
ApplicationID = 0x47504B47 // "GPKG"
// ... |
srss := make([]SpatialReferenceSystem, 0, len(KnownSRS))
// Now need to add SRS that we know about
for _, srs := range KnownSRS {
srss = append(srss, srs)
}
return h.UpdateSRS(srss...)
}
// AddGeometryTable will add the given features table to the metadata tables
// This should be called after creating the ta... | {
_, err := h.Exec(sql)
if err != nil {
return err
}
} | conditional_block |
gpkg.go | // +build cgo
package gpkg
import (
"database/sql"
"fmt"
"os"
"strings"
"github.com/go-spatial/geom"
_ "github.com/mattn/go-sqlite3"
)
const (
// SQLITE3 is the database driver name
SQLITE3 = "sqlite3"
// ApplicationID is the required application id for the file
ApplicationID = 0x47504B47 // "GPKG"
// ... |
// Validate that the value already exists in the data base.
err := h.QueryRow(validateSRSSQL, table.SRS).Scan(&count)
if err != nil {
return err
}
if count == 0 {
// let's check known srs's to see if we have it and can add it.
srsdef, ok := KnownSRS[table.SRS]
if !ok {
return fmt.Errorf("unknown srs: %... | count int
) | random_line_split |
gpkg.go | // +build cgo
package gpkg
import (
"database/sql"
"fmt"
"os"
"strings"
"github.com/go-spatial/geom"
_ "github.com/mattn/go-sqlite3"
)
const (
// SQLITE3 is the database driver name
SQLITE3 = "sqlite3"
// ApplicationID is the required application id for the file
ApplicationID = 0x47504B47 // "GPKG"
// ... | (h *Handle) error {
// Set the pragma's that we need to set for this file
_, err := h.Exec(initialSQL)
if err != nil {
return err
}
// Make sure the required metadata tables are available
for _, sql := range []string{TableSpatialRefSysSQL, TableContentsSQL, TableGeometryColumnsSQL} {
_, err := h.Exec(sql)
i... | initHandle | identifier_name |
gpkg.go | // +build cgo
package gpkg
import (
"database/sql"
"fmt"
"os"
"strings"
"github.com/go-spatial/geom"
_ "github.com/mattn/go-sqlite3"
)
const (
// SQLITE3 is the database driver name
SQLITE3 = "sqlite3"
// ApplicationID is the required application id for the file
ApplicationID = 0x47504B47 // "GPKG"
// ... |
// AddGeometryTable will add the given features table to the metadata tables
// This should be called after creating the table.
func (h *Handle) AddGeometryTable(table TableDescription) error {
const (
validateSRSSQL = `
SELECT Count(*)
FROM gpkg_spatial_ref_sys
WHERE
srs_id=?
`
validateTableField... | {
// Set the pragma's that we need to set for this file
_, err := h.Exec(initialSQL)
if err != nil {
return err
}
// Make sure the required metadata tables are available
for _, sql := range []string{TableSpatialRefSysSQL, TableContentsSQL, TableGeometryColumnsSQL} {
_, err := h.Exec(sql)
if err != nil {
... | identifier_body |
test_wikipedia.py | import sys
import time
import datetime
import unittest
import re
import random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import pages
class WikipediaCommon(unittest.TestCase):
def setUp(self)... |
elif browser == 'ie':
self.driver = webdriver.Ie()
elif browser == 'chrome':
self.driver = webdriver.Chrome(executable_path='/selenium_browser_drivers/chromedriver')
elif browser == 'safari':
self.driver = webdriver.Safari()
self.driver.set_window_position(20,20)
self.driver.set_window_size(1200,8... | self.driver = webdriver.Firefox(executable_path='/selenium_browser_drivers/geckodriver') | conditional_block |
test_wikipedia.py | import sys
import time
import datetime
import unittest
import re
import random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import pages
class WikipediaCommon(unittest.TestCase):
def setUp(self)... | text into search term, but not submit
def type_search(self, search_term):
self.home.enter_search_term(search_term)
def verify_suggestions_start_with(self, search_term):
prefix = search_term.lower()
for suggestion in self.home.get_search_suggestions():
title = suggestion['title'].lower()
self.assertTrue(t... | x = "^{0}.*".format(search_term)
encoded_search_term = search_term.replace(" ", "_")
url_regex = ".*{0}$".format(encoded_search_term)
article = pages.ArticlePage(self.driver)
s = article.get_page_title()
self.assertTrue(re.search(title_regex, s),
"Page title '{}' does not start with search term '{}'".f... | identifier_body |
test_wikipedia.py | import sys
import time
import datetime
import unittest
import re
import random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import pages
class WikipediaCommon(unittest.TestCase):
def setUp(self)... | rch_term, expected_values):
self.open_article_by_search(search_term)
article = pages.ArticlePage(self.driver)
infobox = article.get_infobox_contents()
# check expected values are in info box
for (label, expected_value) in expected_values:
found_value = article.get_value_from_infobox_contents(infobox, lab... | st(self, sea | identifier_name |
test_wikipedia.py | import sys
import time
import datetime
import unittest
import re
import random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import pages
class WikipediaCommon(unittest.TestCase):
def setUp(self)... | def test_main_current_events_page(self):
self.navigate_to_current_events_page()
now = datetime.datetime.now()
self.verify_date_headers(
now.strftime('%B'), now.strftime('%Y'), days_ascending=False)
#@unittest.skip('')
def test_main_archived_current_events_page(self):
if browser == "safari":
self.skipT... |
class TestCurrentEventsPage(WikipediaCommon):
#@unittest.skip('') | random_line_split |
instruction.rs | use std::fmt;
use std::hash;
enum_from_primitive! {
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
// Two-operand opcodes (2OP)
OP2_1 = 1, OP2_2 = 2, OP2_3 = 3, OP2_4 = 4, OP2_5 = 5, OP2_6 = 6,
OP2_7 = 7, OP2_8 = 8, ... |
pub fn should_advance(&self, version: u8) -> bool {
!self.does_call(version) && self.opcode != Opcode::OP0_181 && self.opcode != Opcode::OP0_182
}
}
impl hash::Hash for Instruction {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
state.write_usize(se... | {
use self::Opcode::*;
match self.opcode {
OP2_25 | OP2_26 | OP1_136 | VAR_224 | VAR_236 | VAR_249 | VAR_250 => true,
OP1_143 => version >= 4,
_ => false,
}
} | identifier_body |
instruction.rs | use std::fmt;
use std::hash;
enum_from_primitive! {
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
// Two-operand opcodes (2OP)
OP2_1 = 1, OP2_2 = 2, OP2_3 = 3, OP2_4 = 4, OP2_5 = 5, OP2_6 = 6,
OP2_7 = 7, OP2_8 = 8, ... | (bytes: &[u8]) -> Vec<OperandType> {
bytes
.iter()
.fold(Vec::new(), |mut acc, n| {
acc.push((n & 0b1100_0000) >> 6);
acc.push((n & 0b0011_0000) >> 4);
acc.push((n & 0b0000_1100) >> 2);
acc.push(n & 0b0000_0011);
... | from | identifier_name |
instruction.rs | use std::fmt;
use std::hash;
enum_from_primitive! {
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
// Two-operand opcodes (2OP)
OP2_1 = 1, OP2_2 = 2, OP2_3 = 3, OP2_4 = 4, OP2_5 = 5, OP2_6 = 6,
OP2_7 = 7, OP2_8 = 8, ... | pub addr: usize,
pub opcode: Opcode,
pub name: String,
pub operands: Vec<Operand>,
pub store: Option<u8>,
pub branch: Option<Branch>,
pub text: Option<String>,
pub next: usize,
}
impl Instruction {
pub fn does_store(opcode: Opcode, version: u8) -> bool {
use self... |
#[derive(Debug)]
pub struct Instruction {
| random_line_split |
call_addr_alter.py | #coding: utf-8
import json
import re
# import sys
import time
import pandas as pd
from pandas import DataFrame, Series
# from datetime import datetime
# import pymysql
from call_history_addr_alter import mysql_connection as my
'''
1.利用mysql过滤:
call_addr为“未知”,“-”,“������������”及null
2.原数据形式:
“郑州”、“抚顺;沈阳;铁岭”(可能不在同一个省)... | -----------------------------
#目前中国的二级行政区由市和盟,自治州,地区组成,分别用data_2, data_3, data_4表示。另外还要考虑省辖县。
data_2 = data[(data['addr'].str.contains('市')|(data['addr'].str.contains('盟'))|(data['id']%10000//1000==9))]
for data_2_item in data_2.index:
data_2.ix[data_2_item, 'addr'] = data_2.ix[data_2_item, 'addr'][... | ---- | conditional_block |
call_addr_alter.py | #coding: utf-8
import json
import re
# import sys
import time
import pandas as pd
from pandas import DataFrame, Series
# from datetime import datetime
# import pymysql
from call_history_addr_alter import mysql_connection as my
'''
1.利用mysql过滤:
call_addr为“未知”,“-”,“������������”及null
2.原数据形式:
“郑州”、“抚顺;沈阳;铁岭”(可能不在同一个省)... | if province_word not in ['北京', '天津', '上海', '重庆', '香港', '澳门']:
# print(province_word, '***********************************************************')
#找到含有该省名的地址,比如 海南
data_province_index = data_old[data_old["call_addr"].str.contains(province_word)].index
data_old.i... | #找出既有省名又有市名的数据------------------------------------------------------------------------------------------------------------
#遍历每一个省名
for index_province in province.index:
province_word = province.ix[index_province, 'addr_new'] | random_line_split |
call_addr_alter.py | #coding: utf-8
import json
import re
# import sys
import time
import pandas as pd
from pandas import DataFrame, Series
# from datetime import datetime
# import pymysql
from call_history_addr_alter import mysql_connection as my
'''
1.利用mysql过滤:
call_addr为“未知”,“-”,“������������”及null
2.原数据形式:
“郑州”、“抚顺;沈阳;铁岭”(可能不在同一个省)... | = pd.ExcelWriter(path + file_name[:-4] + '.xlsx')
data.to_excel(writer, 'sheet1')
writer.save()
print('本地文件已生成,获取的数据一共%d行\n'%len(data))
print('函数已经结束,共花费时间%d'%(time.time()-start_1))
#读取本地的通话记录文件,并增加新列
def read_local_data():
#不含中文的数据,或者含有国外名称的数据
#既有一级行政区又有二级行政区的数据
#只有二级行政区的数据
#只有三级行政区的数... | addr_alter_test.csv'
print('get_local_data()函数正在执行,请稍候...')
select_string = '''
select call_addr from call_history
group by call_addr
'''
columns = ['call_addr']
data = my.mysql_connection(select_string, columns)
print('正在生成本地文件,请稍候...')
data.to_csv(path + file_name, index=False, sep='\t',... | identifier_body |
call_addr_alter.py | #coding: utf-8
import json
import re
# import sys
import time
import pandas as pd
from pandas import DataFrame, Series
# from datetime import datetime
# import pymysql
from call_history_addr_alter import mysql_connection as my
'''
1.利用mysql过滤:
call_addr为“未知”,“-”,“������������”及null
2.原数据形式:
“郑州”、“抚顺;沈阳;铁岭”(可能不在同一个省)... | = 'call_addr_alter_test.csv'
print('get_local_data()函数正在执行,请稍候...')
select_string = '''
select call_addr from call_history
group by call_addr
'''
columns = ['call_addr']
data = my.mysql_connection(select_string, columns)
print('正在生成本地文件,请稍候...')
data.to_csv(path + file_name, index=False, s... | ile_name_test | identifier_name |
find.py | # Copyright 2014 Jetperch LLC - See LICENSE file.
"""
Find images using a variety of techniques.
This software is heavily based upon and copies some code from the following
opencv samples:
* https://github.com/Itseez/opencv/blob/master/samples/python2/find_obj.py
* https://github.com/Itseez/opencv/blob/master/samples... | (self, image, data=None):
"""Add a new target to the serach list.
:param image: The image containing just the target.
:param data: Additional user data. Defaults to None.
:raises ValueError: If the image is insufficient.
"""
keypoints, descriptors = self._detect... | add_target | identifier_name |
find.py | # Copyright 2014 Jetperch LLC - See LICENSE file.
"""
Find images using a variety of techniques.
This software is heavily based upon and copies some code from the following
opencv samples:
* https://github.com/Itseez/opencv/blob/master/samples/python2/find_obj.py
* https://github.com/Itseez/opencv/blob/master/samples... | H = np.array([[0., 0., x0], [0., 0., y0], [0., 0., 1.0]])
return TrackedTarget(target, image, [(0, 0)], [(x0, y0)], H, quad) | random_line_split | |
find.py | # Copyright 2014 Jetperch LLC - See LICENSE file.
"""
Find images using a variety of techniques.
This software is heavily based upon and copies some code from the following
opencv samples:
* https://github.com/Itseez/opencv/blob/master/samples/python2/find_obj.py
* https://github.com/Itseez/opencv/blob/master/samples... |
features = Features(search_spec)
features.add_target(image_to_find)
tracked = features.find(image, kwargs.get('k'), kwargs.get('ratio'))
if not len(tracked):
raise FindError(1.0, None)
return tracked[0]
def _find_using_template(image_to_find, image, threshold=None, **kwargs):
"""Searc... | return _find_using_template(image_to_find, image, **kwargs) | conditional_block |
find.py | # Copyright 2014 Jetperch LLC - See LICENSE file.
"""
Find images using a variety of techniques.
This software is heavily based upon and copies some code from the following
opencv samples:
* https://github.com/Itseez/opencv/blob/master/samples/python2/find_obj.py
* https://github.com/Itseez/opencv/blob/master/samples... |
def find(self, image, k=None, ratio=None):
"""Find the targets in the provided image.
:param image: The image to search for targets.
:param k: The number of knnMatches to use. None (Default) uses 2.
:param ratio: The distance ration to use. None (Default) uses 0.75.
... | if color is None:
color = [0, 255, 0]
keypoints, _ = self._detector.detectAndCompute(image, None)
image = image.copy()
return cv2.drawKeypoints(image, keypoints, color=color) | identifier_body |
analyzeAnimatedFrames.py | #!/usr/bin/env python3
"""
analyzes performance of animation rendering, based on files
"""
# standard library modules
import argparse
import collections
import contextlib
from concurrent import futures
import datetime
import getpass
import json
import logging
import math
import os
import socket
import shutil
import si... |
recs.append( decoded )
logger.info( 'topLevelKeys: %s', topLevelKeys )
return recs
def scriptDirPath():
'''returns the absolute path to the directory containing this script'''
return os.path.dirname(os.path.realpath(__file__))
def instanceDpr( inst ):
#logger.info( 'NCSC Inst details ... | topLevelKeys[ key ] += 1 | conditional_block |
analyzeAnimatedFrames.py | #!/usr/bin/env python3
"""
analyzes performance of animation rendering, based on files
"""
# standard library modules
import argparse
import collections
import contextlib
from concurrent import futures
import datetime
import getpass
import json
import logging
import math
import os
import socket
import shutil
import si... | ():
'''returns the absolute path to the directory containing this script'''
return os.path.dirname(os.path.realpath(__file__))
def instanceDpr( inst ):
#logger.info( 'NCSC Inst details %s', inst )
# cpuarch: string like "aarch64" or "armv7l"
# cpunumcores: int
# cpuspeeds: list of floa... | scriptDirPath | identifier_name |
analyzeAnimatedFrames.py | #!/usr/bin/env python3
"""
analyzes performance of animation rendering, based on files
"""
# standard library modules
import argparse
import collections
import contextlib
from concurrent import futures
import datetime
import getpass
import json
import logging
import math
import os
import socket
import shutil
import si... | if 'exception' in decoded:
logger.info( 'exception %s for %s', decoded['exception'], iid )
badOnes.add( iid )
if 'timeout' in decoded:
#logger.info( 'timeout %s for %s', decoded['timeout'], iid )
badOnes.add( iid )
return byInst... | badOnes.add( iid ) | random_line_split |
analyzeAnimatedFrames.py | #!/usr/bin/env python3
"""
analyzes performance of animation rendering, based on files
"""
# standard library modules
import argparse
import collections
import contextlib
from concurrent import futures
import datetime
import getpass
import json
import logging
import math
import os
import socket
import shutil
import si... |
def scriptDirPath():
'''returns the absolute path to the directory containing this script'''
return os.path.dirname(os.path.realpath(__file__))
def instanceDpr( inst ):
#logger.info( 'NCSC Inst details %s', inst )
# cpuarch: string like "aarch64" or "armv7l"
# cpunumcores: int
# cpuspee... | '''read JLog file, return list of decoded objects'''
recs = []
topLevelKeys = collections.Counter() # for debugging
# demux by instance
with open( inFilePath, 'rb' ) as inFile:
for line in inFile:
decoded = json.loads( line )
if isinstance( decoded, dict ):
... | identifier_body |
shell.py | # -*- coding: utf-8 -*-
# import os
# os.chdir('D:/Denis/python/freemind-tools')
import sys
# sys.path.append('D:/Denis/python/freemind-tools')
import os.path
import re
from datetime import date, datetime
from pprint import pprint
import freemind
BTN_OK = 'button_ok'
BTN_STOP = 'stop-sign'
BTN_CANCEL = 'button_c... | (path=None, select='', filter=''):
check_path(path)
doc = freemind.freemind_load(path)
result = nodes_select(doc, select)
result = nodes_filter(result, filter)
return result
def todo_command(path=None, select='', filter='', group='', format='flag title {attrs} icon'):
result = query_nodes(path... | query_nodes | identifier_name |
shell.py | # -*- coding: utf-8 -*-
# import os
# os.chdir('D:/Denis/python/freemind-tools')
import sys
# sys.path.append('D:/Denis/python/freemind-tools')
import os.path
import re
from datetime import date, datetime
from pprint import pprint
import freemind
BTN_OK = 'button_ok'
BTN_STOP = 'stop-sign'
BTN_CANCEL = 'button_c... |
def estimate_command(path=None, format=' - {grandparent}/{parent}/{title}, {@estimate}h'):
check_path(path)
def fn_list(n):
if not hasattr(fn_list, 'result'):
fn_list.result = []
fn_list.total = 0
if n.has_attr('estimate'):
if n.has_attr('@ICON') and BT... | check_path(path)
def fn_list(n):
if not hasattr(fn_list, 'counter'):
fn_list.counter = 1
if n.has_attr('@ICON') and 'help' in n.get_attr('@ICON'):
print("%s. %s\n %s\n" % (fn_list.counter, n.get_title(), n.get_content()))
fn_list.counter += 1
... | identifier_body |
shell.py | # -*- coding: utf-8 -*-
# import os
# os.chdir('D:/Denis/python/freemind-tools')
import sys
# sys.path.append('D:/Denis/python/freemind-tools')
import os.path
import re
from datetime import date, datetime
from pprint import pprint
import freemind
BTN_OK = 'button_ok'
BTN_STOP = 'stop-sign'
BTN_CANCEL = 'button_c... |
icon = ", ".join(format_icons(node.get_attr('@ICON')))
if node.has_content():
content = "--\n%s\n--\n" % node.get_content()
else:
content = ''
# return "%s%s / %s {%s} %s" % (flag, parent, node.get_title(), ", ".join(attrs), node.get_attr('@ICON'))
# print(format.replace('icon', ... | grandparent = node.get_parent().get_parent().get_title() | conditional_block |
shell.py | # -*- coding: utf-8 -*-
# import os
# os.chdir('D:/Denis/python/freemind-tools')
import sys
# sys.path.append('D:/Denis/python/freemind-tools')
import os.path
import re
from datetime import date, datetime
from pprint import pprint
import freemind
BTN_OK = 'button_ok'
BTN_STOP = 'stop-sign'
BTN_CANCEL = 'button_c... | print(level * ' ' + nodes.get_title())
if nodes.has_content():
content = nodes.get_content()
l = level + 1
print(l * ' ' + '---')
delim = l * ' '
print(delim + ('\n' + delim).join(content.split("\n")))
print(l * ' ' ... | def display_nodes(nodes:list, level=0):
if type(nodes) is freemind.FreeMindNode: | random_line_split |
script2.js | $(document).ready(function(){
// Fonction d'ajustement
function ajustResp(){
// Ajustement pour le responsive
var largeur_fen = $(window).width()-200; // Largeur de la fenêtre
var hauteur_fen = $("#size").height();
var largeur_el = $(".note").width(); // Largeur d'une note
var hauteur_el = $(".note").hei... | .click(function(event) { // deconnexion
majPos("traitement/deco");
});
$('.note').mousedown(function(event) { // Lorsqu'on presse l'élément
$(this).css('background-color', '#bfb172');
$(this).css('z-index', 1000);
});
// Gestion du positionnement auto
$('.note').mouseup(function(event) { // Lorsqu'on relâc... | ({
url: 'traitement/saveOne.php',
type: 'POST',
dataType: 'text',
data: {tableJson: tableJson,
indice: indice}
})
.done(function() {
console.log("done");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
$("#deco") | identifier_body |
script2.js | $(document).ready(function(){
// Fonction d'ajustement
function ajustResp(){
// Ajustement pour le responsive
var largeur_fen = $(window).width()-200; // Largeur de la fenêtre
var hauteur_fen = $("#size").height();
var largeur_el = $(".note").width(); // Largeur d'une note
var hauteur_el = $(".note").hei... | ch(tableJson, function(numCours,objet) {
// Si le num est différent de celui demandé
if(numCours != numNote)
newtableJson[numCours]={"posL":objet.posL,"posT":objet.posT};
});
// On reconstruit le tableau à partir du nouveau exempt du num à supprimer
var newNum = 0;
tableJson = {};
$.each(newtableJ... | au
$.ea | identifier_name |
script2.js | $(document).ready(function(){
// Fonction d'ajustement
function ajustResp(){
// Ajustement pour le responsive
var largeur_fen = $(window).width()-200; // Largeur de la fenêtre
var hauteur_fen = $("#size").height();
var largeur_el = $(".note").width(); // Largeur d'une note
var hauteur_el = $(".note").hei... | if(confirm("Confirmer-vous la suppression de cette note ?")){
$.post("traitement/suppression.php",{IdNote :id}, function(data) {
if(data == "ok"){
// On réinitialise le tableau json
reiniTable(numNote);
// On sauvegarde puis on recharge la page
saveNewIndice("traitement/reload");
}else... | var numNote = $(this).parent().parent()[0].className;
numNote = numNote.replace("grbt ", ""); // Le numéro de la note
| random_line_split |
peer.rs | use config;
use dt::{Set};
use proto::{Request, Response, Transport};
use tokio_core::channel::{channel, Sender, Receiver};
use tokio_core::reactor::Handle;
use tokio_core::net::TcpStream;
use tokio_service::Service;
use tokio_proto::easy::{EasyClient, multiplex};
use tokio_timer::{Timer, Sleep};
use futures::{Future... | reactor_handle: handle.clone(),
timer: timer.clone(),
// Initialize in the "waiting to connect" state but with a 0 length
// sleep. This will effectively initiate the connect immediately
state: State::Waiting(timer.sleep(Duration::from_millis(0))),
... | rx: rx,
route: route, | random_line_split |
peer.rs | use config;
use dt::{Set};
use proto::{Request, Response, Transport};
use tokio_core::channel::{channel, Sender, Receiver};
use tokio_core::reactor::Handle;
use tokio_core::net::TcpStream;
use tokio_service::Service;
use tokio_proto::easy::{EasyClient, multiplex};
use tokio_timer::{Timer, Sleep};
use futures::{Future... | (&mut self) -> Poll<(), ()> {
trace!(" --> process peer connection");
let service = match self.state {
State::Connected(ref mut service) => service,
_ => unreachable!(),
};
// The connection is currently in the connected state. If there are any
// pen... | process_connected | identifier_name |
peer.rs | use config;
use dt::{Set};
use proto::{Request, Response, Transport};
use tokio_core::channel::{channel, Sender, Receiver};
use tokio_core::reactor::Handle;
use tokio_core::net::TcpStream;
use tokio_service::Service;
use tokio_proto::easy::{EasyClient, multiplex};
use tokio_timer::{Timer, Sleep};
use futures::{Future... |
fn process_response(&mut self) -> Poll<(), ()> {
trace!(" --> process peer response");
// Check the response future. If it is complete, see if it is a
// successful response or if the connection needs to be re-established
let response = match self.pending_response {
... | {
trace!(" --> process peer connection");
let service = match self.state {
State::Connected(ref mut service) => service,
_ => unreachable!(),
};
// The connection is currently in the connected state. If there are any
// pending replication requests, th... | identifier_body |
test4.py |
import arcade
import random
import math
import os
#from arcade.experimental.camera import Camera2D
from arcade import Point, Vector
from arcade.utils import _Vec2
import time
import pyglet
from typing import cast
import pprint
import pyglet.input.base
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
SCREEN_TITLE = "... |
def on_draw(self):
""" Draw this view """
arcade.start_render()
arcade.draw_text("Instructions Screen", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2,
arcade.color.WHITE, font_size=50, anchor_x="center")
arcade.draw_text("Click to advance", SCREEN_WIDTH / 2, SCREEN_H... | """ This is run once when we switch to this view """
arcade.set_background_color(arcade.csscolor.DARK_SLATE_BLUE)
arcade.set_viewport(0, SCREEN_WIDTH - 1, 0, SCREEN_HEIGHT - 1) | identifier_body |
test4.py |
import arcade
import random
import math
import os
#from arcade.experimental.camera import Camera2D
from arcade import Point, Vector
from arcade.utils import _Vec2
import time
import pyglet
from typing import cast
import pprint
import pyglet.input.base
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
SCREEN_TITLE = "... | (self, _joystick, button):
""" Handle button-down event for the joystick """
print("Button {} down".format(button))
if button == JUMPBTN:
iced_ground_contact_list = arcade.check_for_collision_with_list(self.player_list[0], self.lowfric_list)
if iced_ground_contact_list... | on_joybutton_press | identifier_name |
test4.py |
import arcade
import random
import math
import os
#from arcade.experimental.camera import Camera2D
from arcade import Point, Vector
from arcade.utils import _Vec2
import time
import pyglet
from typing import cast
import pprint
import pyglet.input.base
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
SCREEN_TITLE = "... |
elif self.player.shoot_right_pressed:
self.spawn_bullet(0)
elif self.player.shoot_up_pressed:
self.spawn_bullet(90)
elif self.player.shoot_left_pressed:
self.spawn_bullet(180)
elif self.player.shoot_down_pressed:
... | self.spawn_bullet(270+45) | conditional_block |
test4.py | import arcade
import random
import math
import os
#from arcade.experimental.camera import Camera2D
from arcade import Point, Vector
from arcade.utils import _Vec2
import time
import pyglet
from typing import cast
import pprint
import pyglet.input.base
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
SCREEN_TITLE = "test... | print("z {}".format(joy.z))
print("rx {}".format(joy.rx))
print("ry {}".format(joy.ry))
print("rz {}".format(joy.rz))
print("hat_x {}".format(joy.hat_x))
print("hat_y {}".format(joy.hat_y))
print("buttons {}".format(joy.buttons))
print("========== Extra joy")
... | print("y {}".format(joy.y)) | random_line_split |
ip.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, LLC
#
# 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 applicabl... | (line):
"""
Parse the line of `ip addr show` that contains the interface name, MTU, and
flags.
"""
retval = {}
m = re.match(
'[0-9]+: (?P<if>\w+\d{1,3}): <(?P<flags>[^>]+)> mtu (?P<mtu>[0-9]+)',
line
)
if m:
retval['ifname'] = m.group('if')
retval['mtu'] =... | _parse_head | identifier_name |
ip.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, LLC
#
# 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 applicabl... |
def _parse_head(line):
"""
Parse the line of `ip addr show` that contains the interface name, MTU, and
flags.
"""
retval = {}
m = re.match(
'[0-9]+: (?P<if>\w+\d{1,3}): <(?P<flags>[^>]+)> mtu (?P<mtu>[0-9]+)',
line
)
if m:
retval['ifname'] = m.group('if')
... | """
Parse details for an interface, given its data from `ip addr show <ifname>`
:rtype: akanda.router.models.Interface
"""
retval = dict(addresses=[])
for line in data.split('\n'):
if line.startswith(' '):
line = line.strip()
if line.startswith('inet'):
... | identifier_body |
ip.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, LLC
#
# 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 applicabl... | l = l.strip()
if l.startswith('default'):
match = re.search('via (?P<gateway>[^ ]+)', l)
if match:
return match.group('gateway')
def _set_default_gateway(self, gateway_ip, ifname):
"""
Sets the default g... | except:
# assume the route is missing and use defaults
pass
else:
for l in cmd_out.splitlines(): | random_line_split |
ip.py | # Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, LLC
#
# 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 applicabl... |
def _set_default_gateway(self, gateway_ip, ifname):
"""
Sets the default gateway.
:param gateway_ip: the IP address to set as the default gateway_ip
:type gateway_ip: netaddr.IPAddress
:param ifname: the interface name (in our case, of the external
n... | l = l.strip()
if l.startswith('default'):
match = re.search('via (?P<gateway>[^ ]+)', l)
if match:
return match.group('gateway') | conditional_block |
lib.rs | #![cfg_attr(docsrs, doc = include_str!("../README.md"))]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, deny(missing_docs))]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![allow(unused_unsafe)]
//!
//! ## data structures
//!
//! `cordyceps` provides implementations of t... | ///
/// Suppose we have an entry type like this:
/// ```rust
/// use cordyceps::list;
///
/// struct Entry {
/// links: list::Links<Self>,
/// data: usize,
/// }
/// ```
///
/// The naive implementation of [`links`](Linked::links) for this `Entry` type
/// might look like this:
///
/// ```
/// use cordyceps::Li... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.