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 |
|---|---|---|---|---|
code.go | /*
Copyright 2022 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... | () string {
return o.Err.Error()
}
func (o *VitessError) Cause() error {
return o.Err
}
var _ error = (*VitessError)(nil)
func errorWithoutState(id string, code vtrpcpb.Code, short, long string) func(args ...any) *VitessError {
return func(args ...any) *VitessError {
s := short
if len(args) != 0 {
s = fmt.... | Error | identifier_name |
run_utils.py | #!/usr/bin/env python3
import os
from enum import Enum
import numpy as np
import scipy.sparse as sps
from sklearn.preprocessing import LabelEncoder
from tqdm import tqdm, trange
from cython_modules.leave_one_out import train_test_loo_split as __train_test_loo_split_cython
from csv_utils import load_csv, export_csv
fro... | (n_items):
price_icm_items, _, price_icm_values = __load_icm_csv(DataFiles.ICM_PRICE, third_type=float)
price_icm_values = __encode_values(price_icm_values)
n_features = max(price_icm_values) + 1
shape = (n_items, n_features)
ones = np.ones(len(price_icm_values))
price_icm = sps.csr_matrix((ones... | build_price_icm | identifier_name |
run_utils.py | #!/usr/bin/env python3
import os
from enum import Enum
import numpy as np
import scipy.sparse as sps
from sklearn.preprocessing import LabelEncoder
from tqdm import tqdm, trange
from cython_modules.leave_one_out import train_test_loo_split as __train_test_loo_split_cython
from csv_utils import load_csv, export_csv
fro... |
group_struct = namedtuple('group_struct', ['in_group', 'not_in_group'])
def user_segmenter(urm_train, n_groups=10):
groups = dict()
users = dict()
profile_length = np.ediff1d(urm_train.indptr)
group_size = int(profile_length.size/n_groups)
sorted_users = np.argsort(profile_length)
for group... | le = LabelEncoder()
le.fit(values)
return le.transform(values) | identifier_body |
run_utils.py | #!/usr/bin/env python3
import os
from enum import Enum
import numpy as np
import scipy.sparse as sps
from sklearn.preprocessing import LabelEncoder
from tqdm import tqdm, trange
from cython_modules.leave_one_out import train_test_loo_split as __train_test_loo_split_cython
from csv_utils import load_csv, export_csv
fro... |
else:
return evaluate_algorithm(recommender, urm_test, excluded_users=excluded_users, verbose=verbose)
def evaluate_mp(recommender, urm_tests, excluded_users=[], cython=False, verbose=True, n_processes=0):
assert type(urm_tests) == list
assert len(urm_tests) >= 1
assert type(n_processes) == i... | if verbose:
print('Ignoring argument excluded_users')
from cython_modules.evaluation import evaluate_cython
if verbose:
print('Using Cython evaluation')
return evaluate_cython(recommender, urm_test, verbose=verbose) | conditional_block |
run_utils.py | #!/usr/bin/env python3
import os
from enum import Enum
import numpy as np
import scipy.sparse as sps
from sklearn.preprocessing import LabelEncoder
from tqdm import tqdm, trange
from cython_modules.leave_one_out import train_test_loo_split as __train_test_loo_split_cython
from csv_utils import load_csv, export_csv
fro... | age_ucm = sps.csr_matrix((age_ucm_values, (age_ucm_users, age_ucm_features)), shape=shape, dtype=int)
return age_ucm
def build_region_ucm(n_users):
region_ucm_users, region_ucm_features, region_ucm_values = __load_icm_csv(DataFiles.UCM_REGION, third_type=float)
n_features = max(region_ucm_features) + ... | age_ucm_users, age_ucm_features, age_ucm_values = __load_icm_csv(DataFiles.UCM_AGE, third_type=float)
n_features = max(age_ucm_features) + 1
shape = (n_users, n_features) | random_line_split |
Home.js | import React, { useEffect, useState } from 'react';
import firebaseInstance from "../FirebaseInstance"
import
DevSettings,
{
ActivityIndicator,
StyleSheet,
Modal,
View,
ScrollView
} from 'react-native';
import {Button, Text, Header, Image} from "react-native-elements"
import Icon from "react-nat... | readCollection("dinners")
}, [])
//set filteredData to "database"
useEffect(() => {
setFilteredData([...database])
}, [database]);
//Apply filter when a filter is added/removed
useEffect(() => {
applyFilter();
}, [isChecked]);
//Organize courses in weekday,friday and sunday-lists
... | try{
const collection = await firebaseInstance.firestore().collection(text)
const readCollection = await collection.get()
let returnArray = [];
readCollection.forEach(item => {
const itemData = item.data() || {};
returnArray.push({
id: item... | identifier_body |
Home.js | import React, { useEffect, useState } from 'react';
import firebaseInstance from "../FirebaseInstance"
import
DevSettings,
{
ActivityIndicator,
StyleSheet,
Modal,
View,
ScrollView
} from 'react-native';
import {Button, Text, Header, Image} from "react-native-elements"
import Icon from "react-nat... | }
})
if (fishArr.length > 0 || vegArr.length > 0 || meatArr.length > 0) {
tempArr = [...fishArr, ...vegArr, ...meatArr];
}
//filters glutenFree and lactoseFree - based on the tempArr that's already filtered by meat, fish and vegetarian courses
isChecked.filters.forEach(param => {
... | let veg = item => item.type === "veg";
vegArr = filter(veg, tempArr);
}
| conditional_block |
Home.js | import React, { useEffect, useState } from 'react';
import firebaseInstance from "../FirebaseInstance"
import
DevSettings,
{
ActivityIndicator,
StyleSheet,
Modal,
View,
ScrollView
} from 'react-native';
import {Button, Text, Header, Image} from "react-native-elements"
import Icon from "react-nat... | () {
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [weekday, setWeekday] = useState([]);
const [friday, setFriday] = useState([]);
const [sunday, setSunday] = useState([]);
const [fastFood, setFastFood] = useState([]);
const [dinnerList, setDinnerList]... | Home | identifier_name |
Home.js | import React, { useEffect, useState } from 'react';
import firebaseInstance from "../FirebaseInstance"
import
DevSettings,
{
ActivityIndicator,
StyleSheet,
Modal,
View,
ScrollView
} from 'react-native';
import {Button, Text, Header, Image} from "react-native-elements"
import Icon from "react-nat... | {type: "fri", checked: false, text: "Fredag", index: 4},
{type: "sat", checked: false, text: "Lørdag", index: 5},
{type: "sun", checked: false, text: "Søndag", index:6},
]}
);
const storage = useStorageContext();
//----------------------------------------------------------------useEffect... | random_line_split | |
proxy.rs | // #![deny(warnings)]
extern crate clap;
extern crate futures;
extern crate hyper;
extern crate mproxy;
extern crate openssl;
extern crate pretty_env_logger;
extern crate rmp;
extern crate rmp_serde;
extern crate tokio_io;
extern crate tokio_openssl;
extern crate tokio_tcp;
extern crate tokio_tls;
extern crate uuid;
u... |
}
pub enum Trace {
TraceId(String),
TraceSecurity(String, openssl::x509::X509),
TraceRequest(String, Request<Body>),
TraceResponse(String, Request<Body>),
}
fn make_absolute(req: &mut Request<Body>) {
/* RFC 7312 5.4
When a proxy receives a request with an absolute-form of
request-ta... | {
Ok(Identity::Anonymous)
} | identifier_body |
proxy.rs | // #![deny(warnings)]
extern crate clap;
extern crate futures;
extern crate hyper;
extern crate mproxy;
extern crate openssl;
extern crate pretty_env_logger;
extern crate rmp;
extern crate rmp_serde;
extern crate tokio_io;
extern crate tokio_openssl;
extern crate tokio_tcp;
extern crate tokio_tls;
extern crate uuid;
u... | hyper::rt::run(done);
});
}
struct ProxyUserConfig {
key: String,
ca: String,
port: u16,
}
fn parse_options() -> Option<ProxyUserConfig> {
let matches = App::new("My Super Program")
.version("1.0")
.author("Matt Woodyard <matt@mattwoodyard.com>")
.about("Be a proxy"... | }
println!("Trace recv");
Ok(())
}); | random_line_split |
proxy.rs | // #![deny(warnings)]
extern crate clap;
extern crate futures;
extern crate hyper;
extern crate mproxy;
extern crate openssl;
extern crate pretty_env_logger;
extern crate rmp;
extern crate rmp_serde;
extern crate tokio_io;
extern crate tokio_openssl;
extern crate tokio_tcp;
extern crate tokio_tls;
extern crate uuid;
u... | (&self) -> Proxy<U, S, A> {
Proxy {
tracer: self.tracer.iter().map(|t| t.clone()).next(),
ca: self.ca.clone(),
auth_config: self.auth_config.clone(),
upstream_ssl_pool: pool::Pool::empty(100),
}
}
fn handle<C: Connect + 'static>(
&self,
... | dup | identifier_name |
partdisk.go | package partdisk
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
//Max number of files for each size that can be created
const limitFiles uint64 = 25
//Length of random id string
const rstl int = 7
//Holds a representation of the file data
type FileCollection ... | for index, value := range fS.fileSizes {
semiTotal += value * fS.fileAmmount[index]
rst += fmt.Sprintf("Files of size: %d, count: %d, total size: %d\n", value, fS.fileAmmount[index], value*fS.fileAmmount[index])
}
rst += fmt.Sprintf("Total size reserved: %d bytes.\n", semiTotal)
return rst
}
//Generate a messa... | func GetDefFiles(fS *FileCollection) string {
var semiTotal uint64
var rst string | random_line_split |
partdisk.go | package partdisk
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
//Max number of files for each size that can be created
const limitFiles uint64 = 25
//Length of random id string
const rstl int = 7
//Holds a representation of the file data
type FileCollection ... | (fS *FileCollection, ts int64, filelock chan int64) {
var lt time.Time
var err error
select {
case <- time.After(5 * time.Second):
//If 5 seconds pass without getting the proper lock, abort
log.Printf("partdisk.CreateFiles(): timeout waiting for lock\n")
return
case chts := <- filelock:
if chts == ts { //... | CreateFiles | identifier_name |
partdisk.go | package partdisk
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
//Max number of files for each size that can be created
const limitFiles uint64 = 25
//Length of random id string
const rstl int = 7
//Holds a representation of the file data
type FileCollection ... |
//Add or remove files match the files definition in the FileCollection struct
func adrefiles(fS *FileCollection) error {
for index,value := range fS.fileSizes {
directory := fmt.Sprintf("%s/d-%d",fS.frandi,value)
//Create a list of files in directory
fileList,err := getFilesInDir(directory)
if err != nil {
... | {
var lt time.Time
var err error
select {
case <- time.After(5 * time.Second):
//If 5 seconds pass without getting the proper lock, abort
log.Printf("partdisk.CreateFiles(): timeout waiting for lock\n")
return
case chts := <- filelock:
if chts == ts { //Got the lock and it matches the timestamp received
... | identifier_body |
partdisk.go | package partdisk
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
//Max number of files for each size that can be created
const limitFiles uint64 = 25
//Length of random id string
const rstl int = 7
//Holds a representation of the file data
type FileCollection ... |
f,err := os.Create(filename)
defer f.Close()
if err != nil {
log.Printf("newFile(): Error creating file: %s",filename)
return err
}
burval = base[:]
for i:=uint64(0); i<size; i++ {
counter += i + uint64(base[i%uint64(blength)])
index = counter%uint64(len(base))
burval[i%uint64(len(base))]=base[index]
... | {
base[x]=byte(rand.Intn(95) + 32) //ASCII 32 to 126
} | conditional_block |
main.py | # import libraries
import cv2
import time
import numpy as np
import sqlite3
import matplotlib.pyplot as plt
con = sqlite3.connect("traffic.db")
c = con.cursor()
data = c.execute("""SELECT * FROM data""")
rows = c.fetchall()
df = []
df1 = []
df2 = []
df3 = []
for rows in rows:
df.append(rows[0])
... | ():
# get a random row and column index
current_row_index = np.random.randint(environment_rows)
current_column_index = np.random.randint(environment_columns)
# continue choosing random row and column indexes until a non-terminal state is identified
# (i.e., until the chosen state is a 'path whi... | get_starting_location | identifier_name |
main.py | # import libraries
import cv2
import time
import numpy as np
import sqlite3
import matplotlib.pyplot as plt
con = sqlite3.connect("traffic.db")
c = con.cursor()
data = c.execute("""SELECT * FROM data""")
rows = c.fetchall()
df = []
df1 = []
df2 = []
df3 = []
for rows in rows:
df.append(rows[0])
... | output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3)) # to get list of colors for each possible class
# Loading image
with open("{}.jpeg".format(counter), "wb") as f:
f.write(p)
frame = cv2.imread("{}.j... | net = cv2.dnn.readNet("yolo/yolov3.weights", "yolo/yolov3.cfg")
counter = 1
with open("yolo/coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
| random_line_split |
main.py | # import libraries
import cv2
import time
import numpy as np
import sqlite3
import matplotlib.pyplot as plt
con = sqlite3.connect("traffic.db")
c = con.cursor()
data = c.execute("""SELECT * FROM data""")
rows = c.fetchall()
df = []
df1 = []
df2 = []
df3 = []
for rows in rows:
df.append(rows[0])
... |
# Define a function that will get the shortest path between any location within the source that
# the car is allowed to travel and the goal.
def get_shortest_path(start_row_index, start_column_index):
# return immediately if this is an invalid starting location
if is_terminal_state(start_row_index, st... | new_row_index = current_row_index
new_column_index = current_column_index
if actions[action_index] == 'up' and current_row_index > 0:
new_row_index -= 1
elif actions[action_index] == 'right' and current_column_index < environment_columns - 1:
new_column_index += 1
elif actions[acti... | identifier_body |
main.py | # import libraries
import cv2
import time
import numpy as np
import sqlite3
import matplotlib.pyplot as plt
con = sqlite3.connect("traffic.db")
c = con.cursor()
data = c.execute("""SELECT * FROM data""")
rows = c.fetchall()
df = []
df1 = []
df2 = []
df3 = []
for rows in rows:
df.append(rows[0])
... |
print('Training complete!')
sourceone = -1
sourcetwo = -1
sourcelo = input("Enter the source from same list Location : ")
for i in range(len(df)):
if df3[i] == sourcelo:
sourceone = df1[i]-23
sourcetwo = df2[i]-23
if sourceone == -1 or sourcetwo == -1:
print("Location not found pl... | action_index = get_next_action(row_index, column_index, epsilon)
# perform the chosen action, and transition to the next state (i.e., move to the next location)
old_row_index, old_column_index = row_index, column_index # store the old row and column indexes
row_index, column_index = get_ne... | conditional_block |
smart_contract_service_impl.go | package service
import (
"errors"
"it-chain/domain"
"strings"
"os"
"time"
"io/ioutil"
"bytes"
"context"
"docker.io/go-docker"
"io"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/container"
"encoding/json"
"bufio"
"os/exec"
"it-chain/common"
"fmt"
"github.com/spf13/viper"
)
const (
T... | tar file!")
return err
}
/*** copy file to docker ***/
err = cli.CopyToContainer(ctx, resp.ID, "/go/src/", bytes.NewReader(file), types.CopyToContainerOptions{
AllowOverwriteDirWithFile: false,
})
if err != nil {
logger_s.Errorln("An error occured while copying the smartcontract to the container!")
return... | e(tarPath_config)
if err != nil {
logger_s.Errorln("An error occured while reading config | conditional_block |
smart_contract_service_impl.go | package service
import (
"errors"
"it-chain/domain"
"strings"
"os"
"time"
"io/ioutil"
"bytes"
"context"
"docker.io/go-docker"
"io"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/container"
"encoding/json"
"bufio"
"os/exec"
"it-chain/common"
"fmt"
"github.com/spf13/viper"
)
const (
T... | () {
}
func NewSmartContractService(githubID string,smartContractDirPath string) SmartContractService{
return &SmartContractServiceImpl{
GithubID:githubID,
SmartContractDirPath:smartContractDirPath,
SmartContractMap: make(map[string]SmartContract),
}
}
func (scs *SmartContractServiceImpl) PullAllSmartContrac... | Init | identifier_name |
smart_contract_service_impl.go | package service
import (
"errors"
"it-chain/domain"
"strings"
"os"
"time"
"io/ioutil"
"bytes"
"context"
"docker.io/go-docker"
"io"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/container"
"encoding/json"
"bufio"
"os/exec"
"it-chain/common"
"fmt"
"github.com/spf13/viper"
)
const (
T... | g) (key string, ok bool) {
contractName := strings.Replace(OriginReposPath, "/", "^", -1)
for k, v := range scs.SmartContractMap {
if contractName == v.OriginReposPath {
key = k
ok = true
return key, ok
}
}
return "", false
} | {
return errors.New("Tx Marshal Error")
}
sc, ok := scs.SmartContractMap[transaction.TxData.ContractID];
if !ok {
logger_s.Errorln("Not exist contract ID")
return errors.New("Not exist contract ID")
}
_, err = os.Stat(sc.SmartContractPath)
if os.IsNotExist(err) {
logger_s.Errorln("File or Directory Not... | identifier_body |
smart_contract_service_impl.go | package service
import (
"errors"
"it-chain/domain"
"strings"
"os"
"time"
"io/ioutil"
"bytes"
"context"
"docker.io/go-docker"
"io"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/container"
"encoding/json"
"bufio"
"os/exec"
"it-chain/common"
"fmt"
"github.com/spf13/viper"
)
const (
T... | }
_, err = file.WriteString("Deployed at " + now + "\n")
if err != nil {
return "", errors.New("An error occured while writing file!")
}
err = file.Close()
if err != nil {
return "", errors.New("An error occured while closing file!")
}
err = domain.CommitAndPush(scs.SmartContractDirPath + "/" + new_repos_... | return "", errors.New("An error occured while creating or opening file!") | random_line_split |
main.rs | use std::{collections::HashSet, fs::File, sync::Arc, time::Duration};
use anyhow::{Context as _, Result};
use serenity::{
async_trait,
client::bridge::gateway::GatewayIntents,
framework::standard::{
macros::{command, group},
Args, CommandResult, StandardFramework,
},
futures::Stream... | let committee_msg = committee_channel
.say(
ctx,
&MessageBuilder::new()
.push("Received request from ")
.mention(&msg.author)
.push(if is_external {
format!(
" to forward message to {}",
... |
let cleaned_content = content_safe(ctx, args.rest(), &ContentSafeOptions::default()).await;
let typing = msg.channel_id.start_typing(&ctx.http)?;
| random_line_split |
main.rs | use std::{collections::HashSet, fs::File, sync::Arc, time::Duration};
use anyhow::{Context as _, Result};
use serenity::{
async_trait,
client::bridge::gateway::GatewayIntents,
framework::standard::{
macros::{command, group},
Args, CommandResult, StandardFramework,
},
futures::Stream... | mmand("forward")]
async fn forward(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let config = {
let data = ctx.data.read().await;
data.get::<ConfigContainer>().unwrap().clone()
};
let delegate_member = if let Ok(member) = ctx
.http
.get_member(config.guild... |
#[co | identifier_name |
main.rs | use std::{collections::HashSet, fs::File, sync::Arc, time::Duration};
use anyhow::{Context as _, Result};
use serenity::{
async_trait,
client::bridge::gateway::GatewayIntents,
framework::standard::{
macros::{command, group},
Args, CommandResult, StandardFramework,
},
futures::Stream... | fn parse_name_and_discriminator(
args: &mut Args,
) -> Option<Result<(String, u16), &'static str>> {
let mut name = String::new();
while let Ok(arg) = args.single::<String>() {
let mut fragment = arg.as_str();
if name.is_empty() {
match fragment.strip_prefix('@') {
... | et mut iter = text.splitn(2, pat);
Some((iter.next()?, iter.next()?))
}
async | identifier_body |
NeatDatePicker.js | import React, { useState, useEffect, } from 'react'
import { StyleSheet, TouchableOpacity, View, Text, Dimensions } from 'react-native'
import Modal from 'react-native-modal'
import PropTypes from 'prop-types'
import useDaysOfMonth from '../hooks/useDaysOfMonth';
import MDicon from 'react-native-vector-icons/MaterialIc... | {sevenDays.map((weekDay, index) => (
<View style={styles.keys} key={index.toString()}>
<Text style={[styles.weekDays, { color: weekDaysColor }]}>
{weekDay}
</Text>
... | <View style={styles.keys_container}>
{/* week days */} | random_line_split |
country-card.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import 'rxjs/add/operator/switchMap';
import { CountryCardService } from './country-card.service';
declare ... |
});
}
resetStyle(e: any) {
this.geoJsonLayer(e.target);
}
removeGeoLayer = function () {
if (this.geoJsonLayer != undefined) {
this.mapObj.removeLayer(this.geoJsonLayer);
}
}
// chart
loadSpiderChart() {
Highcharts.chart('spider-chart-container', {
chart: {
... | {
var currentBounds = L.geoJson(layer).getBounds();
this.mapObj.fitBounds(currentBounds);
setTimeout(() => {
let zoomDiff = this.mapObj.getZoom()
if (this.mapObj.getZoom() > 4) {
zoomDiff = 4;
}
this.mapObj.setView(this.mapObj.getCenter(), zoom... | conditional_block |
country-card.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import 'rxjs/add/operator/switchMap';
import { CountryCardService } from './country-card.service';
declare ... |
getCountriesList() {
this.countryCardService
.getCountryList()
.then(responseObj => {
this.countriesList = this.countryCardService.getSortedData(responseObj.features); // first sort the response object
});
}
// country data
getCountryData() {
this.countryCardService
... | {
this.countryCardService
.getShapeFile()
.then(responseObj => {
this.geoJsonData = responseObj;
this.loadmap();
this.loadlayer();
});
} | identifier_body |
country-card.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import 'rxjs/add/operator/switchMap';
import { CountryCardService } from './country-card.service';
declare ... |
// change the country for country card event hadler
onSelect(selection: any) {
this.selectedCountryName = selection.properties.name;
this.selectedCountryId = selection.properties.iso_a3;
this.selectedCountryFlagId = selection.properties.iso_a2.toLowerCase();
this.router.navigate(['/country-card', ... | random_line_split | |
country-card.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import 'rxjs/add/operator/switchMap';
import { CountryCardService } from './country-card.service';
declare ... | (e: any) {
this.geoJsonLayer(e.target);
}
removeGeoLayer = function () {
if (this.geoJsonLayer != undefined) {
this.mapObj.removeLayer(this.geoJsonLayer);
}
}
// chart
loadSpiderChart() {
Highcharts.chart('spider-chart-container', {
chart: {
polar: true,
ty... | resetStyle | identifier_name |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... | }
fn document_from_form_data(storage_file: StorageFile, metadata: BlobMetadata) -> Document {
Document {
id: metadata.file_name.to_string(),
name: metadata.title.to_string(),
document_type: DocumentType::Par,
author: metadata.author.to_string(),
products: metadata.product_na... | random_line_split | |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... |
fn product_form_data_to_blob_metadata(
file_name: String,
fields: Vec<Field>,
) -> Result<BlobMetadata, SubmissionError> {
let product_name = get_field_as_uppercase_string(&fields, "product_name")?;
let product_names = vec![product_name];
let title = get_field_as_uppercase_string(&fields, "title... | {
let mut products = Vec::new();
let mut file_field = None;
for field in fields {
if field.name == "file" {
file_field = Some(field.value);
continue;
}
if field.name == "product_name" {
products.push(vec![]);
}
match products.las... | identifier_body |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... |
None => {
let group = vec![field];
products.push(group);
}
}
}
let file_name = file_field
.as_ref()
.and_then(|field| field.file_name())
.ok_or(SubmissionError::MissingField { name: "file" })?
.to_string();
le... | {
group.push(field);
} | conditional_block |
pars_upload.rs | use crate::{
create_manager::models::BlobMetadata,
document_manager::{accept_job, check_in_document_handler, delete_document_handler},
models::{Document, FileSource, JobStatusResponse, UniqueDocumentIdentifier},
multipart_form_data::{collect_fields, Field},
state_manager::{with_state, JobStatusClien... | {
job_ids: Vec<Uuid>,
}
#[derive(Debug, Serialize)]
struct UpdateResponse {
delete: JobStatusResponse,
upload: Vec<Uuid>,
}
async fn read_pars_upload(
form_data: FormData,
) -> Result<(Vec<BlobMetadata>, Vec<u8>), SubmissionError> {
let fields = collect_fields(form_data)
.await
.m... | UploadResponse | identifier_name |
calc_CORL2017_Tables.py | # Programmed by Mojtaba Valipour @ Shiraz University - 2018 - vpcom.ir
# Based on the CVC code available in the github repository
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://o... | </style>
<title> Self-Driving Car Research </title>
<p>By Mojtaba Valipour @ Shiraz University - 2018 </p>
<p><a href="http://vpcom.ir/">vpcom.ir</a></p>
</head>
<body><p>MODEL: %s</a></p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p></body>
</html>
"""
# Tested by latexbase.com
late... | background-color: #dddddd;
} | random_line_split |
calc_CORL2017_Tables.py | # Programmed by Mojtaba Valipour @ Shiraz University - 2018 - vpcom.ir
# Based on the CVC code available in the github repository
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://o... |
#print(dataListTable2)
if(table1Flag):
# Accumulate the whole results and calculate std and avg
for tIdx, t in enumerate(dataListTable1):
dataSuccessRate[tIdx][sIdx] = np.mean(t)
dataSuccessRateSTD[tIdx][sIdx]... | dataListTable2[metricIdx][i].append(summed_driven_kilometers[i] / metric_sum_values[i]) | conditional_block |
sketch.js |
// Adding comments because I'm going to forget code
// also in case someone decides to use my code for some odd reason
// like at least use it correctly jeez,
// and change the names of those classes if you really don't want to credit me
//-----Variables-----//
///image variables:
////bunny directions
var bunnyLeft;... | (Bunny) {
if (abs(this.x - Bunny.x) < 20
&& abs(this.y - Bunny.y) < 20){
gameState = 2;
}
}
}
class platform {
constructor(_x, _y, _length) {
this.x = _x;
this.y = _y;
this.length = _length;
}
display() {
imageMode(CORNER);
// fill(25);
// rect(this.x, this.y, thi... | check | identifier_name |
sketch.js |
// Adding comments because I'm going to forget code
// also in case someone decides to use my code for some odd reason
// like at least use it correctly jeez,
// and change the names of those classes if you really don't want to credit me
//-----Variables-----//
///image variables:
////bunny directions
var bunnyLeft;... |
else if (6 <= i) {
let y = HEIGHT/2 - HEIGHT/5 + (platformSize + 10);
platforms[i] = new platform(x, y, platformSize);
}
else if (3 <= i < 6) {
let y = HEIGHT/2 - HEIGHT/5 + (platformSize + 10) * 2;
platforms[i] = new platform(x, y, platformSize);
}
}
//an array of spots/tomatoes! altered... | {
let y = HEIGHT/2 - HEIGHT/5;
platforms[i] = new platform(x, y, platformSize);
} | conditional_block |
sketch.js | // Adding comments because I'm going to forget code
// also in case someone decides to use my code for some odd reason
// like at least use it correctly jeez,
// and change the names of those classes if you really don't want to credit me
//-----Variables-----//
///image variables:
////bunny directions
var bunnyLeft;
... | function gameOver(){
imageMode(CORNER);
//graphics
background(grassimg);
textFont(font);
textSize(50);
fill(255, 200, 0, 200);
textAlign(CENTER);
text("Game Over!", WIDTH/2, HEIGHT/4);
textSize(20);
text("Final Score: " + score, WIDTH/2, HEIGHT/4 + 30);
textSize(25);
text("Press Space to... | //game over | random_line_split |
rbtree.go | // Copyright 2020 wongoo@apache.org. All rights reserved.
// a red-black tree implement
// the node only contains pointers to left/right child, not for the parent, for saving storage space for large tree.
package rbtree
import (
"sync"
"github.com/vogo/goalg/compare"
)
// Color node color
type Color bool
func (c... | () bool {
return n.Left == nil || n.Left.Color == Black
}
// LeftRed the left child of a node is black if not nil and its color is black.
func (n *Node) LeftRed() bool {
return n.Left != nil && n.Left.Color == Red
}
// RightBlack the right child of a node is black if nil or its color is black.
func (n *Node) RightB... | LeftBlack | identifier_name |
rbtree.go | // Copyright 2020 wongoo@apache.org. All rights reserved.
// a red-black tree implement
// the node only contains pointers to left/right child, not for the parent, for saving storage space for large tree.
package rbtree
import (
"sync"
"github.com/vogo/goalg/compare"
)
// Color node color
type Color bool
func (c... |
s := stack.sibling()
// case 3: P is red, S is red, PP is black
// execute: set P,S to black, PP to red
// result: black count through PP is not change, continue balance on parent of PP
if s != nil && s.Color == Red {
p.Color = Black
s.Color = Black
pp.Color = Red
stack.pop().pop()
continu... | {
return
} | conditional_block |
rbtree.go | // Copyright 2020 wongoo@apache.org. All rights reserved.
// a red-black tree implement
// the node only contains pointers to left/right child, not for the parent, for saving storage space for large tree.
package rbtree
import (
"sync"
"github.com/vogo/goalg/compare"
)
// Color node color
type Color bool
func (c... | node = node.Left
case node.Item.Less(item):
stack.push(node, Right)
node = node.Right
default:
ret = node.Item
break FOR
}
}
// not find
if node == nil {
return root, nil
}
var inorderSuccessor *Node
// find the inorder successor
if node.Right != nil {
stack.push(node, Right)
inord... | FOR:
for node != nil {
switch {
case item.Less(node.Item):
stack.push(node, Left) | random_line_split |
rbtree.go | // Copyright 2020 wongoo@apache.org. All rights reserved.
// a red-black tree implement
// the node only contains pointers to left/right child, not for the parent, for saving storage space for large tree.
package rbtree
import (
"sync"
"github.com/vogo/goalg/compare"
)
// Color node color
type Color bool
func (c... |
// RightRed the right child of a node is black if not nil and its color is black.
func (n *Node) RightRed() bool {
return n.Right != nil && n.Right.Color == Red
}
// RBTree red-black tree
type RBTree struct {
Node *Node
lock sync.RWMutex
stack *stack
}
// New create a new red-black tree
func New() *RBTree {
... | {
return n.Right == nil || n.Right.Color == Black
} | identifier_body |
Estimate_Hazard.py | import csv
import numpy as np
import scipy as sp
from scipy.stats import exponweib
import matplotlib
import matplotlib.pyplot as plt
import pandas
import thinkstats2
import thinkbayes2
import survival
import thinkplot
import random
import math
houselist=['Wildling','None','Night\'s Watch','Lannister','House Lannister... | (k, lam, age, alive):
joint = thinkbayes2.MakeJoint(k, lam)
suite = GOT(joint)
suite.Update((age, alive))
k, lam = suite.Marginal(0, label=k.label), suite.Marginal(1, label=lam.label)
return k, lam
def makePMF(k,lam):
k.label = 'K'
lam.label = 'Lam'
print("Updating deaths")
numDead = len(dead)
ticks = math... | Update | identifier_name |
Estimate_Hazard.py | import csv
import numpy as np
import scipy as sp
from scipy.stats import exponweib
import matplotlib
import matplotlib.pyplot as plt
import pandas
import thinkstats2
import thinkbayes2
import survival
import thinkplot
import random
import math
houselist=['Wildling','None','Night\'s Watch','Lannister','House Lannister... |
for info in data:
for key in houselist:
house_list(key,info)
def ages(alive,dead):
got=72
cok=69
sos=81
ffc=45
dwd=72
bd={'got':got,'cok':cok,'sos':sos,'ffc':ffc,'dwd':dwd}
bnd={'got':0,'cok':1,'sos':2,'ffc':3,'dwd':4}
introductions=[]
lifetimes=[]
for pers in dead:
if pers[9]=='1':
start='got'
... | print 'e',info | conditional_block |
Estimate_Hazard.py | import csv
import numpy as np
import scipy as sp
from scipy.stats import exponweib
import matplotlib
import matplotlib.pyplot as plt
import pandas
import thinkstats2
import thinkbayes2
import survival
import thinkplot
import random
import math
houselist=['Wildling','None','Night\'s Watch','Lannister','House Lannister... | for key in houselist:
house_list(key,info)
def ages(alive,dead):
got=72
cok=69
sos=81
ffc=45
dwd=72
bd={'got':got,'cok':cok,'sos':sos,'ffc':ffc,'dwd':dwd}
bnd={'got':0,'cok':1,'sos':2,'ffc':3,'dwd':4}
introductions=[]
lifetimes=[]
for pers in dead:
if pers[9]=='1':
start='got'
elif pers[10]=='1':... | print 'e',info
for info in data: | random_line_split |
Estimate_Hazard.py | import csv
import numpy as np
import scipy as sp
from scipy.stats import exponweib
import matplotlib
import matplotlib.pyplot as plt
import pandas
import thinkstats2
import thinkbayes2
import survival
import thinkplot
import random
import math
houselist=['Wildling','None','Night\'s Watch','Lannister','House Lannister... |
# for house in ['Martell','None']
# alive,dead=char_lists(house)
# introductions,lifetimes=ages(alive,dead)
# sf,haz=SurvivalHaz(introductions,lifetimes)
# # kal,kah,lal,lah=cred_params(house)
# # CredIntPlt(sf,kal,kah,lal,lah,house,2.5559687549462544,0.26786495258406434) #NW all
# if house=='Martell':
# ka... | cur_house=hd[house]
alive1=cur_house[1][1][1] #Noble Men
alive2=cur_house[1][1][2] #Noble Women
alive3=cur_house[1][2][1] #Small Men
alive4=cur_house[1][2][2] #Small Women
alive1.pop(0)
alive2.pop(0)
alive3.pop(0)
alive4.pop(0)
dead1=cur_house[0][1][1]
dead2=cur_house[0][1][2]
dead3=cur_house[0][2][1]
dea... | identifier_body |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... |
// Finally grow the crack with the current parameters which may have been optimised.
// We exit here if the scale has not been set. Otherwise we
// would go through and do a default calculation which confuses
// people if they just want to start the program to see how to get
// help.
fn generate_crack_history(option... | {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors),
OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options, &mut factors),
OptimMethod::All => {
... | identifier_body |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... | OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options, &mut factors),
OptimMethod::All => {
sweep::sweep(options, &mut factors);
optimise::nelder_match_crack(options, &mut factors);
... | fn optimise_error(options: &options::EasiOptions, mut factors: &mut [f64]) {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors), | random_line_split |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... |
};
}
// Finally grow the crack with the current parameters which may have been optimised.
// We exit here if the scale has not been set. Otherwise we
// would go through and do a default calculation which confuses
// people if they just want to start the program to see how to get
// help.
fn generate_crack_histo... | {
sweep::sweep(options, &mut factors);
optimise::nelder_match_crack(options, &mut factors);
optimise_gsl::gsl_match_crack(options, &mut factors)
} | conditional_block |
main.rs | /// easiGrow
///
/// by Paul White (Nov 2014--2017)
/// written in rust (www.rust-lang.org)
///
/// A program to match crack growth predictions to measurements.
///
/// The program calculates fatigue crack growth rates and finds the
/// optimum parameters of a crack growth model to match predictions
/// with measuremen... | (options: &options::EasiOptions, mut factors: &mut [f64]) {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors),
OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options... | optimise_error | identifier_name |
player.go | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to wri... | (w http.ResponseWriter, r *http.Request,
gameId, color string, minutes int, cleanup, switchColors func(),
username, userId string) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
http.Error(w, "Could not upgrade conn", http.StatusInternalServerError)
return
}
playerClock := time.... | serveGame | identifier_name |
player.go | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to wri... |
// JSON-marshal and send message to the connection.
func sendTextMsg(data map[string]string, conn *websocket.Conn) error {
dataB, err := json.Marshal(data)
if err != nil {
return err
}
conn.SetWriteDeadline(time.Now().Add(writeWait))
w, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
return ... | {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
p.conn.Close()
}()
for {
select {
case <-p.disconnect:
// Finish this goroutine to not to send messages anymore
return
case move, ok := <-p.sendMove: // Opponent moved a piece
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
... | identifier_body |
player.go | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to wri... |
w, err := p.conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Println("Could not make next writer:", err)
return
}
w.Write(msgB)
// Add queued chat messages to the current websocket message.
n := len(p.sendChat)
for i := 0; i < n; i++ {
msg = <-p.sendChat
if (msg.userId ... | {
log.Println("Could not marshal data:", err)
break
} | conditional_block |
player.go | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to wri... | clock: playerClock,
color: color,
conn: conn,
gameId: gameId,
oppRanOut: make(chan bool, 1),
disconnect: make(chan bool),
drawOffer: make(chan bool, 1),
oppAcceptedDraw: make(chan bool, 1),
oppResigned: make(chan b... | cleanup: cleanup, | random_line_split |
plugin.go | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// isImageAllowed returns true if the image matches against the list of allowed matches by the plugin.
func (p *pluginProvider) isImageAllowed(image string) bool {
for _, matchImage := range p.matchImages {
if matched, _ := credentialprovider.URLsMatchStr(matchImage, image); matched {
return true
}
}
retur... | {
return true
} | identifier_body |
plugin.go | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | if !ok {
klog.Errorf("Invalid response type returned by external credential provider")
return credentialprovider.DockerConfig{}
}
var cacheKey string
switch cacheKeyType := response.CacheKeyType; cacheKeyType {
case credentialproviderapi.ImagePluginCacheKeyType:
cacheKey = image
case credentialproviderapi.... | klog.Errorf("Failed getting credential from external registry credential provider: %v", err)
return credentialprovider.DockerConfig{}
}
response, ok := res.(*credentialproviderapi.CredentialProviderResponse) | random_line_split |
plugin.go | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error) {
mediaType := "application/json"
info, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)
if !ok {
return nil, fmt.Errorf("unsupported media type %q", mediaType)
}
gv, ok := apiVersions[prov... | newPluginProvider | identifier_name |
plugin.go | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
gv, ok := apiVersions[provider.APIVersion]
if !ok {
return nil, fmt.Errorf("invalid apiVersion: %q", provider.APIVersion)
}
clock := clock.RealClock{}
return &pluginProvider{
clock: clock,
matchImages: provider.MatchImages,
cache: cache.NewExpirationStore(cacheKey... | {
return nil, fmt.Errorf("unsupported media type %q", mediaType)
} | conditional_block |
Article.js | import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import { Link } from "react-router-dom";
import HomeBar from "./Home-bar";
import Claps from "./Article-part/Claps";
import Avatar from "@material-ui/... | () {
var [ claps, setClaps] = React.useState(0);
const follows = [
{
image:
"https://upload.wikimedia.org/wikipedia/commons/a/a7/20180602_FIFA_Friendly_Match_Austria_vs._Germany_Mesut_%C3%96zil_850_0704.jpg",
nama: "Amin Subagiyo",
comment:
"Lorem ipsum dolor sit amet, consec... | Article | identifier_name |
Article.js | import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import { Link } from "react-router-dom";
import HomeBar from "./Home-bar";
import Claps from "./Article-part/Claps";
import Avatar from "@material-ui/... | Lying by Ryan Holiday / The Brass Check by Upton Sinclair I strongly
recommend that you take the time in 2018 to read these books. In light
of this year, you owe it to yourself to study and better understand
how our media system works. In The Filter Bubble, Eli Pariser warns of
... | also knew how to tell a story and create a collective cause. He could
work within the system but knew how to shake it up and generate
attention. This book is a classic and woefully underrated. Whatever
you set out to do in 2018, this book can provide you with strategic
... | random_line_split |
Article.js | import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import { Link } from "react-router-dom";
import HomeBar from "./Home-bar";
import Claps from "./Article-part/Claps";
import Avatar from "@material-ui/... | {
var [ claps, setClaps] = React.useState(0);
const follows = [
{
image:
"https://upload.wikimedia.org/wikipedia/commons/a/a7/20180602_FIFA_Friendly_Match_Austria_vs._Germany_Mesut_%C3%96zil_850_0704.jpg",
nama: "Amin Subagiyo",
comment:
"Lorem ipsum dolor sit amet, consectet... | identifier_body | |
__init__.py | import types
def escape_text(text=''):
text = str(text)
return text.replace("\'", "\\'")
class GaqHub(object):
data_struct = None
def __init__(self, account_id, single_push=False):
"""Sets up self.data_struct dict which we use for storage.
You'd probably have something like thi... |
if self.data_struct['_trackTrans']:
if single_push:
single_pushes.append(u"""['_trackTrans']""")
else:
script.append(u"""_gaq.push(['_trackTrans']);""")
# events seem to be on their own.
for category in ['_trackEvent']:
for i ... | for i in self.data_struct[category]:
if single_push:
single_pushes.append(i)
else:
script.append(u"""_gaq.push(%s);""" % i) | random_line_split |
__init__.py | import types
def escape_text(text=''):
text = str(text)
return text.replace("\'", "\\'")
class GaqHub(object):
data_struct = None
def __init__(self, account_id, single_push=False):
"""Sets up self.data_struct dict which we use for storage.
You'd probably have something like thi... |
def as_html(self):
"""helper function. prints out GA code for you, in the right order.
You'd probably call it like this in a Mako template:
<head>
${h.as_html()|n}
</head>
Notice that you have to escape under Mako. For more information on mako es... | if single_push:
script.append(u"""_gaq.push(""")
# according to GA docs, the order to submit via javascript is:
# # _setAccount
# # _setDomainName
# # _setAllowLinker
# #
# # cross domain tracking reference
# # http://code.google.com/apis/analytics/do... | identifier_body |
__init__.py | import types
def escape_text(text=''):
text = str(text)
return text.replace("\'", "\\'")
class GaqHub(object):
data_struct = None
def __init__(self, account_id, single_push=False):
"""Sets up self.data_struct dict which we use for storage.
You'd probably have something like thi... |
else:
script.append(u"""_gaq.push(['_trackTrans']);""")
# events seem to be on their own.
for category in ['_trackEvent']:
for i in self.data_struct[category]:
if single_push:
single_pushes.append(i)
else:
... | single_pushes.append(u"""['_trackTrans']""") | conditional_block |
__init__.py | import types
def | (text=''):
text = str(text)
return text.replace("\'", "\\'")
class GaqHub(object):
data_struct = None
def __init__(self, account_id, single_push=False):
"""Sets up self.data_struct dict which we use for storage.
You'd probably have something like this in your base controller:
... | escape_text | identifier_name |
aio.rs | use std::default::Default;
use std::io;
use std::thread::{self, JoinHandle};
use std::time::SystemTime;
use mio;
use core::pin::Pin;
use futures::channel::{mpsc, oneshot};
use futures::executor;
use futures::stream::Stream;
use futures::task::Context;
use futures::{Future, Poll};
use bytes::BytesMut;
use eventfd::Ev... | // let file = DirectFile::open(path.clone(), Mode::Open, FileAccess::Read, 4096).unwrap();
// let mut buf = BytesMut::with_capacity(512);
// unsafe { buf.set_len(512) };
// let (tx, rx) = oneshot::channel();
// session.inner.send(Message::PRead(file, 0, 512, b... |
// let reads = (0..5).map(|_| {
// println!("foo"); | random_line_split |
aio.rs | use std::default::Default;
use std::io;
use std::thread::{self, JoinHandle};
use std::time::SystemTime;
use mio;
use core::pin::Pin;
use futures::channel::{mpsc, oneshot};
use futures::executor;
use futures::stream::Stream;
use futures::task::Context;
use futures::{Future, Poll};
use bytes::BytesMut;
use eventfd::Ev... | {
curr_polls: u64,
curr_preads: u64,
curr_pwrites: u64,
prev_polls: u64,
prev_preads: u64,
prev_pwrites: u64,
}
impl Future for AioThread {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
trace!(
"============ AioThread... | AioStats | identifier_name |
workflow.py | """
Base implementation for high level workflow.
The goal of this design is to make it easy to share
code among different variants of the Inferelator workflow.
"""
from __future__ import unicode_literals, print_function
from inferelator import utils
from inferelator.utils import Validator as check
from inferelator im... | the preprocessing/postprocessing workflow
"""
return create_inferelator_workflow(regression=regression, workflow=workflow)() | random_line_split | |
workflow.py | """
Base implementation for high level workflow.
The goal of this design is to make it easy to share
code among different variants of the Inferelator workflow.
"""
from __future__ import unicode_literals, print_function
from inferelator import utils
from inferelator.utils import Validator as check
from inferelator im... |
else:
raise ValueError("Workflow must be a string that maps to a workflow class or an actual workflow class")
# Decide which regression workflow to use
# Return just the workflow if regression is set to None
if regression is None:
return workflow_class
# String arguments are parsed... | workflow_class = workflow | conditional_block |
workflow.py | """
Base implementation for high level workflow.
The goal of this design is to make it easy to share
code among different variants of the Inferelator workflow.
"""
from __future__ import unicode_literals, print_function
from inferelator import utils
from inferelator.utils import Validator as check
from inferelator im... | (expression_matrix):
"""
Create a meta_data dataframe from basic defaults
"""
metadata_rows = expression_matrix.columns.tolist()
metadata_defaults = {"isTs": "FALSE", "is1stLast": "e", "prevCol": "NA", "del.t": "NA", "condName": None}
data = {}
for key in metadata... | create_default_meta_data | identifier_name |
workflow.py | """
Base implementation for high level workflow.
The goal of this design is to make it easy to share
code among different variants of the Inferelator workflow.
"""
from __future__ import unicode_literals, print_function
from inferelator import utils
from inferelator.utils import Validator as check
from inferelator im... |
def inferelator_workflow(regression=RegressionWorkflow, workflow=WorkflowBase):
"""
Create and instantiate a workflow
:param regression: RegressionWorkflow subclass
A class object which implements the run_regression and run_bootstrap methods for a specific regression strategy
:param workflow... | """
This is the factory method to create workflow ckasses that combine preprocessing and postprocessing (from workflow)
with a regression method (from regression)
:param regression: RegressionWorkflow subclass
A class object which implements the run_regression and run_bootstrap methods for a specif... | identifier_body |
handshake.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The handshake module implements the handshake part of the protocol.
//! This module also implements additional anti-DoS mitigation,
//! by including a timestamp in each handshake initialization message.
//! Refer to the module's do... | their_public_key
),
));
}
}
// if on a mutually authenticated network
if let Some(anti_replay_timestamps) = &anti_replay_timestamps {
// check that the payload received as the client timestamp (in seconds)
... | // TODO: security logging (mimoo)
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"noise: client connecting to us with an unknown public key: {}", | random_line_split |
handshake.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The handshake module implements the handshake part of the protocol.
//! This module also implements additional anti-DoS mitigation,
//! by including a timestamp in each handshake initialization message.
//! Refer to the module's do... |
};
self.dial(socket, anti_replay_timestamps.is_some(), remote_public_key)
.await?
}
ConnectionOrigin::Inbound => {
self.accept(socket, anti_replay_timestamps, trusted_peers)
.await?
}
};
... | {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"noise: SHOULD NOT HAPPEN: missing server's key when dialing",
));
} | conditional_block |
handshake.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The handshake module implements the handshake part of the protocol.
//! This module also implements additional anti-DoS mitigation,
//! by including a timestamp in each handshake initialization message.
//! Refer to the module's do... | (&self, pubkey: x25519::PublicKey, timestamp: u64) -> bool {
if let Some(last_timestamp) = self.0.get(&pubkey) {
×tamp <= last_timestamp
} else {
false
}
}
/// Stores the timestamp
pub fn store_timestamp(&mut self, pubkey: x25519::PublicKey, timestamp: u... | is_replay | identifier_name |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... | (&self) -> u32 {
self.fields.flags
}
/// Returns the detected local APIC structures.
pub fn lapic(&self) -> &[MadtLapic] {
&self.lapic_entries[..self.num_lapic_entries]
}
}
| flags | identifier_name |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... |
}
// If we reach this point, the table could not be found.
Err(Error::NotFound)
}
}
/// Size of the SDT header.
const ACPI_MADT_FIELDS_SIZE: usize = core::mem::size_of::<AcpiMadtFields>();
/// Maximum number of entries in the MADT.
const ACPI_MADT_ENTRIES_LEN: usize = 256;
/// Extra fie... | {
return unsafe { Madt::new(entry.try_into()?) };
} | conditional_block |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... |
/// Local Interrupt Controller Address. In other words, the 32-bit physical
/// address at which each processor can access its local interrupt
/// controller.
pub fn lapic_addr(&self) -> u32 {
self.fields.lapic_addr
}
/// Multiple ACPI flags.
///
/// Bit offset | Bit length | ... | {
// Parse header.
let hdr = AcpiSdtHeader::new(madt_ptr, SdtType::Madt)?;
// Parse fields.
let fields = core::ptr::read_unaligned(
(madt_ptr.0 as *const u8).add(ACPI_SDT_SIZE)
as *const AcpiMadtFields,
);
// Parse entries.
let mut nu... | identifier_body |
acpi.rs | //! This module provides access to ACPI.
use core::convert::TryInto;
use crate::utils;
use crate::{Error, Ptr};
/// Signature of the RSDP structure.
const ACPI_RSDP_SIGNATURE: &[u8] = b"RSD PTR ";
/// Size of the SDT header.
const ACPI_SDT_SIZE: usize = core::mem::size_of::<AcpiSdtHeader>();
/// Root System Descri... | Xsdt,
Madt,
}
impl SdtType {
/// Returns the signature of the SDT.
fn signature(&self) -> &[u8] {
match self {
SdtType::Xsdt => b"XSDT",
SdtType::Madt => b"APIC",
}
}
}
/// System Description Table header of the ACPI specification. It is common to
/// all Sy... | random_line_split | |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... | let ranges = [10..20, 30..35, 45..55];
let core_ranges = [
Block {
range: 10..20,
offset: 0,
},
Block {
range: 25..35,
offset: 10,
},
Block {
range: 40..50,
... | mod tests {
use super::*;
#[test]
fn translate_ranges() { | random_line_split |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... |
// try to perform an action, either returning on success, or having the result
// of the error in an indented string.
//
// This special cases `DiskUsageEstimateExceeded` errors, as we want this to
// fail fast and bail out of the `try_method` caller.
macro_rules! try_method {
($func:expr) => {{
match $fu... | {
metadata(Path::new("/proc/kcore"))
.map(|x| x.len() > 0x2000)
.unwrap_or(false)
&& can_open(Path::new("/proc/kcore"))
} | identifier_body |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... | () {
let ranges = [10..20, 30..35, 45..55];
let core_ranges = [
Block {
range: 10..20,
offset: 0,
},
Block {
range: 25..35,
offset: 10,
},
Block {
range: 40..50,
... | translate_ranges | identifier_name |
snapshot.rs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#[cfg(target_family = "unix")]
use crate::disk_usage;
use crate::{
format_error,
image::{Block, Image},
};
use clap::ValueEnum;
use elf::{abi::PT_LOAD, endian::NativeEndian, segment::ProgramHeader};
#[cfg(not(target... | else if can_open(Path::new("/dev/crash")) {
self.create_source(&Source::DevCrash)?;
} else if can_open(Path::new("/dev/mem")) {
self.create_source(&Source::DevMem)?;
} else {
return Err(Error::UnableToCreateSnapshot(
"no source... | {
self.create_source(&Source::ProcKcore)?;
} | conditional_block |
real_comparison.py | #!/usr/bin/env python
import sys
import datetime
import glob
import operator as op
import numpy as np
import matplotlib.pyplot as plt
from bunch import Bunch
import mygis
wrf_dir="/glade/u/home/gutmann/scratch/wrfoutput/4km/2007/"
DIM_2D_SHAPE=3
DIM_3D_SHAPE=4
def echo(fn):
def wrapped(*v, **k):
print(... |
def __next__(self):
self.curpos+=1
output_data=Bunch()
filename=self.files[self._curfile]
for v in self._var_names:
if type(v)==str:
curdata=self.load_data(v)
curvarname=v
elif type(v)==l... | return self | identifier_body |
real_comparison.py | #!/usr/bin/env python
import sys
import datetime
import glob
import operator as op
import numpy as np
import matplotlib.pyplot as plt
from bunch import Bunch
import mygis
wrf_dir="/glade/u/home/gutmann/scratch/wrfoutput/4km/2007/"
DIM_2D_SHAPE=3
DIM_3D_SHAPE=4
def echo(fn):
def wrapped(*v, **k):
print(... | (self):
return self
def __next__(self):
self.curpos+=1
output_data=Bunch()
filename=self.files[self._curfile]
for v in self._var_names:
if type(v)==str:
curdata=self.load_data(v)
curvarname=v
... | __iter__ | identifier_name |
real_comparison.py | #!/usr/bin/env python
import sys
import datetime
import glob
import operator as op
import numpy as np
import matplotlib.pyplot as plt
from bunch import Bunch
import mygis
wrf_dir="/glade/u/home/gutmann/scratch/wrfoutput/4km/2007/"
DIM_2D_SHAPE=3
DIM_3D_SHAPE=4
def echo(fn):
def wrapped(*v, **k):
print(... |
fig=make_plots(icar,wrf,wrf.date,fig=fig)
fig.savefig(output_filename.format(str(wrf.date).replace(" ","_")))
if __name__ == '__main__':
global wrf_dir
out_dir="./"
icar_dir="output/"
if len(sys.argv)>1:
if sys.argv[1][:2]=="-h":
print("Usage: real_c... | random_line_split | |
real_comparison.py | #!/usr/bin/env python
import sys
import datetime
import glob
import operator as op
import numpy as np
import matplotlib.pyplot as plt
from bunch import Bunch
import mygis
wrf_dir="/glade/u/home/gutmann/scratch/wrfoutput/4km/2007/"
DIM_2D_SHAPE=3
DIM_3D_SHAPE=4
def echo(fn):
def wrapped(*v, **k):
print(... |
# Get/Set the position in the timeseries, while properly updating the filenumber and position in file
@property
def curpos(self):
return self._curpos
@curpos.setter
def curpos(self,pos):
self._curpos=pos
self._pos_in_file= int(self._curpos) % int(self.times_per_fi... | return data | conditional_block |
PanoImageRenderer.js | import Component from "@egjs/component";
import {glMatrix, vec3, mat3, mat4, quat} from "gl-matrix";
import ImageLoader from "./ImageLoader";
import VideoLoader from "./VideoLoader";
import WebGLUtils from "./WebGLUtils";
import Renderer from "./renderer/Renderer";
import CubeRenderer from "./renderer/CubeRenderer";
im... | ldOfView && this.fieldOfView === fieldOfView &&
this._shouldForceDraw === false) {
return;
}
// updatefieldOfView only if fieldOfView is changed.
if (fieldOfView !== undefined && fieldOfView !== this.fieldOfView) {
this.updateFieldOfView(fieldOfView);
}
this.mvMatrix = mat4.fromQuat(mat4.create(), ... | ) &&
this.fie | conditional_block |
PanoImageRenderer.js | import Component from "@egjs/component";
import {glMatrix, vec3, mat3, mat4, quat} from "gl-matrix";
import ImageLoader from "./ImageLoader";
import VideoLoader from "./VideoLoader";
import WebGLUtils from "./WebGLUtils";
import Renderer from "./renderer/Renderer";
import CubeRenderer from "./renderer/CubeRenderer";
im... |
exitVR = () => {
const vr = this._vr;
const gl = this.context;
const animator = this._animator;
if (!vr) return;
vr.removeEndCallback(this.exitVR);
vr.destroy();
this._vr = null;
// Restore canvas & context on iOS
if (IS_IOS) {
this._restoreStyle();
}
this.updateViewportDimensions(this.wid... | random_line_split | |
PanoImageRenderer.js | import Component from "@egjs/component";
import {glMatrix, vec3, mat3, mat4, quat} from "gl-matrix";
import ImageLoader from "./ImageLoader";
import VideoLoader from "./VideoLoader";
import WebGLUtils from "./WebGLUtils";
import Renderer from "./renderer/Renderer";
import CubeRenderer from "./renderer/CubeRenderer";
im... | alConfig, renderingContextAttributes
) {
// Super constructor
super();
this.sphericalConfig = sphericalConfig;
this.fieldOfView = sphericalConfig.fieldOfView;
this.width = width;
this.height = height;
this._lastQuaternion = null;
this._lastYaw = null;
this._lastPitch = null;
this._lastFieldOfVie... | eo, spheric | identifier_name |
PanoImageRenderer.js | import Component from "@egjs/component";
import {glMatrix, vec3, mat3, mat4, quat} from "gl-matrix";
import ImageLoader from "./ImageLoader";
import VideoLoader from "./VideoLoader";
import WebGLUtils from "./WebGLUtils";
import Renderer from "./renderer/Renderer";
import CubeRenderer from "./renderer/CubeRenderer";
im... | ement("canvas");
canvas.width = width;
canvas.height = height;
this._onWebglcontextlost = this._onWebglcontextlost.bind(this);
this._onWebglcontextrestored = this._onWebglcontextrestored.bind(this);
canvas.addEventListener("webglcontextlost", this._onWebglcontextlost);
canvas.addEventListener("webglconte... | }
this._imageType = imageType;
this._isCubeMap = imageType === ImageType.CUBEMAP;
if (this._renderer) {
this._renderer.off();
}
switch (imageType) {
case ImageType.CUBEMAP:
this._renderer = new CubeRenderer();
break;
case ImageType.CUBESTRIP:
this._renderer = new CubeStripRenderer();... | identifier_body |
row.rs | /*
* Copyright (C) 2020, 2021 Yury Vostrikov
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the foll... | header_crc32c, header_crc32c_calculated);
}
let len = (&header[ROW_LAYOUT.size() - 8..]).read_u32::<LittleEndian>().unwrap();
let mut row = BoxRow { ptr: Self::alloc(len) };
row.as_bytes_mut().copy_from_slice(&header);
debug_assert!(row.len == len);
io... | random_line_split | |
row.rs | /*
* Copyright (C) 2020, 2021 Yury Vostrikov
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the foll... | (&self) -> &[u8] {
&self.0.get_ref()[self.0.position() as usize..]
}
}
pub fn print_row<W: fmt::Write + fmt::Debug>(buf: &mut W, row: &Row,
handler: &dyn Fn(&mut W, u16, &[u8])) -> Result<()> {
fn int_flag(name: &str, default: bool) -> bool {
let fla... | unparsed | identifier_name |
main.go | package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gorilla/handlers"
"github.com/kyma-project/kyma/components/apiserver-proxy/cmd/proxy/reload"
"github.com/kyma-project/kyma/components/apiserv... | (target *url.URL, kcfg *rest.Config, proxyForApiserver bool) (*httputil.ReverseProxy, error) {
rp := httputil.NewSingleHostReverseProxy(target)
rp.ModifyResponse = deleteUpstreamCORSHeaders
if proxyForApiserver {
t, err := rest.TransportFor(kcfg)
if err != nil {
return nil, fmt.Errorf("unable to set HTTP Tra... | newReverseProxy | identifier_name |
main.go | package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gorilla/handlers"
"github.com/kyma-project/kyma/components/apiserver-proxy/cmd/proxy/reload"
"github.com/kyma-project/kyma/components/apiserv... |
func main() {
cfg := config{
auth: proxy.Config{
Authentication: &authn.AuthnConfig{
X509: &authn.X509Config{},
Header: &authn.AuthnHeaderConfig{},
OIDC: &authn.OIDCConfig{},
},
Authorization: &authz.Config{},
},
cors: corsConfig{},
}
flagset := pflag.NewFlagSet(os.Args[0], pflag.Ex... | {
if version, ok := versions[versionName]; ok {
return version, nil
}
return 0, fmt.Errorf("unknown tls version %q", versionName)
} | identifier_body |
main.go | package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gorilla/handlers"
"github.com/kyma-project/kyma/components/apiserver-proxy/cmd/proxy/reload"
"github.com/kyma-project/kyma/components/apiserv... |
cert, err := tls.X509KeyPair(certBytes, keyBytes)
if err != nil {
glog.Fatalf("Failed to load generated self signed cert and key: %v", err)
}
version, err := tlsVersion(cfg.tls.minVersion)
if err != nil {
glog.Fatalf("TLS version invalid: %v", err)
}
cipherSuiteIDs, err := cliflag.TLSCip... | {
glog.Fatalf("Failed to generate self signed cert and key: %v", err)
} | conditional_block |
main.go | package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gorilla/handlers"
"github.com/kyma-project/kyma/components/apiserver-proxy/cmd/proxy/reload"
"github.com/kyma-project/kyma/components/apiserv... | glog.Fatalf("Failed to build parse upstream URL: %v", err)
}
spdyMetrics := monitoring.NewSPDYMetrics()
spdyProxy := spdy.New(kcfg, upstreamURL, spdyMetrics)
kubeClient, err := kubernetes.NewForConfig(kcfg)
if err != nil {
glog.Fatalf("Failed to instantiate Kubernetes client: %v", err)
}
var oidcAuthentic... | if err != nil { | random_line_split |
main.go | package main
import (
"code.google.com/p/go.net/websocket"
"code.google.com/p/goauth2/oauth"
"code.google.com/p/google-api-go-client/mirror/v1"
"code.google.com/p/google-api-go-client/oauth2/v2"
"encoding/json"
"fmt"
picarus "github.com/bwhite/picarus/go"
"github.com/gorilla/pat"
"github.com/ugorji/go-msgpack... |
func notifyOpenGlass(conn *picarus.Conn, svc *mirror.Service, trans *oauth.Transport, t *mirror.TimelineItem, userId string) {
if !hasFlagSingle(userId, "flags", "user_openglass") {
LogPrintf("openglass: flag user_openglass")
return
}
var err error
flags, err := getUserFlags(userId, "uflags")
if err != nil {... | {
a, err := svc.Timeline.Attachments.Get(t.Id, t.Attachments[0].Id).Do()
if err != nil {
LogPrintf("getattachment: metadata")
return nil, err
}
req, err := http.NewRequest("GET", a.ContentUrl, nil)
if err != nil {
LogPrintf("getattachment: http")
return nil, err
}
resp, err := trans.RoundTrip(req)
if er... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.