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 |
|---|---|---|---|---|
size_cache_fs.go | package kafero
import (
"encoding/json"
"fmt"
"github.com/wangjia184/sortedset"
"io"
"math"
"os"
"path/filepath"
"sync"
"syscall"
"time"
)
// The SizeCacheFS is a cache file system composed of a cache layer and a base layer
// the cache layer has a maximal size, and files get evicted relative to their
// la... | lfile, err := u.cache.Open(name)
if err != nil && bfile == nil {
return nil, err
}
fi, err = u.cache.Stat(name)
if err != nil {
return nil, err
}
uf := NewSizeCacheFile(bfile, lfile, os.O_RDONLY, u, info)
return uf, nil
}
func (u *SizeCacheFS) Mkdir(name string, perm os.FileMode) error {
err := u.base.M... |
// the dirs from cacheHit, cacheStale fall down here:
bfile, _ := u.base.Open(name) | random_line_split |
size_cache_fs.go | package kafero
import (
"encoding/json"
"fmt"
"github.com/wangjia184/sortedset"
"io"
"math"
"os"
"path/filepath"
"sync"
"syscall"
"time"
)
// The SizeCacheFS is a cache file system composed of a cache layer and a base layer
// the cache layer has a maximal size, and files get evicted relative to their
// la... | (name string, flag int, perm os.FileMode) (File, error) {
// Very important, remove from cache to prevent eviction while opening
info := u.getCacheFile(name)
if info != nil {
u.removeFromCache(name)
}
st, _, err := u.cacheStatus(name)
if err != nil {
return nil, err
}
switch st {
case cacheLocal, cacheHi... | OpenFile | identifier_name |
ikey.js | /*
Fluid Project
Copyright (c) 2006, 2007 University of Toronto. All rights reserved.
Licensed under the Educational Community 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.osedu.org/licenses/ECL-2... |
else if (!wrap) {
jQuery(target).after(jQuery.iKey.focusedNode);
}
else {
jQuery(target).before(jQuery.iKey.focusedNode);
}
},
/**
* Process up arrow events
*/
handleUpAction : function(isCtrl, event) {
var target = jQuery(jQuery.iKey.focusedNode).prev();
var wrap = false;
if (!target ||... | {
this.focusNode(target, event);
} | conditional_block |
ikey.js | /*
Fluid Project
Copyright (c) 2006, 2007 University of Toronto. All rights reserved.
Licensed under the Educational Community 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.osedu.org/licenses/ECL-2... | dhe.css('-khtml-user-select', 'none');
}
this.keyCfg = {
domNode : o.domNode ? o.domNode : false,
accept : o.accept || false,
activeclass : o.activeclass || false,
hoverclass : o.hoverclass || false,
helperclass : o.helperclass || false,
axis : /vertical... | }
else {
dhe.css('-moz-user-select', 'none');
dhe.css('user-select', 'none'); | random_line_split |
b_get_data.py | # -*- coding: UTF-8 -*-
""" Main lib for wmillfailprev Project
"""
import os
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn import metrics, model_selection
from sklearn.linear_model import LogisticRegr... | pd.set_option('display.width', 200)
def get_data(file):
'file = full path of the original file. obter os dataframes dos ficheiros'
df = pd.read_csv(file, sep=';')
df = time_transform(df)
df = timestamp_round_down(df)
df = df.bfill()
return df
def logs_cols_uniform(df):
'A partir de uma lis... | from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import roc_auc_score, accuracy_score, log_loss, roc_curve, precision_score, recall_score,confusion_matrix,f1_score,fbeta_score, make_scorer
| random_line_split |
b_get_data.py | # -*- coding: UTF-8 -*-
""" Main lib for wmillfailprev Project
"""
import os
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn import metrics, model_selection
from sklearn.linear_model import LogisticRegr... | rbines_list):
df_ = pd.DataFrame(columns=df.columns, dtype='int64')
for turbine in turbines_list:
df1 = df.loc[df['Turbine_ID']==turbine]
if df1['Component'].nunique()>1:
index = df1[df1['Component']==1]
index['date'] = index['Timestamp']
index = index[['date'... | _by_turbine(df, tu | identifier_name |
b_get_data.py | # -*- coding: UTF-8 -*-
""" Main lib for wmillfailprev Project
"""
import os
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn import metrics, model_selection
from sklearn.linear_model import LogisticRegr... | or_av_cols = [nm+'_av' for nm in sensor_cols]
sensor_sd_cols = [nm+'_sd' for nm in sensor_cols]
df_out = pd.DataFrame()
ws = rolling_win_size
#calculate rolling stats for each engine id
for m_id in pd.unique(df_in.Turbine_ID):
# get a subset for each engine sensors
df_engine = d... | s.append(i)
sens | conditional_block |
b_get_data.py | # -*- coding: UTF-8 -*-
""" Main lib for wmillfailprev Project
"""
import os
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn import metrics, model_selection
from sklearn.linear_model import LogisticRegr... | features(df_in, rolling_win_size=15):
"""Add rolling average and rolling standard deviation for sensors readings using fixed rolling window size.
"""
cols =['Turbine_ID', 'Date', 'TTF', '60_days', 'Component']
other_cols = []
for i in df_in.columns:
if i not in cols:
other_cols.a... | para agregar o data-frame pela medida de tempo pretendida, periodo _Dia_ ou _Hora_'
if period == 'Dia':
df['Date'] = df['Timestamp'].dt.date
elif period == 'Hora':
df['Date'] = df.apply(lambda x: x['Timestamp'] - datetime.timedelta(hours=x['Timestamp'].hour % -1, minutes=x['Timestamp'].minute, ... | identifier_body |
main.go | package main
import (
"database/sql"
"encoding/gob"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
"strings"
"text/template"
)
var database *sql.DB
var store *sessions.CookieStore
var tpl *temp... |
func AddUser( w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
res , _ := database.Exec("INSERT INTO users(username,password) VALUES (?,?)",username,password)
fmt.Println(res)
fmt.Fprintf(w, "User successfully added")
http.Redirect(w, r, "/", http.... | {
session, err := store.Get(r, "cookie-name")
if err != nil {
}
user := getUser(session)
fmt.Println("[serving main page]",user)
tpl.ExecuteTemplate(w, "index.gohtml", user)
} | identifier_body |
main.go | package main
import (
"database/sql"
"encoding/gob"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
"strings"
"text/template"
)
var database *sql.DB
var store *sessions.CookieStore
var tpl *temp... | func retrieveUserId(username string) int {
var dbUser UserData
err := database.QueryRow("SELECT id FROM users WHERE username=$1", username).
Scan(&dbUser.Id)
if err != nil {
fmt.Println("[retrieveUserId] user not found in DB",username)
panic(err)
}
return dbUser.Id
}
func retrieveBookmarkId(url string, use... | }
return dbUser.Password
} | random_line_split |
main.go | package main
import (
"database/sql"
"encoding/gob"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
"strings"
"text/template"
)
var database *sql.DB
var store *sessions.CookieStore
var tpl *temp... | (){
database, _ = sql.Open("sqlite3", "./cisco.db")
createUsersTable, _ := database.Prepare("CREATE TABLE IF NOT EXISTS users (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"username VARCHAR (20) NOT NULL, " +
"password VARCHAR (20) NOT NULL)")
createUsersTable.Exec()
createBookmarksTable, _ := databa... | initDB | identifier_name |
main.go | package main
import (
"database/sql"
"encoding/gob"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
"strings"
"text/template"
)
var database *sql.DB
var store *sessions.CookieStore
var tpl *temp... |
return false
}
func getUserName (w http.ResponseWriter,r *http.Request) string {
var username string
username, _, ok := r.BasicAuth()
if !ok {
session, err := store.Get(r, "cookie-name")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return ""
}
fmt.Println("username retri... | {
if b == a {
return true
}
} | conditional_block |
alpha_beta.py | import numpy as np
#!pip install pygame
import pygame
#from copy import deepcopy
pygame.init()
#-----------
# Modifications (Matthieu, 15/04):
# Modification de la représentation du terrain du jeu. Il est maintenant représenté par une seule liste.
# un seul identifiant par coupe semble plus simple à gérer qu'un... | #joueurMaximisant = joueur pour lequel on veut maximiser le score (0 ou 1)
#On simule ici des situations fictives de jeu de manière récursive (l'I.A. lit en quelque sorte l'avenir pour n=profondeur tours en avance)
self.arbreFils = {}
#on détermine les coups possibles
#si a... | #si aucun coup n'est possible cette fonction arrête aussi la partie
coupesPossibles = self.coupesAdmissibles(self.tour)
if (self.profondeur == self.profondeurMinimax or self.finie): #cas de base
self.value = self.evaluation(joueurMaximisant)
return self.valu... | identifier_body |
alpha_beta.py | import numpy as np
#!pip install pygame
import pygame
#from copy import deepcopy
pygame.init()
#-----------
# Modifications (Matthieu, 15/04):
# Modification de la représentation du terrain du jeu. Il est maintenant représenté par une seule liste.
# un seul identifiant par coupe semble plus simple à gérer qu'un... | #on commence par la coupe la plus proche de l'adversaire (dans le sens trigo)
idCoupe = (self.nCoupes*(joueur+1))-1
distance = 1
while (self.joueurCoupe(idCoupe)==joueur):
#s'il y a plus de graines dans idCoupe que la distance qui la sépare aux coupes de l'adversaire
... | coupesAdmissibles = []
| random_line_split |
alpha_beta.py | import numpy as np
#!pip install pygame
import pygame
#from copy import deepcopy
pygame.init()
#-----------
# Modifications (Matthieu, 15/04):
# Modification de la représentation du terrain du jeu. Il est maintenant représenté par une seule liste.
# un seul identifiant par coupe semble plus simple à gérer qu'un... | .grainesRestantesJoueur(adversaire) == 0:
coupesAdmissibles = self.coupesAdmissiblesNourrir(joueur)
#si aucun coup ne peut être joué pour nourrir l'adversaire
if len(coupesAdmissibles)==0:
self.scores[joueur] += self.grainesRestantes()
self.platea... |
if self | identifier_name |
alpha_beta.py | import numpy as np
#!pip install pygame
import pygame
#from copy import deepcopy
pygame.init()
#-----------
# Modifications (Matthieu, 15/04):
# Modification de la représentation du terrain du jeu. Il est maintenant représenté par une seule liste.
# un seul identifiant par coupe semble plus simple à gérer qu'un... | mpte le nombre de graines restantes sur le plateau
def grainesRestantes(self):
return np.sum(self.plateau)
#on compte le nombre de graines restantes sur le plateau pour les coupes de joueur
def grainesRestantesJoueur(self,joueur):
if joueur==0:
return np.sum(self.plateau[0... | while (self.joueurCoupe(idCoupe)==joueurCoupeFinale and self.coupePrenable(idCoupe)):
self.scores[joueur]+=self.plateau[idCoupe]
self.plateau[idCoupe]=0
idCoupe = self.coupePrecedente(idCoupe)
#si on va affamer l'adversaire :
... | conditional_block |
minilab.py | #!/usr/bin/python
"""
Minilab is a network lab simulator based on
mininet. Its goal is to provide an easy way
to setup and test any kind of complex network.
"""
import subprocess
import shutil
import shlex
import argparse
import yaml
import os
import sys
import glob
from mininet.net import Mininet
from mininet.node... |
def copy_auth_keys(self):
ssh_dir = os.path.join(self.root_dir, 'root/.ssh')
if not os.path.exists(ssh_dir):
os.mkdir(ssh_dir, 0700)
key_file = open(self.auth_keys)
destination = open(os.path.join(ssh_dir, 'authorized_keys'), 'wb')
destination.write(key_file.rea... | return self.ssh_template.render(pid_file=self.ssh_pid_file,
host_dir=self.root_dir) | random_line_split |
minilab.py | #!/usr/bin/python
"""
Minilab is a network lab simulator based on
mininet. Its goal is to provide an easy way
to setup and test any kind of complex network.
"""
import subprocess
import shutil
import shlex
import argparse
import yaml
import os
import sys
import glob
from mininet.net import Mininet
from mininet.node... |
def set_oob_switch_standalone(topology):
if 'nat' in topology:
switch = topology['nat']['switch']['name']
cmd = shlex.split("ovs-vsctl set-fail-mode %s standalone " % switch)
subprocess.call(cmd)
cmd2 = shlex.split("ovs-vsctl del-controller %s" % switch)
subprocess.call(c... | """ force protocols versions as mininet < 2.2.0 is not doing its job"""
for switch in topology['switches']:
if 'protocols' in switch:
protocols = ','.join(switch['protocols'])
else:
protocols = 'OpenFlow10'
cmd = "ovs-vsctl set Bridge %s protocols=%s" % (switch['nam... | identifier_body |
minilab.py | #!/usr/bin/python
"""
Minilab is a network lab simulator based on
mininet. Its goal is to provide an easy way
to setup and test any kind of complex network.
"""
import subprocess
import shutil
import shlex
import argparse
import yaml
import os
import sys
import glob
from mininet.net import Mininet
from mininet.node... | (net, topology):
switches = {}
info('*** Adding switches\n')
# first loop : create switches
for switch in topology['switches']:
if 'protocols' in switch:
protocols = ','.join(switch['protocols'])
else:
protocols = 'OpenFlow10'
switches[switch['name']] = n... | setup_switches | identifier_name |
minilab.py | #!/usr/bin/python
"""
Minilab is a network lab simulator based on
mininet. Its goal is to provide an easy way
to setup and test any kind of complex network.
"""
import subprocess
import shutil
import shlex
import argparse
import yaml
import os
import sys
import glob
from mininet.net import Mininet
from mininet.node... |
ssh_config = self.create_ssh_config()
host_config_path = os.path.join(self.root_dir,
'etc/ssh/sshd_config')
sshf = open(host_config_path, 'wb')
sshf.write(ssh_config)
sshf.close()
info('**** Starting ssh server on %s\n' % self.n... | self.copy_auth_keys() | conditional_block |
get_samples.py | #!/usr/bin/env
#coding:utf8
import re, json, random, sys, jieba
from utils import char_cut
re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>', re.I) # 匹配 CDATA
re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>', re.I) # Script
re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*s... | 0: return m
dp = [[0] * (n + 1) for _ in range(m + 1)] # 初始化dp和边界
for i in range(1, m + 1): dp[i][0] = i
for j in range(1, n + 1): dp[0][j] = j
for i in range(1, m + 1): # 计算dp
for j in range(1, n + 1):
a=word1[i - 1];b=word2[j - 1]
if word1[i - 1] == word2[j - ... | rn n
if n == | identifier_name |
get_samples.py | #!/usr/bin/env
#coding:utf8
import re, json, random, sys, jieba
from utils import char_cut
re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>', re.I) # 匹配 CDATA
re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>', re.I) # Script
re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*s... | le(r'\s*[-\*+]\s*(.+)')
txt = open(src_file, 'r', encoding='utf8').readlines()
for line in txt:
if '## intent:' in line:
label = line.strip().split(':')[-1]
else:
match = re.match(item_regex, line)
if match:
item = match.group(1)
... | open(des_file, 'w', encoding='utf8') as f:
for e in txt:
split_text = e.split('\t')
question = filterHtmlTag(split_text[2])
labels = json.loads((split_text[4]))
if len(labels) == 0 or question.strip() == '': continue
qes_set.add(question)
... | identifier_body |
get_samples.py | #!/usr/bin/env
#coding:utf8
import re, json, random, sys, jieba
from utils import char_cut
re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>', re.I) # 匹配 CDATA
re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>', re.I) # Script
re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*s... | ))
intersection = set(w1).intersection(w2)
union = set(w1).union(set(w2))
if len(intersection) == 0:
return None
dice_dist = 2 * len(intersection) / len(union)
#edit_distance = min_edit_distance(word1, word2)
return dice_dist #/ (edit_distance + 1e-8)
def get_sample(src_file, d... | d2[j - 1]:
d = 0
else:
d = 1
dp[i][j] = min(dp[i - 1][j - 1] + d, dp[i][j - 1] + 1, dp[i - 1][j] + 1)
return dp[m][n]
def words_sim(word1, word2):
w1 = char_cut(word1); w2 = set(char_cut(word2 | conditional_block |
get_samples.py | #!/usr/bin/env
#coding:utf8
import re, json, random, sys, jieba
from utils import char_cut
re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>', re.I) # 匹配 CDATA
re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>', re.I) # Script
re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*s... | #get_fasttext_sample('./data/q1.res', './data/fasttext.train')
#get_ft_data('./data/sen_class_corp666.md', './data/sen_class.train', './data/sen_class.test', './data/sen_class.val')
patt = re.compile(r"活动|策划"); aa=patt.search("活动着")
get_sample_new('./data/q1.res', './data/sen_class.train', './data/se... | #min_edit_distance('求职', '求职应聘')
#get_sample('./data/q1.res', './data/sen_class_corp666.md')
| random_line_split |
foreign.rs | // Copyright 2019 The Grin Developers
//
// 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 agree... |
/// verify slate messages
pub fn verify_slate_messages(slate: &Slate) -> Result<(), Error> {
slate.verify_messages()
}
/// Receive a tx as recipient
/// Note: key_id & output_amounts needed for secure claims, mwc713.
pub fn receive_tx<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Sl... | {
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
} | identifier_body |
foreign.rs | // Copyright 2019 The Grin Developers
//
// 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 agree... | pub fn build_coinbase<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
block_fees: &BlockFees,
test_mode: bool,
) -> Result<CbData, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
}
/// ve... | })
}
/// Build a coinbase transaction | random_line_split |
foreign.rs | // Copyright 2019 The Grin Developers
//
// 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 agree... | () -> Result<VersionInfo, Error> {
// Proof address will be the onion address (Dalec Paublic Key). It is exactly what we need
Ok(VersionInfo {
foreign_api_version: FOREIGN_API_VERSION,
supported_slate_versions: SlateVersion::iter().collect(),
})
}
/// Build a coinbase transaction
pub fn build_coinbase<'a, T: ?S... | check_version | identifier_name |
foreign.rs | // Copyright 2019 The Grin Developers
//
// 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 agree... |
tx::update_message(&mut *w, keychain_mask, &ret_slate)?;
let excess = ret_slate.calc_excess(Some(&keychain))?;
if let Some(ref mut p) = ret_slate.payment_proof {
if p.sender_address
.public_key
.eq(&p.receiver_address.public_key)
{
debug!("file proof, replace the receiver address with its address");... | {
// Add our contribution to the offset
ret_slate.adjust_offset(&keychain, &mut context)?;
} | conditional_block |
inventory.pb.go | /*
Copyright 2019 Cisco Systems
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 in writing, software
d... |
func (m *Inventory) GetBootImageName() string {
if m != nil {
return m.BootImageName
}
return ""
}
func (m *Inventory) GetLoadPath() []*PkgInfo {
if m != nil {
return m.LoadPath
}
return nil
}
func (m *Inventory) GetNodeType() uint64 {
if m != nil {
return m.NodeType
}
return 0
}
func (m *Inventory)... | {
if m != nil {
return m.Minor
}
return 0
} | identifier_body |
inventory.pb.go | /*
Copyright 2019 Cisco Systems
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 in writing, software
d... | func (m *Inventory_KEYS) String() string { return proto.CompactTextString(m) }
func (*Inventory_KEYS) ProtoMessage() {}
func (*Inventory_KEYS) Descriptor() ([]byte, []int) {
return fileDescriptor_7173caedb7c6ae96, []int{0}
}
func (m *Inventory_KEYS) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Inventory... | XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Inventory_KEYS) Reset() { *m = Inventory_KEYS{} } | random_line_split |
inventory.pb.go | /*
Copyright 2019 Cisco Systems
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 in writing, software
d... |
return ""
}
func (m *PkgInfo) GetBuildInformation() string {
if m != nil {
return m.BuildInformation
}
return ""
}
type Inventory struct {
Major uint32 `protobuf:"varint,50,opt,name=major,proto3" json:"major,omitempty"`
Minor uint32 `protobuf:"varint,51,opt,name=mino... | {
return m.Version
} | conditional_block |
inventory.pb.go | /*
Copyright 2019 Cisco Systems
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 in writing, software
d... | (src proto.Message) {
xxx_messageInfo_PkgGroup.Merge(m, src)
}
func (m *PkgGroup) XXX_Size() int {
return xxx_messageInfo_PkgGroup.Size(m)
}
func (m *PkgGroup) XXX_DiscardUnknown() {
xxx_messageInfo_PkgGroup.DiscardUnknown(m)
}
var xxx_messageInfo_PkgGroup proto.InternalMessageInfo
func (m *PkgGroup) GetDeviceName... | XXX_Merge | identifier_name |
Serigne.py | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # Matlab-style plotting
import seaborn as sns
import warnings
from scipy import stats
from scipy.stats import norm, skew #for some statistics
from subprocess import check_output
c... |
############################################################
############## Features engineering ############
# let's first concatenate the train and test data in the same dataframe
ntrain = train.shape[0]
ntest = test.shape[0]
y_train = train.SalePrice.values
all_data = pd.concat((train, test)).reset_index(dro... | # #Get also the QQ-plot
# fig = plt.figure()
# res = stats.probplot(train['SalePrice'], plot=plt)
# plt.show() | random_line_split |
Serigne.py | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # Matlab-style plotting
import seaborn as sns
import warnings
from scipy import stats
from scipy.stats import norm, skew #for some statistics
from subprocess import check_output
c... |
warnings.warn = ignore_warn # ignore annoying warning (from sklearn and seaborn)
pd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) # Limiting floats output to 3 decimal points
# print(check_output(["ls", "../data"]).decode("utf8")) # check the files available in the directory
##########... | pass | identifier_body |
Serigne.py | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # Matlab-style plotting
import seaborn as sns
import warnings
from scipy import stats
from scipy.stats import norm, skew #for some statistics
from subprocess import check_output
c... |
# BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1 and BsmtFinType2 :
# For all these categorical basement-related features, NaN means that there is no basement
for col in ('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'):
all_data[col] = all_data[col].fillna('None')
# MasVnrArea and MasVnr... | all_data[col] = all_data[col].fillna(0) | conditional_block |
Serigne.py | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # Matlab-style plotting
import seaborn as sns
import warnings
from scipy import stats
from scipy.stats import norm, skew #for some statistics
from subprocess import check_output
c... | (*args, **kwargs):
pass
warnings.warn = ignore_warn # ignore annoying warning (from sklearn and seaborn)
pd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) # Limiting floats output to 3 decimal points
# print(check_output(["ls", "../data"]).decode("utf8")) # check the files available ... | ignore_warn | identifier_name |
main.py | # coding=utf-8
# Martin Svonava
# program sluzi na parsovanie HTML rozvrhov na UMBcke
# a tvorbu XMLka ktore sa da dalej spracovavat
# >>>> Struktura dat <<<<
# [0] Nazov hodiny
# [1] Vyucujuci
# [2] Ucebna
# [3] Den
# [4] Zaciatok
# [5] Trvanie
# [6] Nazov Triedy pre ktoru rozvrh plati
from operator import attr... | generate_xml):
make_folder()
global pondelok, utorok, streda, stvrtok, piatok, rozvrh, trieda_nazov
if generate_xml == XML_ONLY or generate_xml == BOTH_XML_ODT:
# cele_rozvrhy_tried = [get_lessons_of_class("http://www.pdf.umb.sk/~jsedliak/Public/rozvrh_tr2815.htm")]
cele_rozvrhy_tried = []
... | enerate_xmls( | identifier_name |
main.py | # coding=utf-8
# Martin Svonava
# program sluzi na parsovanie HTML rozvrhov na UMBcke
# a tvorbu XMLka ktore sa da dalej spracovavat
# >>>> Struktura dat <<<<
# [0] Nazov hodiny
# [1] Vyucujuci
# [2] Ucebna
# [3] Den
# [4] Zaciatok
# [5] Trvanie
# [6] Nazov Triedy pre ktoru rozvrh plati
from operator import attr... |
def get_class_start(title):
# title obsahuje nieco ako "* streda : 14-15 *" - potrebujem dostat len prve cislo
# pretoze aka dlha hodina bude viem z ineho atributu (pozri funkciu get_lessons_of_class, colspan)
# toto mi vrati pole obsahujuce ['streda', '14-15'], vezmem prvy index cize cisla 14-15
zac_... | eturn title['colspan']
| identifier_body |
main.py | # coding=utf-8
# Martin Svonava
# program sluzi na parsovanie HTML rozvrhov na UMBcke
# a tvorbu XMLka ktore sa da dalej spracovavat
# >>>> Struktura dat <<<<
# [0] Nazov hodiny
# [1] Vyucujuci
# [2] Ucebna
# [3] Den
# [4] Zaciatok
# [5] Trvanie
# [6] Nazov Triedy pre ktoru rozvrh plati
from operator import attr... | zac_hod = title['title'].partition('*')[-1].rpartition('*')[0].replace(" ", "").split(':')[1]
# 1 alebo 15 to je v poriadku
# 1-2 a 9-10 -> v oboch pripadoch chcem len prve cislo (dlzka 3 a 4)
# 12-13 -> tu chcem prve dve cisla (dlzka 5)
if len(zac_hod) == 3 or len(zac_hod) == 4:
return za... | # title obsahuje nieco ako "* streda : 14-15 *" - potrebujem dostat len prve cislo
# pretoze aka dlha hodina bude viem z ineho atributu (pozri funkciu get_lessons_of_class, colspan)
# toto mi vrati pole obsahujuce ['streda', '14-15'], vezmem prvy index cize cisla 14-15 | random_line_split |
main.py | # coding=utf-8
# Martin Svonava
# program sluzi na parsovanie HTML rozvrhov na UMBcke
# a tvorbu XMLka ktore sa da dalej spracovavat
# >>>> Struktura dat <<<<
# [0] Nazov hodiny
# [1] Vyucujuci
# [2] Ucebna
# [3] Den
# [4] Zaciatok
# [5] Trvanie
# [6] Nazov Triedy pre ktoru rozvrh plati
from operator import attr... | return zac_hod
def get_lessons_of_class(url_class):
global hlavicka_dni
print "Ziskavam rozvrh z URL " + url_class
src = requests.get(url_class)
txt = src.text
bsoup = BeautifulSoup(txt, "html.parser")
predmety = []
ucitelia = []
ucebne = []
dni = []
zacina_hod = []
... | eturn zac_hod[0:2]
| conditional_block |
renderer.rs | use crate::fft::*;
use crate::Opt;
use anyhow::Result;
use rustfft::num_traits::Zero;
use std::{fs::File, io::Read, path::PathBuf, slice};
use wgpu::util::DeviceExt;
use winit::{event::*, window::Window};
#[repr(transparent)]
#[derive(Copy, Clone)]
struct PodComplex(FftSample);
unsafe impl bytemuck::Zeroable for PodC... | sc_desc,
swap_chain,
size,
render_pipeline,
render_parameters,
fft_vec,
render_parameters_buffer: render_param_buffer,
fft_vec_buffer,
bind_group,
})
}
pub fn resize(&mut self, new_size: winit::d... | device,
queue, | random_line_split |
renderer.rs | use crate::fft::*;
use crate::Opt;
use anyhow::Result;
use rustfft::num_traits::Zero;
use std::{fs::File, io::Read, path::PathBuf, slice};
use wgpu::util::DeviceExt;
use winit::{event::*, window::Window};
#[repr(transparent)]
#[derive(Copy, Clone)]
struct PodComplex(FftSample);
unsafe impl bytemuck::Zeroable for PodC... |
pub fn render(&mut self) {
let frame = self
.swap_chain
.get_current_frame()
.expect("Timeout getting texture")
.output;
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
... | {
self.render_parameters = GpuRenderParameters {
screen_wx: self.size.width,
screen_hy: self.size.height,
..self.render_parameters
};
self.queue.write_buffer(
&self.render_parameters_buffer,
0,
bytemuck::cast_slice(slice::fr... | identifier_body |
renderer.rs | use crate::fft::*;
use crate::Opt;
use anyhow::Result;
use rustfft::num_traits::Zero;
use std::{fs::File, io::Read, path::PathBuf, slice};
use wgpu::util::DeviceExt;
use winit::{event::*, window::Window};
#[repr(transparent)]
#[derive(Copy, Clone)]
struct PodComplex(FftSample);
unsafe impl bytemuck::Zeroable for PodC... | (&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
}
pub fn input(&mut self, event: &WindowEvent) ... | resize | identifier_name |
error.rs | //! Errorand Result types.
use crate::database::Database;
use crate::types::Type;
use std::any::type_name;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::io;
#[allow(unused_macros)]
macro_rules! decode_err {
($s:literal, $($args:tt)*) => {
crate::Error::Decode(format!($s... | #[doc(hidden)]
fn into_box_err(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;
}
impl dyn DatabaseError {
/// Downcast this `&dyn DatabaseError` to a specific database error type:
///
/// * [PgError][crate::postgres::PgError] (if the `postgres` feature is active)
/// * [MySqlErro... | #[doc(hidden)]
fn as_mut_err(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);
| random_line_split |
error.rs | //! Errorand Result types.
use crate::database::Database;
use crate::types::Type;
use std::any::type_name;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::io;
#[allow(unused_macros)]
macro_rules! decode_err {
($s:literal, $($args:tt)*) => {
crate::Error::Decode(format!($s... |
}
impl<'de> Deserialize<'de> for Error {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let r = deserializer.deserialize_string(ErrorVisitor)?;
return Ok(Error::from(r));
}
}
#[test]
fn test_json_error(){
l... | {
Ok(v.to_string())
} | identifier_body |
error.rs | //! Errorand Result types.
use crate::database::Database;
use crate::types::Type;
use std::any::type_name;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::io;
#[allow(unused_macros)]
macro_rules! decode_err {
($s:literal, $($args:tt)*) => {
crate::Error::Decode(format!($s... | <DB: Database, T>(expected: DB::TypeInfo) -> Self
where
T: Type<DB>,
{
let ty_name = type_name::<T>();
return decode_err!(
"mismatched types; Rust type `{}` (as SQL type {}) is not compatible with SQL type {}",
ty_name,
T::type_info(),
... | mismatched_types | identifier_name |
emitter.rs | extern crate xml;
use polyfill;
use std::str::FromStr;
use std::collections::BTreeMap;
/// Parse a float with appropriate panic message on failure.
macro_rules! parse_float {
($s:expr) => (f64::from_str($s).expect("Failed to parse float"))
}
pub struct Color {
r: u8, g: u8, b: u8
}
impl Color {
pub fn ... | (&mut self, attributes: &Vec<xml::attribute::OwnedAttribute>) -> Rect {
// x, y, w, h, style
let mut params = (None, None, None, None, None);
for ref attr in attributes {
let name: &str = &attr.name.local_name;
match name {
"x" ... | parse_rect | identifier_name |
emitter.rs | extern crate xml;
use polyfill;
use std::str::FromStr;
use std::collections::BTreeMap;
/// Parse a float with appropriate panic message on failure.
macro_rules! parse_float {
($s:expr) => (f64::from_str($s).expect("Failed to parse float"))
}
pub struct Color {
r: u8, g: u8, b: u8
}
impl Color {
pub fn ... |
for ref attr in attributes {
let name: &str = &attr.name.local_name;
match name {
"x" => params.0 = Some(attr.value.clone()),
"y" => params.1 = Some(attr.value.clone()),
"width" => params.2 = Some(attr.value.clone()),
... | /// Parse a rect with origin at the bottom right (??)
///
pub fn parse_rect(&mut self, attributes: &Vec<xml::attribute::OwnedAttribute>) -> Rect {
// x, y, w, h, style
let mut params = (None, None, None, None, None); | random_line_split |
emitter.rs | extern crate xml;
use polyfill;
use std::str::FromStr;
use std::collections::BTreeMap;
/// Parse a float with appropriate panic message on failure.
macro_rules! parse_float {
($s:expr) => (f64::from_str($s).expect("Failed to parse float"))
}
pub struct Color {
r: u8, g: u8, b: u8
}
impl Color {
pub fn ... |
fn emit_physics(&self, id: &str, physicsbody: &str) {
println!("// Physics for {}", id);
let emit_shape = |a: &[f64; 2], b: &[f64; 2]|
println!(
"{}->addShape(PhysicsShapeEdgeSegment::create(Vec2({:.10}f, {:.10}f), Vec2({:.10}f, {:.10}f)));",
Emitter::v... | {
println!("// Rect for {}", id);
// arguments: origin, destination, color
println!(
"{}->drawSolidRect(Vec2({:.10}f,{:.10}f), Vec2({:.10}f,{:.10}f), {});",
Emitter::varname(id, drawnode),
self.x, self.y,
self.x+self.w, self.y+self.h,
... | identifier_body |
suicidegirls.py | import time, subprocess, os.path, re, multiprocessing, threading
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class SuicideGirls:
driver = None
dispatcher... |
self.__download_and_save_set(image_urls, girl, title)
self.sets_completed += 1
def __download_and_save_set(self, urls, girl, title):
aria_path = os.path.join(self.exec_dir, "dependencies", "aria2", "aria2c.exe")
error_strings = []
dir_name = os.path.join("Suicide Girls", girl.title(), title.title()... | t(girl.title() + "/" + title.title() + " Img" + str(i).zfill(3) + " already exists, skipping...")
| conditional_block |
suicidegirls.py | import time, subprocess, os.path, re, multiprocessing, threading
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class SuicideGirls:
driver = None
dispatcher... | ame__ == "__main__":
print_warning()
| his file is meant to be imported by other Python files, not run directly. Exiting now.")
if __n | identifier_body |
suicidegirls.py | import time, subprocess, os.path, re, multiprocessing, threading
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class SuicideGirls:
driver = None
dispatcher... | (self, type_xpath):
time_period_xpath = "//li[@class='dropdown'][3]//ul/li/a[text() = '" + self.time_period + "']"
girl_name_xpath = "//article/header//h2/a"
load_more_xpath = "//a[@id='load-more']"
choice = SuicideGirls.driver.find_element_by_xpath(type_xpath)
SuicideGirls.driver.get(choice.get_attribute(... | __rip_all | identifier_name |
suicidegirls.py | import time, subprocess, os.path, re, multiprocessing, threading
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class SuicideGirls:
driver = None
dispatcher... | if len(lmb) > 0 and lmb[0].is_displayed():
lmb[0].click()
time.sleep(10)
else:
break
set_links = list(set(set_links))
for link in set_links:
SuicideGirls.driver.get(link)
self.__rip_set()
self.girls_completed += 1
def __rip_set(self):
girl_xpath = "//h1/a"
title_xpath = ... | time.sleep(2)
lmb = SuicideGirls.driver.find_elements_by_xpath(load_more_xpath) | random_line_split |
app.go | package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"io/ioutil"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
redis "gopkg.in/redis.v3"
)
type Ad struct {
Slot string `... |
return
}
err = os.Remove(path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
return
}
// curl -XDELETE -v http://127.0.0.1:8080/fs/foo
func routeGetFs(rdr render.Render, w http.ResponseWriter, r *http.Request, params martini.Params) {
path := FSR... | {
http.Error(w, err.Error(), http.StatusInternalServerError)
} | conditional_block |
app.go | package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"io/ioutil"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
redis "gopkg.in/redis.v3"
)
type Ad struct {
Slot string `... |
func main() {
m := martini.Classic()
m.Use(martini.Static("../public"))
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Group("/slots/:slot", func(r martini.Router) {
m.Post("/ads", routePostAd)
m.Get("/ad", routeGetAd)
m.Get("/ads/:id", routeGetAdWithId)
m.Get("/ads/:id/asset", routeGe... | {
path := FSRoot + strings.TrimPrefix(r.URL.Path, FSPathPrefix)
http.ServeFile(w, r, path)
return
} | identifier_body |
app.go | package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"io/ioutil"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
redis "gopkg.in/redis.v3"
)
type Ad struct {
Slot string `... |
// curl -XPOST --data-binary "hoge" -v http://127.0.0.1:8080/fs/foo
func routePostFs(rdr render.Render, w http.ResponseWriter, r *http.Request, params martini.Params) {
path := FSRoot + strings.TrimPrefix(r.URL.Path, FSPathPrefix)
dir := filepath.Dir(path)
log.Println(dir)
err := os.MkdirAll(dir, FSDirPermission)... |
var FSPathPrefix = "/fs"
var FSRoot = "/"
var FSDirPermission os.FileMode = 0777 | random_line_split |
app.go | package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"io/ioutil"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
redis "gopkg.in/redis.v3"
)
type Ad struct {
Slot string `... | (path string, id string) string {
i, _ := strconv.Atoi(id)
host := internalIP[i%3]
if host != "" {
return "http://" + host + path
} else {
return path
}
}
func fetch(hash map[string]string, key string, defaultValue string) string {
if hash[key] == "" {
return defaultValue
} else {
return hash[key]
}
}
... | urlFor2 | identifier_name |
tk.py | #!/usr/bin/env python3
import time
from tkinter import *
from PIL import ImageTk, Image
import csv
from subprocess import Popen
import RPi.GPIO as GPIO
from subprocess import call
from datetime import datetime
from crontab import CronTab
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO... | (self):
# Setup number pad screen
self.number_pad = Toplevel(root)
self.keypad_entery = Entry(self.number_pad,width=5,font=("Helvetica", 55))
self.keypad_entery.grid(row=0, column=0, columnspan=3, ipady=5)
self.number_pad.attributes('-fullscreen',True)
# Variables of keys to loop though
self.keys... | __init__ | identifier_name |
tk.py | #!/usr/bin/env python3
import time
from tkinter import *
from PIL import ImageTk, Image
import csv
from subprocess import Popen
import RPi.GPIO as GPIO
from subprocess import call
from datetime import datetime
from crontab import CronTab
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO... |
if days > 1:
total_seconds = (days - 1) * 86400
countdown = total_seconds - int(round(seconds_since_last_run))
m, s = divmod(countdown, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
times = (
"There is {} day(s) {} hour(s) {} minute(s) and {} seconds remaining on the time... | total_seconds = (days - 1) * 86400
countdown = total_seconds - int(round(seconds_since_last_run))
if countdown <= 1:
total_seconds = days * 86400
countdown = total_seconds - int(round(seconds_since_last_run)) | conditional_block |
tk.py | #!/usr/bin/env python3
import time
from tkinter import *
from PIL import ImageTk, Image
import csv
from subprocess import Popen
import RPi.GPIO as GPIO
from subprocess import call
from datetime import datetime
from crontab import CronTab
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO... |
self.timer_set_page.attributes('-fullscreen', True)
# Strings for all recurrence rate
self.recurrence = ["1 Day", "2 Day", "3 Day", "4 Day", "5 Day", "6 Day","7 Day"]
self.timer_reoc_text = Label(
self.timer_set_page, text="Please choose how often you would like to run the timer.",
font=('Helve... | self.b = Button(self.timer_set_page, text=self.key, command=lambda val=self.z:self.__timer_return(val))
self.b.grid(row=self.y + 1, column=self.x, ipadx=20, ipady=10)
| random_line_split |
tk.py | #!/usr/bin/env python3
import time
from tkinter import *
from PIL import ImageTk, Image
import csv
from subprocess import Popen
import RPi.GPIO as GPIO
from subprocess import call
from datetime import datetime
from crontab import CronTab
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO... |
def timer(): # Simple timer class,
try: # If any errors usually due to no input pass
run_time = timer_input_value.get()
root_status_string.set(str("Pump Running"))
timer_input_value.set("")
if GPIO.input(23) == 1:
GPIO.output(24, 1)
for i in range(1, run_time + 1, +1):
m, s = d... | def __init__(self):
global timer_set_run_text
global daily_timer_input_value
global timer_status
global timer_error_string
global keyboard_img
self.timer_set_page = Toplevel(root)
# Setup the window for the timer selections
# Strings for all of the buttons
self.timer_run_text = Label(... | identifier_body |
graphql-client.js | 'use strict'
import utils from '../../utils/utils'
const gql = require('graphql-tag')
var deepEqual = require('deep-equal')
const tradle = require('@tradle/engine')
const tradleUtils = tradle.utils
const { ApolloClient, createNetworkInterface } = require('apollo-client')
var constants = require('@tradle/constants');... | )
}
let m = utils.getModel(ref).value
if (m.subClassOf === ENUM) {
if (m.enum)
return (
`${p} {
id
title
}`
)
else
return p
}
if (m.id === PHOTO) {
let mprops = m.properties
return (
`${p} {${th... | id
title
}` | random_line_split |
graphql-client.js | 'use strict'
import utils from '../../utils/utils'
const gql = require('graphql-tag')
var deepEqual = require('deep-equal')
const tradle = require('@tradle/engine')
const tradleUtils = tradle.utils
const { ApolloClient, createNetworkInterface } = require('apollo-client')
var constants = require('@tradle/constants');... | (params) {
let { author, recipient, client, context } = params
let table = `rl_${MESSAGE.replace(/\./g, '_')}`
let inbound = true
let query =
`query {
rl_tradle_Message(
first:20,
filter:{
EQ: {
_inbound: true
cont... | getChat | identifier_name |
graphql-client.js | 'use strict'
import utils from '../../utils/utils'
const gql = require('graphql-tag')
var deepEqual = require('deep-equal')
const tradle = require('@tradle/engine')
const tradleUtils = tradle.utils
const { ApolloClient, createNetworkInterface } = require('apollo-client')
var constants = require('@tradle/constants');... | ,
getAllPropertiesForServerSearch(model, inlined) {
let props = model.properties
let arr
if (model.inlined)
arr = []
else {
arr = ['_permalink', '_link', '_time', '_author', '_authorTitle', '_virtual', 'time']
if (model.id !== PUB_KEY && !inlined) {
let newarr = arr.concat(... | {
let { author, recipient, client, context } = params
let table = `rl_${MESSAGE.replace(/\./g, '_')}`
let inbound = true
let query =
`query {
rl_tradle_Message(
first:20,
filter:{
EQ: {
_inbound: true
context: "${c... | identifier_body |
greader.go | package api
import (
"encoding/json"
"fmt"
log "github.com/golang/glog"
"github.com/jrupac/goliath/models"
"github.com/jrupac/goliath/storage"
"github.com/jrupac/goliath/utils"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/bcrypt"
"net/http"
"net/http/httputil"
"strconv"
"strings"
... | Alternate: []greaderCanonical{
{Href: article.Link},
},
Summary: greaderContent{
Content: article.GetContents(*serveParsedArticles),
},
Origin: greaderOrigin{
StreamId: greaderFeedId(article.FeedID),
},
})
}
a.returnSuccess(w, streamItemContents)
}
func (a GReader) handleEditTag(w ht... | Published: article.Date.Unix(),
Canonical: []greaderCanonical{
{Href: article.Link},
}, | random_line_split |
greader.go | package api
import (
"encoding/json"
"fmt"
log "github.com/golang/glog"
"github.com/jrupac/goliath/models"
"github.com/jrupac/goliath/storage"
"github.com/jrupac/goliath/utils"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/bcrypt"
"net/http"
"net/http/httputil"
"strconv"
"strings"
... |
subList := greaderSubscriptionList{}
for _, feed := range feeds {
subList.Subscriptions = append(subList.Subscriptions, greaderSubscription{
Title: feed.Title,
// No client seems to use this field, so let it as zero
FirstItemMsec: "0",
HtmlUrl: feed.Link,
IconUrl: fmt.Sprintf("data:%s"... | {
folderMap[folder.ID] = folder.Name
} | conditional_block |
greader.go | package api
import (
"encoding/json"
"fmt"
log "github.com/golang/glog"
"github.com/jrupac/goliath/models"
"github.com/jrupac/goliath/storage"
"github.com/jrupac/goliath/utils"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/bcrypt"
"net/http"
"net/http/httputil"
"strconv"
"strings"
... |
func (a GReader) route(w http.ResponseWriter, r *http.Request) {
// Record the total server latency of each call.
defer a.recordLatency(time.Now(), "server")
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/greader/accounts/ClientLogin":
a.handleLogin(w, r)
case "/greader/reader... | {
utils.Elapsed(t, func(d time.Duration) {
// Record latency measurements in microseconds.
greaderLatencyMetric.WithLabelValues(label).Observe(float64(d) / float64(time.Microsecond))
})
} | identifier_body |
greader.go | package api
import (
"encoding/json"
"fmt"
log "github.com/golang/glog"
"github.com/jrupac/goliath/models"
"github.com/jrupac/goliath/storage"
"github.com/jrupac/goliath/utils"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/bcrypt"
"net/http"
"net/http/httputil"
"strconv"
"strings"
... | (feedId int64) string {
return fmt.Sprintf("feed/%d", feedId)
}
func greaderFolderId(folderId int64) string {
return fmt.Sprintf("user/-/label/%d", folderId)
}
func (a GReader) returnError(w http.ResponseWriter, status int) {
w.WriteHeader(status)
}
func (a GReader) returnSuccess(w http.ResponseWriter, resp any) ... | greaderFeedId | identifier_name |
locale.js | var dictBG = {
"PORTFOLIO": "Портфолио",
"RANGE":"Обхват",
"AUDIENCE":"Аудитория",
"BRAND": "Бранд",
"CONTACT":"Контакт",
"LEADING MEDIA COMPANY":"Xenium е водеща медийна компания в България",
"MEDIA KIT":"МЕДИА КИТ",
"AUDIENCE REACH":"Медиен обхват на аудиторията",
"AUDIENCE PROFILE... | "BIG CITIES AND REGIONAL CAPITALS":"big cities and regional capitals",
"AGED":"aged",
"THE MOST COMPEHENCIVE":"the most comprehencive social medium for news and entertainment.",
"OVER 4000 PUBLICATIONS DAILY":"Over <strong>4000 publications daily </strong>are added by the users.",
"OVER 2M PUBLICATI... | random_line_split | |
__init__.py | import inspect
import json
import socket
import sys
import execnet
import logging
from remoto.process import check
class BaseConnection(object):
"""
Base class for Connection objects. Provides a generic interface to execnet
for setting up the connection
"""
executable = ''
remote_import_system... |
return 'popen//python=%s' % interpreter
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.group.terminate(timeout=1.0)
return False
def cmd(self, cmd):
"""
In the base connection class, this method just returns the ``cmd`... | if self.ssh_options:
return 'ssh=%s %s//python=%s' % (
self.ssh_options, hostname, interpreter
)
else:
return 'ssh=%s//python=%s' % (hostname, interpreter) | conditional_block |
__init__.py | import inspect
import json
import socket
import sys
import execnet
import logging
from remoto.process import check
class BaseConnection(object):
"""
Base class for Connection objects. Provides a generic interface to execnet
for setting up the connection
"""
executable = ''
remote_import_system... | self.hostname = hostname
self.ssh_options = ssh_options
self.logger = logger or basic_remote_logger()
self.remote_module = None
self.channel = None
self.use_ssh = use_ssh
self.global_timeout = None # wait for ever
self.interpreter = interpreter or 'pytho... |
def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=True,
detect_sudo=False, use_ssh=False, interpreter=None, ssh_options=None):
self.sudo = sudo | random_line_split |
__init__.py | import inspect
import json
import socket
import sys
import execnet
import logging
from remoto.process import check
class BaseConnection(object):
"""
Base class for Connection objects. Provides a generic interface to execnet
for setting up the connection
"""
executable = ''
remote_import_system... | """
Try to determine the remote Python version so that it can be used
when executing. Avoids the problem of different Python versions, or distros
that do not use ``python`` but do ``python3``
"""
# executables in order of preference:
executables = ['python3', 'python', 'python2.7']
for execu... | identifier_body | |
__init__.py | import inspect
import json
import socket
import sys
import execnet
import logging
from remoto.process import check
class BaseConnection(object):
"""
Base class for Connection objects. Provides a generic interface to execnet
for setting up the connection
"""
executable = ''
remote_import_system... | ():
logging.basicConfig()
logger = logging.getLogger(socket.gethostname())
logger.setLevel(logging.DEBUG)
return logger
def needs_ssh(hostname, _socket=None):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
if hostname.lower() in ['localhost'... | basic_remote_logger | identifier_name |
user_controller.py |
from flask import render_template, flash, redirect, session, url_for, request, g, json, jsonify
from flask.ext.login import login_user, logout_user, current_user, login_required
from lumberjack import app, login_manager, db
from lumberjack.models import *
from lumberjack.models.user import User
from lumberjack.m... |
@app.route("/user_feeds/")
@app.route('/user_feeds/<int:page>', methods = ['GET'])
def user_feeds(page=1):
user = g.user
if user.is_anonymous():
return jsonify(result="")
posts = g.user.followed_posts().paginate(request.args.get('page', '', type=int), 10, False)
if not p... | user = g.user
posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False)
return render_template("users/followers.html",user = user) | identifier_body |
user_controller.py |
from flask import render_template, flash, redirect, session, url_for, request, g, json, jsonify
from flask.ext.login import login_user, logout_user, current_user, login_required
from lumberjack import app, login_manager, db
from lumberjack.models import *
from lumberjack.models.user import User
from lumberjack.m... |
@login_manager.user_loader
@app.route("/user/find/", methods=['GET'])
def load_user(id):
return User.find_by_id(int(id))
@app.route("/user/<username>")
@app.route('/user/<username>/<int:page>', methods = ['GET'])
def display_user_profile(username, page=1):
user = User.find_by_username(username)
... | if form.validate():
user = User(form.username.data,
form.password.data)
User.save_to_db(user)
user = user.follow(user)
User.add_newsfeed(user,"Has joined Lumberjack.")
flash("Registration Successful!")
if request.head... | conditional_block |
user_controller.py |
from flask import render_template, flash, redirect, session, url_for, request, g, json, jsonify
from flask.ext.login import login_user, logout_user, current_user, login_required
from lumberjack import app, login_manager, db
from lumberjack.models import *
from lumberjack.models.user import User
from lumberjack.m... | ():
query = request.args.get('key', '')
if query.startswith('#'):
return redirect(url_for('display_user_profile', username=query[1:]))
user_search_result = (User.query.filter(or_((User.first_last_name.like("%" + query + "%")), (User.last_first_name.like("%" + query + "%"))))).all()
workout_... | search_for_key | identifier_name |
user_controller.py | from flask import render_template, flash, redirect, session, url_for, request, g, json, jsonify
from flask.ext.login import login_user, logout_user, current_user, login_required
from lumberjack import app, login_manager, db
from lumberjack.models import *
from lumberjack.models.user import User
from lumberjack.mod... | """
result = []
userids = []
usernames = []
if 'username' in request.form:
usernames = User.find_all_by_username(request.form['username'])
if usernames is not None:
for username in usernames:
result.append(username.to_hash())
elif 'email... | random_line_split | |
block.rs | use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use ansi_colours::ansi256_from_rgb;
use image::{DynamicImage, GenericImageView, Rgba};
use std::io::Write;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crossterm::cursor::{MoveRight, MoveT... |
}
// enum used to keep track where the current line of pixels processed should be displayed - as
// background or foreground color
#[derive(PartialEq)]
enum Mode {
Top,
Bottom,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_block_printer_small() {
let img = DynamicImage::ImageR... | {
Color::Ansi256(ansi256_from_rgb(rgb))
} | conditional_block |
block.rs | use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use ansi_colours::ansi256_from_rgb;
use image::{DynamicImage, GenericImageView, Rgba};
use std::io::Write;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crossterm::cursor::{MoveRight, MoveT... | if let Some(bg) = c.bg() {
new_color.set_fg(Some(*bg));
out_char = UPPER_HALF_BLOCK;
} else {
execute!(out_buffer, MoveRight(1))?;
continue;
}
out_color = &new_color;
} else {
match (c.fg(... | new_color = ColorSpec::new(); | random_line_split |
block.rs | use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use ansi_colours::ansi256_from_rgb;
use image::{DynamicImage, GenericImageView, Rgba};
use std::io::Write;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crossterm::cursor::{MoveRight, MoveT... | () {
let img = DynamicImage::ImageRgba8(image::RgbaImage::new(2000, 1000));
let config = Config {
width: Some(160),
height: None,
absolute_offset: false,
transparent: true,
..Default::default()
};
let (w, h) = BlockPrinter {}.p... | test_block_printer_large | identifier_name |
immutable.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | <U: ArrowNativeType, T: AsRef<[U]>>(items: &T) -> Self {
let slice = items.as_ref();
let capacity = slice.len() * std::mem::size_of::<U>();
let mut buffer = MutableBuffer::with_capacity(capacity);
buffer.extend_from_slice(slice);
buffer.into()
}
/// Creates a buffer from... | from_slice_ref | identifier_name |
immutable.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Returns a slice of this buffer starting at a certain bit offset.
/// If the offset is byte-aligned the returned buffer is a shallow clone,
/// otherwise a new buffer is allocated and filled with a copy of the bits in the range.
pub fn bit_slice(&self, offset: usize, len: usize) -> Self {
i... | {
// JUSTIFICATION
// Benefit
// Many of the buffers represent specific types, and consumers of `Buffer` often need to re-interpret them.
// Soundness
// * The pointer is non-null by construction
// * alignment asserted below.
let (prefix, offsets... | identifier_body |
immutable.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | macro_rules! check_as_typed_data {
($input: expr, $native_t: ty) => {{
let buffer = Buffer::from_slice_ref($input);
let slice: &[$native_t] = unsafe { buffer.typed_data::<$native_t>() };
assert_eq!($input, slice);
}};
}
#[test]
#[allow(clippy::float_c... | assert_eq!(buffer2, buffer_copy.ok().unwrap());
}
| random_line_split |
ZH.js | export default {
one_way: '单程',
round_trip: '往返',
flight_search_btn: '搜索',
Economy: '经济舱',
Business: '商务舱',
PremiumEconomy: '高端经济舱',
First: '头等舱',
BusinessAndFirst: '商务/头等舱',
departure: '去程',
departure_alias: '去程',
departure_title: '去程:',
return: '返程',
return_title: '返程:',
duration: '总时长',
... | summary_footer_tip: '飞呀辅助订购为你提供快捷预订通道,无需跳转到第三方平台。但出票和退改签服务仍由第三方机票服务平台提供。',
summary_no_result: '暂无平台报价',
summary_research: '重新搜索',
summary_timeout_tips1: '航班价格可能发生变化,将为你刷新',
summary_timeout_tips2: '以获取最新价格',
summary_quick_login: '动态码登录',
summary_quick_login_tip: '下单前先花10秒登录账号哦',
summary_other_login: '其他登... | summary_price: '各大平台实时价格', | random_line_split |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | (&self,
native_context: &NativeCompositingGraphicsContext,
texture: &Texture,
size: Size2D<isize>) {
// Create the GLX pixmap.
//
// FIXME(pcwalton): RAII for exception safety?
unsafe {
let pixma... | bind_to_texture | identifier_name |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | /// Creates graphics metadata from a metadata descriptor.
pub fn from_descriptor(descriptor: &NativeGraphicsMetadataDescriptor)
-> NativeGraphicsMetadata {
// WARNING: We currently rely on the X display connection being the
// same in both the Painting and Compositing ... | unsafe impl Send for NativeGraphicsMetadata {}
impl NativeGraphicsMetadata { | random_line_split |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
pub fn mark_wont_leak(&mut self) {
self.will_leak = false;
}
}
| {
self.will_leak = true;
} | identifier_body |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
}
}
impl PixmapNativeSurface {
fn from_pixmap(pixmap: Pixmap) -> PixmapNativeSurface {
PixmapNativeSurface {
pixmap: pixmap,
will_leak: true,
}
}
pub fn from_skia_shared_gl_context(context: SkiaSkNativeSharedGLContextRef)
... | {
panic!("You should have disposed of the pixmap properly with destroy()! This pixmap \
will leak!");
} | conditional_block |
mountfs.go | // Package fs provides mountpath and FQN abstractions and methods to resolve/map stored content
/*
* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*/
package fs
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/NVIDIA/aistore/3rdparty/ato... |
// DisableFsIDCheck disables fsid checking when adding new mountpath
func (mfs *MountedFS) DisableFsIDCheck() { mfs.checkFsID = false }
func (mfs *MountedFS) CreateBuckets(op string, bcks ...cmn.Bck) (errs []error) {
var (
availablePaths, _ = mfs.Get()
totalDirs = len(availablePaths) * len(bcks) * len(C... | {
var (
availablePaths = (*MPI)(mfs.available.Load())
disabledPaths = (*MPI)(mfs.disabled.Load())
)
if availablePaths == nil {
tmp := make(MPI, 10)
availablePaths = &tmp
}
if disabledPaths == nil {
tmp := make(MPI, 10)
disabledPaths = &tmp
}
return *availablePaths, *disabledPaths
} | identifier_body |
mountfs.go | // Package fs provides mountpath and FQN abstractions and methods to resolve/map stored content
/*
* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*/
package fs
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/NVIDIA/aistore/3rdparty/ato... | // the counter will catch up with counter of the previous mountpath.
// If the directories from the previous mountpath were not yet removed
// (slow disk or filesystem) we can end up with the same name.
// For now we try to fight this with randomizing the initial counter.
// In backgroun... | // There are at least two cases when this might not be true:
// 1. `nonExistingDir` is leftover after target crash.
// 2. Mountpath was removed and then added again. The counter
// will be reset and if we will be removing dirs quickly enough | random_line_split |
mountfs.go | // Package fs provides mountpath and FQN abstractions and methods to resolve/map stored content
/*
* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*/
package fs
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/NVIDIA/aistore/3rdparty/ato... |
return nil
}
// Add adds new mountpath to the target's mountpaths.
// FIXME: unify error messages for original and clean mountpath
func (mfs *MountedFS) Add(mpath string) error {
cleanMpath, err := cmn.ValidateMpath(mpath)
if err != nil {
return err
}
if err := Access(cleanMpath); err != nil {
return fmt.Er... | {
if err := mfs.Add(path); err != nil {
return err
}
} | conditional_block |
mountfs.go | // Package fs provides mountpath and FQN abstractions and methods to resolve/map stored content
/*
* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*/
package fs
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/NVIDIA/aistore/3rdparty/ato... | (mpath string) error {
var (
mp *MountpathInfo
exists bool
)
mfs.mu.Lock()
defer mfs.mu.Unlock()
cleanMpath, err := cmn.ValidateMpath(mpath)
if err != nil {
return err
}
availablePaths, disabledPaths := mfs.mountpathsCopy()
if mp, exists = availablePaths[cleanMpath]; !exists {
if mp, exists = di... | Remove | identifier_name |
webmux.py | #!/usr/bin/env python
from __future__ import print_function, absolute_import
import logging
import os, os.path, socket
import sys, subprocess, threading, time
import requests, re
import tornado.web
from tornado.netutil import bind_unix_socket
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
... |
return ssh_procs
class WebmuxTermManager(terminado.NamedTermManager):
"""Share terminals between websockets connected to the same endpoint.
"""
def __init__(self, max_terminals=None, **kwargs):
super(WebmuxTermManager, self).__init__(**kwargs)
def get_terminal(self, port_number):
... | subprocess.call(["kill", p]) | conditional_block |
webmux.py | #!/usr/bin/env python
from __future__ import print_function, absolute_import
import logging
import os, os.path, socket
import sys, subprocess, threading, time
import requests, re
import tornado.web
from tornado.netutil import bind_unix_socket
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
... | # Log out a little bit
logging.info("Registered %s at %s:%d on webmux port %d"%(data['hostname'], data['global_ip'], data['host_port'], data['webmux_port']))
self.write(str(data['webmux_port']))
class ResetPageHandler(tornado.web.RequestHandler):
"""Reset all SSH connections forwarding port... | server_list[data['hostname']].update(data)
data = server_list[data['hostname']]
| random_line_split |
webmux.py | #!/usr/bin/env python
from __future__ import print_function, absolute_import
import logging
import os, os.path, socket
import sys, subprocess, threading, time
import requests, re
import tornado.web
from tornado.netutil import bind_unix_socket
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
... | ():
global server_list
while server_list['ivolethe']['global_ip'] == 'webmux.cflo.at':
try:
findTags = re.compile(r'<.*?>')
findIP = re.compile(r'\d+\.\d+\.\d+\.\d+')
html = requests.get('http://checkip.dyndns.org' ).text()
ipaddress = findIP.search(findT... | get_global_ip | identifier_name |
webmux.py | #!/usr/bin/env python
from __future__ import print_function, absolute_import
import logging
import os, os.path, socket
import sys, subprocess, threading, time
import requests, re
import tornado.web
from tornado.netutil import bind_unix_socket
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
... |
class IndexPageHandler(tornado.web.RequestHandler):
"""Render the index page"""
def get(self):
logging.info("Hit the index page")
return self.render("index.html", static=self.static_url, server_list=server_list)
class RegistrationPageHandler(tornado.web.RequestHandler):
"""Return a port n... | """Share terminals between websockets connected to the same endpoint.
"""
def __init__(self, max_terminals=None, **kwargs):
super(WebmuxTermManager, self).__init__(**kwargs)
def get_terminal(self, port_number):
from terminado.management import MaxTerminalsReached
# This is importan... | identifier_body |
server.py | #######################################################
# Copyright (C) 2020 Sam Pickell and Aishwarya Vissom
# Last Updated: Apr. 20, 2020
# UML COMP 5610 Computer Network and Security
#
# This is a working implementation of an
# encrypted messaging client/server program
# using DES, RSA, and PKC. This is our fina... |
# Apply the IP Key encryption algorithm
final_list = []
next_index = 56
for i in range(28):
final_list.append(smaller_key[next_index])
next_index = ((next_index - 8) % 65)
next_index = 62
for i in range(28, 52):
final_list.append(smaller_key[next_index])
nex... | smaller_key.append(my_key_list[i])
counter += 1 | conditional_block |
server.py | #######################################################
# Copyright (C) 2020 Sam Pickell and Aishwarya Vissom
# Last Updated: Apr. 20, 2020
# UML COMP 5610 Computer Network and Security
#
# This is a working implementation of an
# encrypted messaging client/server program
# using DES, RSA, and PKC. This is our fina... | (K_List):
new_list = []
# Convert to bits
for i in range(len(K_List)):
new_list.append(format(ord(K_List[i]), '07b'))
if K_List[i].count("1") % 2 == 0:
new_list.append("0")
else:
new_list.append("1")
return "".join(new_list)
def apply_IP(M):
rev_M... | convert_K | identifier_name |
server.py | #######################################################
# Copyright (C) 2020 Sam Pickell and Aishwarya Vissom
# Last Updated: Apr. 20, 2020
# UML COMP 5610 Computer Network and Security
#
# This is a working implementation of an
# encrypted messaging client/server program
# using DES, RSA, and PKC. This is our fina... |
def apply_IPKey(my_key):
my_key_list = list(my_key)
smaller_key = []
counter = 1
# Convert every 8th bit from the key to an "8", to be removed later
for i in range(len(my_key_list)):
if counter % 8 == 0:
smaller_key.append("8")
counter = 1
else:
... | final_list = [C[39], C[7], C[47], C[15], C[55], C[23], C[63], C[31], C[38], C[6], C[46], C[14], C[54], C[22], C[62],
C[30],
C[37], C[5], C[45], C[13], C[53], C[21], C[61], C[29], C[36], C[4], C[44], C[12], C[52], C[20], C[60],
C[28],
C[35], C[3], C... | identifier_body |
server.py | #######################################################
# Copyright (C) 2020 Sam Pickell and Aishwarya Vissom
# Last Updated: Apr. 20, 2020
# UML COMP 5610 Computer Network and Security
#
# This is a working implementation of an
# encrypted messaging client/server program
# using DES, RSA, and PKC. This is our fina... | return "".join(new_list)
def apply_IP(M):
rev_M = list(M[len(M)::-1])
my_mat = [["0", "0", "0", "0", "0", "0", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0", "0", "0"], ["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0",... | new_list.append("1")
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.