file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | #![warn(clippy::pedantic)]
mod error;
mod transport;
use crate::error::Result;
use crate::transport::{HttpQueryTransport, QueryParams};
use bottlerocket_release::BottlerocketRelease;
use chrono::Utc;
use log::debug;
use model::modeled_types::FriendlyVersion;
use semver::Version;
use serde::{Deserialize, Serialize};
u... | .arg("-r")
.status()
.context(error::RebootFailureSnafu)
{
// Kill the signal handling thread
signals_handle.close();
return Err(err);
}
Ok(())
}
/// Our underlying HTTP client, reqwest, supports proxies by reading the `HTTPS_PROXY` and `NO_PROXY`
/// environ... | random_line_split | |
main.rs | #![warn(clippy::pedantic)]
mod error;
mod transport;
use crate::error::Result;
use crate::transport::{HttpQueryTransport, QueryParams};
use bottlerocket_release::BottlerocketRelease;
use chrono::Utc;
use log::debug;
use model::modeled_types::FriendlyVersion;
use semver::Version;
use serde::{Deserialize, Serialize};
u... | () -> Result<()> {
let mut gpt_state = State::load().context(error::PartitionTableReadSnafu)?;
gpt_state.cancel_upgrade();
gpt_state.write().context(error::PartitionTableWriteSnafu)?;
Ok(())
}
fn set_common_query_params(
query_params: &mut QueryParams,
current_version: &Version,
config: &Co... | revert_update_flags | identifier_name |
main.rs | #![warn(clippy::pedantic)]
mod error;
mod transport;
use crate::error::Result;
use crate::transport::{HttpQueryTransport, QueryParams};
use bottlerocket_release::BottlerocketRelease;
use chrono::Utc;
use log::debug;
use model::modeled_types::FriendlyVersion;
use semver::Version;
use serde::{Deserialize, Serialize};
u... |
#[test]
fn older_versions() {
// A manifest with two updates, both less than 0.1.3.
// Use a architecture specific JSON payload, otherwise updog will ignore the update
let path = format!("tests/data/example_3_{TARGET_ARCH}.json");
let manifest: Manifest = serde_json::from_reade... | {
// A manifest with a single update whose version exceeds the max version.
// update in manifest has
// - version: 1.25.0
// - max_version: 1.20.0
let path = "tests/data/regret.json";
let manifest: Manifest = serde_json::from_reader(File::open(path).unwrap()).unwrap();
... | identifier_body |
main.go | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/shirou/gopsutil/cpu"
//"os/exec"
)
var (
index = 0
index2 = 0
Times [1000]string
Values [1000]string
Times2 [1000]string
Values2 [1000]string
)
type Strumemoria struct {
Total int... | (w http.ResponseWriter, r *http.Request) {
fmt.Println("ENTRE")
/* fmt.Fprintf(w, "Welcome to the HomePage!") //IMPRIME EN LA WEB
fmt.Println("Endpoint Hit: homePage")*/ //IMPRIMIR EN CONSOLA AL
b, err := ioutil.ReadFile("mockram.json")
if err != nil { //nil es contrario a null por asi decirlo
fmt.Println("pri... | obtenerram | identifier_name |
main.go | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/shirou/gopsutil/cpu"
//"os/exec"
)
var (
index = 0
index2 = 0
Times [1000]string
Values [1000]string
Times2 [1000]string
Values2 [1000]string
)
type Strumemoria struct {
Total int... |
//c fmt.Println("la memoria libre es ", respuestamem)
//conver := string(crearj)
// fmt.Println("EL indice es ", index)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
w.Write(crearj)
// convertir_a_cadena := string(jso... | {
fmt.Println("HAY UN ERROR")
http.Error(w, errorjson.Error(), http.StatusInternalServerError)
return
} | conditional_block |
main.go | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/shirou/gopsutil/cpu"
//"os/exec"
)
var (
index = 0
index2 = 0
Times [1000]string
Values [1000]string
Times2 [1000]string
Values2 [1000]string
)
type Strumemoria struct {
Total int... |
func main() {
//obtener ram
http.HandleFunc("/", obtenerram)
//obtener info del cpu
http.HandleFunc("/cpu", obtenercpu)
http.HandleFunc("/principal", obtenerprincipal)
http.HandleFunc("/post", reply)
log.Fatal(http.ListenAndServe(":3030", nil)) //log.fatal como que lo mantiene a la escucha y permite pararlo
... | {
fmt.Println("==============================")
fmt.Println("ENTRE A REPLY")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorizat... | identifier_body |
main.go | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/shirou/gopsutil/cpu"
//"os/exec"
)
var (
index = 0
index2 = 0
Times [1000]string
Values [1000]string
Times2 [1000]string
Values2 [1000]string
)
type Strumemoria struct {
Total int... | hayram:=true;
nombre:="";
for _,salto:= range splitsalto{
splitpuntos:=strings.Split(salto,":");
if(splitpuntos[0]=="Name"){
//fmt.Printf("El nombre del proceso con id: %s es: %s\n",nombreArchivo,splitpuntos[1])
textocompleto+=archivo.Name()+",";
aux:=strings.ReplaceAll(splitpuntos[1],"\... | if err != nil {
fmt.Printf("Error leyendo archivo: %v", err)
}
contenido := string(bytesLeidos)
splitsalto:=strings.Split(contenido,"\n"); | random_line_split |
PIL_ext.py | # -*- coding: utf-8 -*-
import itertools
import pathlib
import numpy as np
import numpy.linalg as LA
from PIL import Image
def tovector(image, k=None):
# image -> vector
data = np.asarray(image, dtype=np.float64)
if k:
return data[:,:, k].flatten()
else:
return data.f... |
def hstack(images, height=None):
'''Stack images horizontally
Arguments:
images {[Image]} -- list of images
Keyword Arguments:
height {Int} -- the common height of images (default: {None})
Returns:
Image -- the result of image stacking
'''
i... | random_line_split | |
PIL_ext.py | # -*- coding: utf-8 -*-
import itertools
import pathlib
import numpy as np
import numpy.linalg as LA
from PIL import Image
def tovector(image, k=None):
# image -> vector
data = np.asarray(image, dtype=np.float64)
if k:
return data[:,:, k].flatten()
else:
return data.f... | and f.suffix in exts:
im = Image.open(f)
images.append(im)
else:
raise LookupError('Invalid file name %s' % f)
if op:
images = [op(image) for image in images]
return images
def lrmerge(im1, im2, loc=None):
'''Merge left part of `im1` and r... | ))
break
elif f.exists() | conditional_block |
PIL_ext.py | # -*- coding: utf-8 -*-
import itertools
import pathlib
import numpy as np
import numpy.linalg as LA
from PIL import Image
def tovector(image, k=None):
# image -> vector
data = np.asarray(image, dtype=np.float64)
if k:
return data[:,:, k].flatten()
else:
return data.f... | (images, way='row'):
# image -> matrix
if way in {'r', 'row'}:
return np.row_stack([tovector(image) for image in images])
elif way in {'c', 'col', 'column'}:
return np.column_stack([tovector(image) for image in images])
def toimage(vector, size, mode='RGB'):
# vector -> image
... | tomatrix | identifier_name |
PIL_ext.py | # -*- coding: utf-8 -*-
import itertools
import pathlib
import numpy as np
import numpy.linalg as LA
from PIL import Image
def tovector(image, k=None):
# image -> vector
data = np.asarray(image, dtype=np.float64)
if k:
return data[:,:, k].flatten()
else:
return data.f... |
assert len(images) == 9, 'exactly 9 images'
return tile([imags[:3], images[3:6], images[6:9]])
def center_paste(image, other):
# put other onto the center of the image
width1, height1 = image.size
width2, height2 = other.size
image.paste(other, ((width1-width2)//2, (height1-height2)/... | ==1:
return images[0]
if n is None:
n = int(np.ceil(np.sqrt(N)))
layout = []
k = 0
while True:
if k+n<N:
layout.append(images[k:k+n])
elif k+n >= N:
layout.append(images[k:])
break
k += n
return tile(layout)
... | identifier_body |
app.py | from flask import Flask, request, render_template, jsonify, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaFiel... |
@app.route("/actualizarProducto/<id>", methods=["PUT"])
def update_product(id):
#recupera al producto
prod = Producto.query.get(id)
#recupera los campos del request
nombreProd = request.json['nombreProd']
precio = request.json['precio']
cantidad = request.json['cantidad']
categoria = reques... | _prods = Producto.query.all()
result = productos_schema.dump(all_prods)
#print(result)
return jsonify(result)
| identifier_body |
app.py | from flask import Flask, request, render_template, jsonify, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaFiel... | # OPERACIONES DE PRODUCTO - FIN
#///////////////////////////////////////
#-----------------------------------------------------------------------------------------------------------------
#///////////////////////////////////////
# LOGIN - Inicio (operaciones con el usuario)
#///////////////////////... | #/////////////////////////////////////// | random_line_split |
app.py | from flask import Flask, request, render_template, jsonify, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaFiel... | if "id_user" in session:
session.pop("id_user")
return render_template('index.html')
class RegisterForm(FlaskForm):#Crea el formulario de regisgtro del usuario
email=StringField('email',validators=[InputRequired(), Length(min=4,max=30)])
nombre=StringField('nombre',validators=[InputRequired(), Leng... | on.pop("user")
| conditional_block |
app.py | from flask import Flask, request, render_template, jsonify, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaFiel... |
form = ProductForm()
if request.method == "GET":
return render_template("AgregarProducto.html",form=form)
else:
if form.validate_on_submit():
nuevo_producto=Producto(nombreProd=form.nombreProd.data, precio=form.precio.data, cantidad=form.cantidad.data, categoria=form.categoria.d... | ate_product(): | identifier_name |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... | (&self, line: &str, code: &str) -> bool {
info!(
"checking for python module usage: line {} in code {}",
line, code
);
if line.contains('*') {
return true;
}
if line.contains(" as ") {
if let Some(name) = line.split(' ').last() {
... | module_used | identifier_name |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... |
}
}
impl Interpreter for Python3_original {
fn new_with_level(data: DataHolder, level: SupportLevel) -> Box<Python3_original> {
//create a subfolder in the cache folder
let rwd = data.work_dir.clone() + "/python3_original";
let mut builder = DirBuilder::new();
builder.recursive... | {
if let Some(venv_array_config) = Python3_original::get_interpreter_option(&self.get_data(), "venv") {
if let Some(actual_vec_of_venv) = venv_array_config.as_array() {
for possible_venv in actual_vec_of_venv.iter() {
if let Some(possible_venv_str)... | conditional_block |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... | self.code = self.data.current_line.clone();
} else {
self.code = String::from("");
}
Ok(())
}
fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
if !self.imports.is_empty() {
let mut indented_imports = String::new();
for i... | } else if !self.data.current_line.replace(" ", "").is_empty()
&& self.get_current_level() >= SupportLevel::Line
{ | random_line_split |
Python3_original.rs | #[derive(Clone)]
#[allow(non_camel_case_types)]
pub struct Python3_original {
support_level: SupportLevel,
data: DataHolder,
code: String,
imports: String,
interpreter: String,
main_file_path: String,
plugin_root: String,
cache_dir: String,
venv: Option<String>,
}
impl Python3_origin... |
fn get_name() -> String {
String::from("Python3_original")
}
fn behave_repl_like_default() -> bool {
false
}
fn has_repl_capability() -> bool {
true
}
fn default_for_filetype() -> bool {
true
}
fn get_supported_languages() -> Vec<String> {
... | {
// All cli arguments are sendable to python
// Though they will be ignored in REPL mode
Ok(())
} | identifier_body |
launch_fishbowl.py | from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QProgressBar, QComboBox, QDesktopWidget, \
QGridLayout, QSlider, QGroupBox, QVBoxLayout, QHBoxLayout, QStyle, QScrollBar, QMainWindow, QAction, QDialog
from PyQt5.QtCore import QDateTime, Qt, QTimer, QPoint, pyqtSignal, QLineF
from PyQt5.QtGui import QFont, QC... |
class Enemy(NPC):
def __init__(self, diameter, fishbowl_diameter):
super().__init__(diameter, fishbowl_diameter)
self.original_color = Qt.red
self.color = Qt.red
class Player(NPC):
"""
https://keon.io/deep-q-learning/
"""
def __init__(self, diameter, fishbowl_diameter, state_size):
super().__init__(di... | r -= self.d/2
dist = np.sqrt(np.sum(np.array(p) ** 2))
if dist > r:
return False
else:
return True | identifier_body |
launch_fishbowl.py | from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QProgressBar, QComboBox, QDesktopWidget, \
QGridLayout, QSlider, QGroupBox, QVBoxLayout, QHBoxLayout, QStyle, QScrollBar, QMainWindow, QAction, QDialog
from PyQt5.QtCore import QDateTime, Qt, QTimer, QPoint, pyqtSignal, QLineF
from PyQt5.QtGui import QFont, QC... | (self):
"""
waits 1 second so that the QT app is running and then launches the ball animation thread
"""
time.sleep(1)
self.fishbowl.animate_balls()
if __name__ == "__main__":
ui = gameUI()
ui.start_ui()
| start_animation | identifier_name |
launch_fishbowl.py | from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QProgressBar, QComboBox, QDesktopWidget, \
QGridLayout, QSlider, QGroupBox, QVBoxLayout, QHBoxLayout, QStyle, QScrollBar, QMainWindow, QAction, QDialog
from PyQt5.QtCore import QDateTime, Qt, QTimer, QPoint, pyqtSignal, QLineF
from PyQt5.QtGui import QFont, QC... |
self.first = False
self.v = self.dir * np.random.randint(low=40, high=100, size=2) * 0.00002
self.coords = self.spherical_clip(self.coords)
def check_killed_by(self, player):
p = player.coords
e = self.coords
dist = self.dist(e, p)
if dist < self.d:
self.dead = True
self.color = Qt.gray
@... | chosen_dir = np.random.randint(low=0, high=len(self.allowed_dirs))
self.dir = self.allowed_dirs[chosen_dir, :]
self.pvdi = chosen_dir | conditional_block |
launch_fishbowl.py | from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QProgressBar, QComboBox, QDesktopWidget, \
QGridLayout, QSlider, QGroupBox, QVBoxLayout, QHBoxLayout, QStyle, QScrollBar, QMainWindow, QAction, QDialog
from PyQt5.QtCore import QDateTime, Qt, QTimer, QPoint, pyqtSignal, QLineF
from PyQt5.QtGui import QFont, QC... | # draw alive enemies
for i, enemy in enumerate([x for x in self.enemies if not x.dead]):
qp.setBrush(QBrush(enemy.color, Qt.SolidPattern))
qp.drawEllipse(c + QPoint(*self.scale_point(enemy.coords)), *([self.npc_size] * 2))
# draw player
qp.setBrush(QBrush(self.player.color, Qt.SolidPattern))
qp.drawEll... |
# draw dead enemies
for i, enemy in enumerate([x for x in self.enemies if x.dead]):
qp.setBrush(QBrush(enemy.color, Qt.SolidPattern))
qp.drawEllipse(c + QPoint(*self.scale_point(enemy.coords)), *([self.npc_size] * 2)) | random_line_split |
frameworks.rs | // stripped mac core foundation + metal layer only whats needed
#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
pub use {
std::{
ffi::c_void,
os::raw::c_ulong,
ptr::NonNull,
},
crate::{
makepad_platform::{
os::app... | {
pub protocol: MIDIProtocolID,
pub numPackets: u32,
pub packet: [MIDIEventPacket; 1usize],
}
#[repr(C, packed(4))]
#[derive(Copy, Clone)]
pub struct MIDIEventPacket {
pub timeStamp: MIDITimeStamp,
pub wordCount: u32,
pub words: [u32; 64usize],
}
#[link(name = "CoreMidi", kind = "framework")]... | MIDIEventList | identifier_name |
frameworks.rs | // stripped mac core foundation + metal layer only whats needed
#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
pub use {
std::{
ffi::c_void,
os::raw::c_ulong,
ptr::NonNull,
},
crate::{
makepad_platform::{
os::app... |
pub const kAudioUnitManufacturer_Apple: u32 = 1634758764;
#[repr(C)] pub struct OpaqueAudioComponent([u8; 0]);
pub type CAudioComponent = *mut OpaqueAudioComponent;
#[repr(C)] pub struct ComponentInstanceRecord([u8; 0]);
pub type CAudioComponentInstance = *mut ComponentInstanceRecord;
pub type CAudioUnit = CAudioCo... | }
};
// CORE AUDIO | random_line_split |
models.py | # -*- coding: utf-8 -*-
# Copyright 2016, Digital Reasoning
#
# 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 applica... |
def set_status(self, event, status, detail, level=Level.INFO):
self.status = status
self.save()
self.history.create(event=event, status=status,
status_detail=detail, level=level)
def get_driver_hosts_map(self, host_ids=None):
"""
Stacks are ... | return u'{0} (id={1})'.format(self.title, self.id) | identifier_body |
models.py | # -*- coding: utf-8 -*-
# Copyright 2016, Digital Reasoning
#
# 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 applica... | (self):
return self.blueprint_host_definition.formula_components
def get_account(self):
return self.cloud_image.account
def get_provider(self):
return self.get_account().provider
def get_driver(self):
return self.cloud_image.get_driver()
| formula_components | identifier_name |
models.py | # -*- coding: utf-8 -*-
# Copyright 2016, Digital Reasoning
#
# 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 applica... | std_out_storage = models.TextField()
# The error output from the action
std_err_storage = models.TextField()
@property
def std_out(self):
if self.std_out_storage != "":
return json.loads(self.std_out_storage)
else:
return []
@property
def std_err(se... | # The command to be run (for custom actions)
command = models.TextField('Command')
# The output from the action | random_line_split |
models.py | # -*- coding: utf-8 -*-
# Copyright 2016, Digital Reasoning
#
# 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 applica... |
return result
def get_hosts(self, host_ids=None):
"""
Quick way of getting all hosts or a subset for this stack.
@host_ids (list); list of primary keys of hosts in this stack
@returns (QuerySet);
"""
if not host_ids:
return self.hosts.all()
... | result[account.get_driver()] = host_queryset.filter(id__in=[h.id for h in hosts]) | conditional_block |
download_data.py | import requests
from datetime import datetime, timedelta
import pandas as pd
import json
import os
from difflib import SequenceMatcher
import time
DATA_FOLDER = "./data"
base_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/"
date_format ='%m-%d-%Y... | population = pd.read_csv(f"./data/population/{name}", sep=";")
#population = population[population["Periodo"] == 2019]
#population = population[population["Sexo"] == "Total"]
population.drop(columns=['Periodo', 'Sexo'], inplace=True)
population['Comunidades y Ciudades Autónomas'] = [clean_name_pop(name... | " in pop:
return int(pop.replace(".",""))
| identifier_body |
download_data.py | import requests
from datetime import datetime, timedelta
import pandas as pd
import json
import os
from difflib import SequenceMatcher
import time
DATA_FOLDER = "./data"
base_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/"
date_format ='%m-%d-%Y... | lat_sum, lon_sum):
# For moving Canary Islands near Spain.
# l is the list of list of lists .... of coordinates
if isinstance(l, list) and isinstance(l[0], float) and isinstance(l[1], float):
return l[0] + lat_sum, l[1] + lon_sum
return [add_to_list(sub, lat_sum, lon_sum) for sub in l]
def red... | to_list(l, | identifier_name |
download_data.py | import requests
from datetime import datetime, timedelta
import pandas as pd
import json
import os
from difflib import SequenceMatcher
import time
DATA_FOLDER = "./data"
base_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/"
date_format ='%m-%d-%Y... | return result
#download_all_datasets()
def add_to_list(l, lat_sum, lon_sum):
# For moving Canary Islands near Spain.
# l is the list of list of lists .... of coordinates
if isinstance(l, list) and isinstance(l[0], float) and isinstance(l[1], float):
return l[0] + lat_sum, l[1] + lon_su... | lt.append(start_date.strftime(date_format))
start_date += step
| conditional_block |
download_data.py | import requests
from datetime import datetime, timedelta
import pandas as pd
import json
import os
from difflib import SequenceMatcher
import time
DATA_FOLDER = "./data"
base_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/"
date_format ='%m-%d-%Y... | r'% Población fallecida total'],
inplace = True,
axis = 1)
dfs_desacumulado.sort_values(by = "Día", inplace = True)
return dfs_desacumulado
def correct_names():
def read_population_dataset_custom(name = 'spain-communities-2020.csv... | r'% Población contagiada total', | random_line_split |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | (s: &str) -> Result<Self, Self::Err> {
bytes::from_hex(s).map(Bytes)
}
}
/// Stores the encoded `RuntimeMetadata` for the native side as opaque type.
#[derive(Encode, Decode, PartialEq, TypeInfo)]
pub struct OpaqueMetadata(Vec<u8>);
impl OpaqueMetadata {
/// Creates a new instance with the given metadata blob.
p... | from_str | identifier_name |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use sp_runtime_interface::pass_by::{PassByEnum, PassByInner};
use sp_std::{ops::Deref, prelude::*};
pub use sp_debug_derive::RuntimeDebug;
#[cfg(feature = "serde")]
pub use impl_serde::serialize as bytes;
#[cfg(feature = "full_crypto")]
pub mod hashing;
... | #[cfg(feature = "serde")]
pub use serde; | random_line_split |
lib.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
}
impl codec::WrapperTypeEncode for Bytes {}
impl codec::WrapperTypeDecode for Bytes {
type Wrapped = Vec<u8>;
}
#[cfg(feature = "std")]
impl sp_std::str::FromStr for Bytes {
type Err = bytes::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
bytes::from_hex(s).map(Bytes)
}
}
/// Stores the en... | {
&self.0[..]
} | identifier_body |
api.rs | //! This API contains all you will need to interface your
//! your bot algorithm with the GTPv2 protocol.
//! Your main task will be to implement the GoBot trait.
use std::str::FromStr;
use std::vec::Vec;
/// Contains all the possible errors your bot
/// may return to the library.
/// Be careful, any callback returni... | fn komi(&mut self, komi: f32) -> ();
/// Sets the board size.
/// Returns `Err(InvalidBoardSize)` if the size is not supported.
/// The protocol cannot handle board sizes > 25x25.
fn boardsize(&mut self, size: usize) -> Result<(), GTPError>;
/// Plays the provided move on the board.
/// Re... | /// Clears the board, can never fail.
fn clear_board(&mut self) -> ();
/// Sets the komi, can never fail, must accept absurd values. | random_line_split |
api.rs | //! This API contains all you will need to interface your
//! your bot algorithm with the GTPv2 protocol.
//! Your main task will be to implement the GoBot trait.
use std::str::FromStr;
use std::vec::Vec;
/// Contains all the possible errors your bot
/// may return to the library.
/// Be careful, any callback returni... | // eliminate 'I'
let number = u8::from_str(&text[1..]);
let mut y: u8 = 0;
match number {
Ok(num) => y = num,
_ => (),
}
if y == 0 || y > 25 {
return None;
}
Some(Vertex{x: x, y: y})
}
/// Returns a tuple of coordinates... |
x -= 1;
} | conditional_block |
api.rs | //! This API contains all you will need to interface your
//! your bot algorithm with the GTPv2 protocol.
//! Your main task will be to implement the GoBot trait.
use std::str::FromStr;
use std::vec::Vec;
/// Contains all the possible errors your bot
/// may return to the library.
/// Be careful, any callback returni... | (&self, status: StoneStatus) -> Result<Vec<Vertex>, GTPError> {
Err(GTPError::NotImplemented)
}
/// Computes the bot's calculation of the final score.
/// If it is a draw, float value must be 0 and colour is not important.
/// Can fail with èErr(CannotScore)`.
fn final_score(&self) -> Resul... | final_status_list | identifier_name |
my.rs | use std::{io, iter};
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
use std::ops::RangeFull;
use paths_builder::Path;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Pt {
... | {
pub moves: Vec<(i8, i8)>, // (dx, dy)
pub nowater: Vec<Pt>, // (x, y) sorted
pub noobstacles: Vec<Pt>, // (x, y) sorted
pub xmin: i32,
pub xmax: i32,
pub ymin: i32,
pub ymax: i32,
}
#[derive(Debug)]
pub struct Paths {
pub paths: HashMap... | Path | identifier_name |
my.rs | use std::{io, iter};
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
use std::ops::RangeFull;
use paths_builder::Path;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Pt {
... | pub struct Paths {
pub paths: HashMap<usize, HashMap<(i32, i32), Vec<Path>>>,
}
}
struct BallPaths {
count: usize,
ball: usize,
paths: Vec<(paths_builder::Path,usize)>
}
struct Main {
width : usize,
height: usize,
field : Vec<u8>,
holes : Vec<Pt>,
balls : Vec<(Pt, u8)>,... | pub ymax: i32,
}
#[derive(Debug)] | random_line_split |
my.rs | use std::{io, iter};
use std::collections::{HashSet, HashMap};
use std::iter::FromIterator;
use std::ops::RangeFull;
use paths_builder::Path;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Pt {
... |
for pt in path.noobstacles.iter().chain(path.nowater.iter()) {
if used_points.contains(pt) {
continue 'outer;
}
}
if is_leaf {
let mut s : Vec<(usize, Path)> = Vec::new();
s.push((paths.ball, path.cl... | {
continue;
} | conditional_block |
FireBehaviorForecaster.js | /**
* @file FireBehaviorForecaster.js provides site specific terrain, weather, and fire behavior
* for a 48-hour period.
* @copyright 2021 Systems for Environmental Management
* @author Collin D. Bevins, <cbevins@montana.com>
* @license MIT
*/
import { Sim } from '@cbevins/fire-behavior-simulator'
import moment fr... | (parms, wxArray) {
wxArray.forEach(wx => {
const input = {
fuel: parms.fuel,
curedHerb: 0.01 * parms.cured,
month: +(wx.date).substr(5, 2),
hour: +(wx.time).substr(0, 2),
elevDiff: parms.elevdiff,
aspect: parms.aspect,
slope: 0.01 * parms.slope,
... | addFireBehavior | identifier_name |
FireBehaviorForecaster.js | /**
* @file FireBehaviorForecaster.js provides site specific terrain, weather, and fire behavior
* for a 48-hour period.
* @copyright 2021 Systems for Environmental Management
* @author Collin D. Bevins, <cbevins@montana.com>
* @license MIT
*/
import { Sim } from '@cbevins/fire-behavior-simulator'
import moment fr... |
}
| {
// configure the time frame up to 6 hours back and 15 days out
const now = moment.utc()
parms.start = moment.utc(now).startOf('hour').toISOString() // "2019-03-20T14:09:50Z"
parms.end = moment.utc(now).add(48, 'hours').toISOString()
// First get elevation, slope, and aspect and add it to the parm... | identifier_body |
FireBehaviorForecaster.js | /**
* @file FireBehaviorForecaster.js provides site specific terrain, weather, and fire behavior
* for a 48-hour period.
* @copyright 2021 Systems for Environmental Management
* @author Collin D. Bevins, <cbevins@montana.com>
* @license MIT
*/
import { Sim } from '@cbevins/fire-behavior-simulator'
import moment fr... | else { // tomorrow.io
_wx = getTomorrow(parms.lat, parms.lon, parms.start, parms.end, parms.timezone)
}
// Run requests in parallel...
const esa = await _esa
const wx = await _wx
parms.elev = esa.elev
parms.slope = 100 * esa.slopeRatio
parms.aspect = esa.aspect
// Add fire beha... | {
_wx = getWeatherapi(parms.lat, parms.lon, 1, 'fire')
} | conditional_block |
FireBehaviorForecaster.js | /**
* @file FireBehaviorForecaster.js provides site specific terrain, weather, and fire behavior
* for a 48-hour period.
* @copyright 2021 Systems for Environmental Management
* @author Collin D. Bevins, <cbevins@montana.com>
* @license MIT
*/
import { Sim } from '@cbevins/fire-behavior-simulator'
import moment fr... | 'surface.primary.fuel.fire.heatPerUnitArea', // btu/ft2 |
'surface.primary.fuel.fire.reactionIntensity', // btu/ft2/min
'surface.fire.ellipse.axis.lengthToWidthRatio', // ratio
'surface.fire.ellipse.back.firelineIntensity', // Btu/ft/s
'surface.fire.ellipse.back.flameLength', // ft
'... | 'surface.primary.fuel.fire.heading.fromNorth', // degrees | random_line_split |
slack.go | package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/nlopes/slack"
)
// SlackClient is
type SlackClient struct {
client *slack.Client
verificationToken string
channelID string
}
type slackMsg struct {
text string
ts string
channel string
r... | {
params := &slack.GetConversationRepliesParameters{}
params.ChannelID = id
params.Timestamp = ts
params.Inclusive = true
params.Limit = 1
// get slack messages
msg, _, _, err := c.client.GetConversationReplies(params)
if err != nil {
log.Println("[Error] failed to get slack messages: ", err)
return nil, e... | identifier_body | |
slack.go | package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/nlopes/slack"
)
// SlackClient is
type SlackClient struct {
client *slack.Client
verificationToken string
channelID string
}
type slackMsg struct {
text string
ts string
channel string
r... | (id string, ts string) (*slackMsg, error) {
params := &slack.GetConversationRepliesParameters{}
params.ChannelID = id
params.Timestamp = ts
params.Inclusive = true
params.Limit = 1
// get slack messages
msg, _, _, err := c.client.GetConversationReplies(params)
if err != nil {
log.Println("[Error] failed to g... | getMessage | identifier_name |
slack.go | package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/nlopes/slack"
)
// SlackClient is
type SlackClient struct {
client *slack.Client
verificationToken string
channelID string
}
type slackMsg struct {
text string
ts string
channel string
r... |
return nil
}
// https://api.slack.com/methods/conversations.replies
func (c *SlackClient) getMessage(id string, ts string) (*slackMsg, error) {
params := &slack.GetConversationRepliesParameters{}
params.ChannelID = id
params.Timestamp = ts
params.Inclusive = true
params.Limit = 1
// get slack messages
msg, ... | {
log.Println("[Error] failed to post slack messages: ", err)
return err
} | conditional_block |
slack.go | package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/nlopes/slack"
)
// SlackClient is
type SlackClient struct {
client *slack.Client
verificationToken string
channelID string
}
type slackMsg struct {
text string
ts string
channel string
r... | "flag-sh": "English",
"flag-si": "Slovenian",
"flag-sj": "Norwegian",
"flag-sk": "Slovak",
"flag-sl": "English",
"flag-sm": "Italian",
"flag-sn": "French",
"flag-so": "Somali",
"flag-sr": "Dutch",
"flag-ss": "English",
"flag-st": "Portuguese",
"flag-sv": "Spanish",
"flag-sx": "Dutch",
"flag-sw": "Arabic",... | random_line_split | |
c01_mainChangeover.py | # --------CHANGE OVERS
######################################### 0 Intro #########################################
# Naming Convention: first letter of variable indicates the type
# a = array
# b = binary / boolean
# c = code, for .py files only
# d = dictionary
# f = float
# g = graph
# i = integer
# l = list
# lim ... |
#open file to track usage history
filePopulationHistory = open(os.path.join(glob.sPathToExcels, "90_populationHistory.txt"), "w", encoding="utf-8")
fileFitnessHistory_runs = open(os.path.join(glob.sPathToExcels, "91_fitnessRuns.txt"), "a", encoding="utf-8")
######################################### 2 GA SETUP #####... | dMaterialCO[row.materialRel] = row["timeCO"]
glob.lMaterialAtlas_0.append(row["materialAtlas"]) | conditional_block |
c01_mainChangeover.py | # --------CHANGE OVERS
######################################### 0 Intro #########################################
# Naming Convention: first letter of variable indicates the type
# a = array
# b = binary / boolean
# c = code, for .py files only
# d = dictionary
# f = float
# g = graph
# i = integer
# l = list
# lim ... | # append calculated fitness for new lowest level
lMinFitness_history.append(fMinFitness)
# create table and calculate selection probabilities
lFitness_sorted = gak.udf_sortByFitness(lFitness)
# initialize population arrays
lPopulation_new = []
lPopulation_new_names = []
dPopulation_new ={}
# select parents... | if lMinFitness[0] <= fMinFitness:
fMinFitness = lMinFitness[0]
| random_line_split |
lib.rs | // Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | (&self) -> Option<::syntax::util::small_vector::SmallVector<::std::gc::Gc<Item>>> {
Some(::syntax::util::small_vector::SmallVector::many(self.content.clone()))
}
}
// handler for generate_gl_bindings!
fn macro_handler(ecx: &mut ExtCtxt, span: Span, token_tree: &[TokenTree]) -> Box<MacResult+'static> {
... | make_items | identifier_name |
lib.rs | // Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | Path::new(ecx.codemap().span_to_filename(span)).display().to_string(), content);
// getting all the items defined by the bindings
let mut items = Vec::new();
loop {
match parser.parse_item_with_outer_attributes() {
None => break,
Some(i) => items.push(i)
}
... | return DummyResult::any(span)
}
};
let mut parser = ::syntax::parse::new_parser_from_source_str(ecx.parse_sess(), ecx.cfg(), | random_line_split |
lib.rs | // Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
fn parse_macro_arguments(ecx: &mut ExtCtxt, span: Span, tts: &[syntax::ast::TokenTree])
-> Option<(String, String, String, String, Vec<String>)>
{
// getting parameters list
let values = match get_exprs_from_tts(ecx, span, tts) {
Some(v) => v,
None => return None
};... | {
// getting the arguments from the macro
let (api, profile, version, generator, extensions) = match parse_macro_arguments(ecx, span.clone(), token_tree) {
Some(t) => t,
None => return DummyResult::any(span)
};
let (ns, source) = match api.as_slice() {
"gl" => (Gl, khronos_api:... | identifier_body |
mdx15_print_gerber.py | #
# Print a gerber file to the MDX-15, optionally setting the home position
#
# Note: Uses RawFileToPrinter.exe as found at http://www.columbia.edu/~em36/windowsrawprint.html
# Note: Might work with other Roland Modela Models (MDX-20), but I don't have access to such machines, so I cannot test.
#
#
# MIT License
#
# Co... |
def run(self):
print('If the green light next to the VIEW button is lit, please press the VIEW button.')
print('Usage:')
print('\th - send to home')
print('\tz - Set Z zero')
print('\tZ - send to zero')
print('\twasd - move on the XY plane (+shift for small increments)')
print('\tup/down - move in ... | if self.x < 0.0 : self.x = 0.0
if self.x > self.X_MAX : self.x = self.X_MAX
if self.y < 0.0 : self.y = 0.0
if self.y > self.Y_MAX : self.y = self.Y_MAX
#print('Moving to {:.0f},{:.0f},{:.0f}'.format(self.x,self.y,self.z))
spindle = '1' if self.spindleEnabled else '0'
# The esoteric syntax was borrowed fro... | identifier_body |
mdx15_print_gerber.py | #
# Print a gerber file to the MDX-15, optionally setting the home position
#
# Note: Uses RawFileToPrinter.exe as found at http://www.columbia.edu/~em36/windowsrawprint.html
# Note: Might work with other Roland Modela Models (MDX-20), but I don't have access to such machines, so I cannot test.
#
#
# MIT License
#
# Co... | self.sendCommand('^IN;!MC0;H') # clear errors, disable spindle, return home
self.z_offset = self.Z_DEFAULT_OFFSET
self.sendCommand('^DF;!ZO{:.3f};;'.format(self.z_offset)) # set z zero half way
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.spindleEnabled = False
self.sendMoveCommand(True)
self.xy_zero ... | random_line_split | |
mdx15_print_gerber.py | #
# Print a gerber file to the MDX-15, optionally setting the home position
#
# Note: Uses RawFileToPrinter.exe as found at http://www.columbia.edu/~em36/windowsrawprint.html
# Note: Might work with other Roland Modela Models (MDX-20), but I don't have access to such machines, so I cannot test.
#
#
# MIT License
#
# Co... |
# Start microscope feed if requested
mic = None
if options.microscope != False :
mic = MicroscopeFeed( int(options.microscope) )
mic.startLoop()
#msvcrt.getwch()
#print( mic.getFocusValue() )
try:
# Manually set zero and microscope set points
x_offset = 0.0
y_offset = 0.0
modelaZeroControl = None... | import subprocess
shelloutput = subprocess.check_output('powershell -Command "(Get-WmiObject Win32_Printer -Filter \\"Name=\'{}\'\\").PortName"'.format(options.printerName))
if len(shelloutput)>0 :
try :
serialport = shelloutput.decode('utf-8').split(':')[0]
print( 'Found {} printer driver ({})'.format(o... | conditional_block |
mdx15_print_gerber.py | #
# Print a gerber file to the MDX-15, optionally setting the home position
#
# Note: Uses RawFileToPrinter.exe as found at http://www.columbia.edu/~em36/windowsrawprint.html
# Note: Might work with other Roland Modela Models (MDX-20), but I don't have access to such machines, so I cannot test.
#
#
# MIT License
#
# Co... | :
# stateful variables
inputConversionFactor = 1.0 # mm units
X = 0.0
Y = 0.0
Z = 0.0
speedmode = None
feedrate = 0.0
isFirstCommand = True
offset_x = 0.0
offset_y = 0.0
feedspeedfactor = 1.0
# Backlash compensation related
backlashX = 0
backlashY = 0
backlashZ = 0
last_x = 0
last_y = 0
last_z = 0
... | GCode2RmlConverter | identifier_name |
core.go | // Copyright 2012 Google Inc. All Rights Reserved.
//
// 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... | () (uint32, error) {
ma.lock.Lock()
defer ma.lock.Unlock()
if len(ma.marks) == 0 {
return 0, errors.New("allocator exhausted")
}
mark := ma.marks[0]
ma.marks = ma.marks[1:]
return mark, nil
}
// put returns the specified mark to the mark allocator.
func (ma *markAllocator) put(mark uint32) {
ma.lock.Lock()
... | get | identifier_name |
core.go | // Copyright 2012 Google Inc. All Rights Reserved.
//
// 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... | else {
e.haManager.disable()
}
node, err := e.thisNode()
if err != nil {
log.Errorf("Manager failed to identify local node: %v", err)
continue
}
if !node.VserversEnabled {
e.shutdownVservers()
e.deleteVLANs()
continue
}
// Process new cluster configuration.
e.updateVLA... | {
e.haManager.enable()
} | conditional_block |
core.go | // Copyright 2012 Google Inc. All Rights Reserved.
//
// 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... |
// haConfig returns the HAConfig for an engine.
func (e *Engine) haConfig() (*seesaw.HAConfig, error) {
n, err := e.thisNode()
if err != nil {
return nil, err
}
// TODO(jsing): This does not allow for IPv6-only operation.
return &seesaw.HAConfig{
Enabled: n.State != spb.HaState_DISABLED,
LocalAddr: e.c... | {
select {
case e.haManager.statusChan <- status:
default:
return fmt.Errorf("status channel if full")
}
return nil
} | identifier_body |
core.go | // Copyright 2012 Google Inc. All Rights Reserved.
//
// 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... | log.Infof("Seesaw Engine starting for %s", e.config.ClusterName)
e.initNetwork()
n, err := config.NewNotifier(e.config)
if err != nil {
log.Fatalf("config.NewNotifier() failed: %v", err)
}
e.notifier = n
if e.config.AnycastEnabled {
go e.bgpManager.run()
}
go e.hcManager.run()
go e.syncClient.run()
g... | random_line_split | |
lib.rs | #![deny(warnings)]
pub mod corgi;
pub mod dict;
#[cfg(test)]
pub mod tests;
use crate::corgi::{decode, encode, Corgi, CorgiDTO, CorgiId, CorgiKey, Rarity};
use crate::dict::Dict;
use near_env::near_envlog;
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
collections::UnorderedMap,
env,
... | /// Internal method to transfer a corgi.
fn move_corgi(
&mut self,
key: CorgiKey,
id: CorgiId,
old_owner: AccountId,
new_owner: AccountId,
mut corgi: Corgi,
) {
self.delete_corgi_from(id, old_owner.clone());
corgi.owner = new_owner;
co... | let (key, mut bids, auction_ends) = self.get_auction(&token_id);
let corgi = {
let corgi = self.corgis.get(&key);
assert!(corgi.is_some());
corgi.unwrap()
};
let owner = corgi.owner.clone();
let end_auction = |it, bidder, price| {
i... | identifier_body |
lib.rs | #![deny(warnings)]
pub mod corgi;
pub mod dict;
#[cfg(test)]
pub mod tests;
use crate::corgi::{decode, encode, Corgi, CorgiDTO, CorgiId, CorgiKey, Rarity};
use crate::dict::Dict;
use near_env::near_envlog;
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
collections::UnorderedMap,
env,
... | }
fn get_collection_key(prefix: &str, mut key: String) -> Vec<u8> {
key.insert_str(0, prefix);
key.as_bytes().to_vec()
} | random_line_split | |
lib.rs | #![deny(warnings)]
pub mod corgi;
pub mod dict;
#[cfg(test)]
pub mod tests;
use crate::corgi::{decode, encode, Corgi, CorgiDTO, CorgiId, CorgiKey, Rarity};
use crate::dict::Dict;
use near_env::near_envlog;
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
collections::UnorderedMap,
env,
... | -> Self {
env::log(format!("init v{}", env!("CARGO_PKG_VERSION")).as_bytes());
Self {
corgis: Dict::new(CORGIS.to_vec()),
corgis_by_owner: UnorderedMap::new(CORGIS_BY_OWNER.to_vec()),
auctions: UnorderedMap::new(AUCTIONS.to_vec()),
}
}
}
#[near_bindgen]
... | fault() | identifier_name |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... | if(email === '') {
if(!message) {
message = 'Email không được để trống'
} else {
message += '\nEmail không được để trống';
}
}
if (user.memberInfo.member.facebook.name
&& objUpdate.name.trim() === _.get(user, 'memberInfo.member.name', '')
... | message += 'Họ và tên không được để trống';
} | random_line_split |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... |
updateProfile(objUpdate) {
var {dispatch,user} = this.props;
dispatch(UserActions_MiddleWare.updateProfile(objUpdate))
.then(()=>{
globalVariableManager.rootView.showToast('Cập nhật thông tin thành công');
dispatch(UserActions_MiddleWare.get())
.then(() => {
if(... | {
super(props);
let {user} = this.props;
this.state = {};
this.handleUpdateProfile = this.handleUpdateProfile.bind(this);
this.userInfo={
Username: _.get(user, 'memberInfo.member.name', ''),
email: _.get(user, 'memberInfo.member.email', ''),
phone: _.get(user, 'mem... | identifier_body |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... | (objUpdate) {
var {dispatch,user} = this.props;
dispatch(UserActions_MiddleWare.updateProfile(objUpdate))
.then(()=>{
globalVariableManager.rootView.showToast('Cập nhật thông tin thành công');
dispatch(UserActions_MiddleWare.get())
.then(() => {
if(this.forceUpdate) {... | updateProfile | identifier_name |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... | if(!message) {
message = 'Email không được để trống'
} else {
message += '\nEmail không được để trống';
}
}
if (user.memberInfo.member.facebook.name
&& objUpdate.name.trim() === _.get(user, 'memberInfo.member.name', '')
&& objUpdate.email.trim() ==... | e += 'Họ và tên không được để trống';
}
if(email === '') {
| conditional_block |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... |
impl<V> Confusion<V> where V: ToString {
fn write_accuracies(&self, mut w: impl Write) -> Result<(), Error> {
for (idx, item) in self.numberer.idx2val.iter().map(V::to_string).enumerate() {
let row = &self.confusion[idx];
let correct = row[idx];
let total = row.iter().s... | } | random_line_split |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... |
Ok(())
}
static DEFAULT_CLAP_SETTINGS: &[AppSettings] = &[
AppSettings::DontCollapseArgsInUsage,
AppSettings::UnifiedHelpMessage,
];
// Argument constants
static VALIDATION: &str = "VALIDATION";
static PREDICTION: &str = "PREDICTION";
static DEPREL_CONFUSION: &str = "deprel_confusion";
static DEPREL_ACCU... | {
let out = File::create(file_name).unwrap();
let mut writer = BufWriter::new(out);
distance_confusion.write_accuracies(&mut writer).unwrap();
} | conditional_block |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... | <V>{
val2idx: HashMap<V, usize>,
idx2val: Vec<V>,
}
impl<V> Numberer<V> where V: Clone + Hash + Eq {
pub fn new() -> Self {
Numberer {
val2idx: HashMap::new(),
idx2val: Vec::new(),
}
}
fn number<S>(&mut self, val: S) -> usize where S: Into<V> {
let v... | Numberer | identifier_name |
main.rs | use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt;
use std::hash::Hash;
use std::io::Write;
use clap::{App, AppSettings, Arg, ArgMatches};
use conllx::io::{Reader, ReadSentence};
use conllx::token::Token;
use failure::{Error};
use itertools::Iter... |
fn number<S>(&mut self, val: S) -> usize where S: Into<V> {
let val = val.into();
if let Some(idx) = self.val2idx.get(&val) {
*idx
} else {
let n_vals = self.val2idx.len();
self.val2idx.insert(val.clone(), n_vals);
self.idx2val.push(val);
... | {
Numberer {
val2idx: HashMap::new(),
idx2val: Vec::new(),
}
} | identifier_body |
bundle.js | "use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _toConsumableArray(arr) { if (Array.i... |
if ($('body').hasClass('logged')) {
$.each(openedTasksArray, function (i, item) {
$('.item-event[data-taskID=' + item + ']').removeClass('disabled');
});
}
$('.item-event').on('click', function (e) {
var logged = $('body').hasClass('logged');
var disabled = ... | {
openedTasksArray = JSON.parse(cookieTasks);
} | conditional_block |
bundle.js | "use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _toConsumableArray(arr) { if (Array.i... | if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps... | random_line_split | |
bundle.js | "use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _toConsumableArray(arr) { if (Array.i... | (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
var expires = "expires=" + d.toUTCString();
document.cookie = ... | _classCallCheck | identifier_name |
bundle.js | "use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _toConsumableArray(arr) { if (Array.i... |
(function () {
var $window = $(window);
var $document = $(document);
var $body = $('body');
var $html = $('html');
var Android = navigator.userAgent.match(/Android/i) && !navigator.userAgent.match(/(Windows\sPhone)/i) ? true : false;
var App = function App() {
var _this = this;
_classCallCheck(... | {
if (mq === 'desktop') {
firstFunc();
} else if (mq === 'tablet') {
otherFunc();
} else if (mq === 'mobile') {
secFunc();
}
// console.log('staticInit:' + mq);
} | identifier_body |
session.rs | use crate::{
auto_remote_syscalls::{AutoRemoteSyscalls, AutoRestoreMem},
emu_fs::EmuFs,
kernel_abi::{
syscall_number_for_close, syscall_number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_F... |
fn on_create_task_common<S: Session>(sess: &S, t: TaskSharedPtr) {
let rec_tid = t.rec_tid();
sess.task_map.borrow_mut().insert(rec_tid, t);
}
| {
let start = m.map.start();
let data_size: usize;
let num_byes_addr =
RemotePtr::<u32>::cast(remote_ptr_field!(start, syscallbuf_hdr, num_rec_bytes));
if read_val_mem(
clone_leader,
remote_ptr_field!(start, syscallbuf_hdr, locked),
None,
) != 0u8
{
// The... | identifier_body |
session.rs | use crate::{
auto_remote_syscalls::{AutoRemoteSyscalls, AutoRestoreMem},
emu_fs::EmuFs,
kernel_abi::{
syscall_number_for_close, syscall_number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_F... | else if m.local_addr.is_some() {
ed_assert_eq!(
clone_leader,
m.map.start(),
AddressSpace::preload_thread_locals_start()
);
} else if m.recorded_map.flags().contains(M... | {
group
.captured_memory
.push((m.map.start(), capture_syscallbuf(&m, &**clone_leader)));
} | conditional_block |
session.rs | use crate::{
auto_remote_syscalls::{AutoRemoteSyscalls, AutoRestoreMem},
emu_fs::EmuFs,
kernel_abi::{
syscall_number_for_close, syscall_number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_F... | (&self, vmuid: AddressSpaceUid) -> Option<AddressSpaceSharedPtr> {
self.finish_initializing();
// If the weak ptr was found, we _must_ be able to upgrade it!;
self.vm_map().get(&vmuid).map(|a| a.upgrade().unwrap())
}
/// Return a copy of `tg` with the same mappings.
/// NOTE: Called... | find_address_space | identifier_name |
session.rs | use crate::{
auto_remote_syscalls::{AutoRemoteSyscalls, AutoRestoreMem},
emu_fs::EmuFs,
kernel_abi::{
syscall_number_for_close, syscall_number_for_munmap, syscall_number_for_openat,
SupportedArch,
},
log::LogDebug,
preload_interface::syscallbuf_hdr,
rd::RD_RESERVED_ROOT_DIR_F... | for k in shared_maps_to_clone {
remap_shared_mmap(&mut remote, emu_fs, dest_emu_fs, k);
}
for t in vm.task_set().iter() {
if Rc::ptr_eq(&group_leader, &t) {
continue;
}
... | shared_maps_to_clone.push(k);
}
}
// Do this in a separate loop to avoid iteration invalidation issues | random_line_split |
data.js | (function () {
"use strict";
var __DOMAIN__ = 'http://laiwang.com';
var __API_DOMAIN__ = 'http://api.laiwang.com/v1';
var __LENGTH__ = 25;
// These three strings encode placeholder images. You will want to set the backgroundImage property in your real data to be URLs to images.
var ... | beforeSend: function (jqXHR, settings) {
if (typeof this.data === 'string') {
this.data = this.data.replace(/%[0-1][0-9a-f]/g, '%20');
this.data += '&access_token=' + localStorage['access_token'];
} else if (typeof this.data === 'object') {
... | identifier_name | |
data.js | (function () {
"use strict";
var __DOMAIN__ = 'http://laiwang.com';
var __API_DOMAIN__ = 'http://api.laiwang.com/v1';
var __LENGTH__ = 25;
// These three strings encode placeholder images. You will want to set the backgroundImage property in your real data to be URLs to images.
var ... | data.forEach(function (item) {//to do rebuild
// Each of these sample items should have a reference to a particular group.
item.group = Groups[0];//通过上面的ajax请求获取到的都是laiwang主墙信息,所以取Groups数组中的第0项:laiwang
//item.key = item.id;
item.itemPubl... | gi, '<br/>');
}
| conditional_block |
data.js | (function () {
"use strict";
var __DOMAIN__ = 'http://laiwang.com';
var __API_DOMAIN__ = 'http://api.laiwang.com/v1';
var __LENGTH__ = 25;
// These three strings encode placeholder images. You will want to set the backgroundImage property in your real data to be URLs to images.
var ... | I_DOMAIN__ + '/relationship/friend/list',
type: 'GET',
data: postData,
_success: function (data) {
data = data.values;
//如果取得的值为空
if (data.length === 0) {
return;
}
data.forEach(functi... | ost/incoming/list',
// group: '/feed/post/circle/list'
//};
var postData = {
'cursor': 0,
'size': __LENGTH__,
'access_token': localStorage['access_token']
};
$.ajax({
global: false,
url: __API_DOMAIN__ + '/feed/post/m... | identifier_body |
data.js | (function () {
"use strict";
|
// These three strings encode placeholder images. You will want to set the backgroundImage property in your real data to be URLs to images.
var lightGray = "../images/item_bac01.jpg"; //"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZc... | var __DOMAIN__ = 'http://laiwang.com';
var __API_DOMAIN__ = 'http://api.laiwang.com/v1';
var __LENGTH__ = 25;
| random_line_split |
integration.go | //
// Author:: Salim Afiune Maya (<afiune@lacework.net>)
// Copyright:: Copyright 2020, Lacework Inc.
// License:: Apache License, Version 2.0
//
// 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... | out[key] = s
} else {
deepMap := deepKeyValueExtract(value)
for deepK, deepV := range deepMap {
out[deepK] = deepV
}
}
}
return out
} | for key, value := range m {
if s, ok := value.(string); ok { | random_line_split |
integration.go | //
// Author:: Salim Afiune Maya (<afiune@lacework.net>)
// Copyright:: Copyright 2020, Lacework Inc.
// License:: Apache License, Version 2.0
//
// 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... |
func deepKeyValueExtract(v interface{}) map[string]string {
out := map[string]string{}
m, ok := v.(map[string]interface{})
if !ok {
return out
}
for key, value := range m {
if s, ok := value.(string); ok {
out[key] = s
} else {
deepMap := deepKeyValueExtract(value)
for deepK, deepV := range deep... | {
switch raw.Type {
case api.GcpCfgIntegration.String(),
api.GcpAuditLogIntegration.String():
var iData api.GcpIntegrationData
err := mapstructure.Decode(raw.Data, &iData)
if err != nil {
cli.Log.Debugw("unable to decode integration data",
"integration_type", raw.Type,
"raw_data", raw.Data,
"... | identifier_body |
integration.go | //
// Author:: Salim Afiune Maya (<afiune@lacework.net>)
// Copyright:: Copyright 2020, Lacework Inc.
// License:: Apache License, Version 2.0
//
// 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... |
return out
}
| {
if s, ok := value.(string); ok {
out[key] = s
} else {
deepMap := deepKeyValueExtract(value)
for deepK, deepV := range deepMap {
out[deepK] = deepV
}
}
} | conditional_block |
integration.go | //
// Author:: Salim Afiune Maya (<afiune@lacework.net>)
// Copyright:: Copyright 2020, Lacework Inc.
// License:: Apache License, Version 2.0
//
// 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... | (lacework *api.Client) error {
var (
integration = ""
prompt = &survey.Select{
Message: "Choose an integration type to create: ",
Options: []string{
"Docker Hub",
"AWS Config",
"AWS CloudTrail",
"GCP Config",
"GCP Audit Log",
"Azure Config",
"Azure Activity Log",
//"Docke... | promptCreateIntegration | identifier_name |
validation_host.rs | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any... | (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "ValidationHostMemory")
}
}
impl std::ops::Deref for ValidationHostMemory {
type Target = SharedMem;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ValidationHostMemory {
fn deref_mut(&mut self) -> &mut Self::Ta... | fmt | identifier_name |
validation_host.rs | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any... | if validation_code.len() > MAX_CODE_MEM {
return Err(ValidationError::InvalidCandidate(InvalidCandidate::CodeTooLarge(validation_code.len())));
}
// First, check if need to spawn the child process
self.start_worker(binary, args)?;
let memory = self.memory.as_mut()
.expect("memory is always `Some` after ... | validation_code: &[u8],
params: ValidationParams,
binary: &PathBuf,
args: &[&str],
) -> Result<ValidationResult, ValidationError> { | random_line_split |
validation_host.rs | // Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any... |
}
{
debug!("{} Reading results", self.id);
let data: &[u8] = &**memory.wlock_as_slice(0)
.map_err(|e| ValidationError::Internal(e.into()))?;
let (header_buf, _) = data.split_at(MAX_VALIDATION_RESULT_HEADER_MEM);
let mut header_buf: &[u8] = header_buf;
let header = ValidationResultHeader::decode... | {} | conditional_block |
auth.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/api/auth.proto
package serviceconfig // import "google.golang.org/genproto/googleapis/api/serviceconfig"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not other... |
func (m *AuthenticationRule) XXX_DiscardUnknown() {
xxx_messageInfo_AuthenticationRule.DiscardUnknown(m)
}
var xxx_messageInfo_AuthenticationRule proto.InternalMessageInfo
func (m *AuthenticationRule) GetSelector() string {
if m != nil {
return m.Selector
}
return ""
}
func (m *AuthenticationRule) GetOauth() ... | {
return xxx_messageInfo_AuthenticationRule.Size(m)
} | identifier_body |
auth.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/api/auth.proto
package serviceconfig // import "google.golang.org/genproto/googleapis/api/serviceconfig"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not other... |
return nil
}
func (m *Authentication) GetProviders() []*AuthProvider {
if m != nil {
return m.Providers
}
return nil
}
// Authentication rules for the service.
//
// By default, if a method has any authentication requirements, every request
// must include a valid credential matching one of the requirements.
/... | {
return m.Rules
} | conditional_block |
auth.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/api/auth.proto
package serviceconfig // import "google.golang.org/genproto/googleapis/api/serviceconfig"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not other... | //
// The list of JWT
// [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
// that are allowed to access. A JWT containing any of these audiences will
// be accepted. When this setting is absent, only JWTs with audience
// "https://[Service_name][google.api.Service.name]/[... | ProviderId string `protobuf:"bytes,1,opt,name=provider_id,json=providerId,proto3" json:"provider_id,omitempty"`
// NOTE: This will be deprecated soon, once AuthProvider.audiences is
// implemented and accepted in all the runtime components. | random_line_split |
auth.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/api/auth.proto
package serviceconfig // import "google.golang.org/genproto/googleapis/api/serviceconfig"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not other... | (b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_AuthProvider.Marshal(b, m, deterministic)
}
func (dst *AuthProvider) XXX_Merge(src proto.Message) {
xxx_messageInfo_AuthProvider.Merge(dst, src)
}
func (m *AuthProvider) XXX_Size() int {
return xxx_messageInfo_AuthProvider.Size(m)
}
func (m *Aut... | XXX_Marshal | identifier_name |
info.py | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from __future__ import print_function
import inspect
import textwrap
from six.moves import zip_longest
import llnl.util... |
def default(self, v):
s = "on" if v.default is True else "off"
if not isinstance(v.default, bool):
s = v.default
return s
@property
def lines(self):
if not self.variants:
yield " None"
else:
yield " " + self.fmt % self.head... | self.variants = variants
self.headers = ("Name [Default]", "When", "Allowed values", "Description")
# Formats
fmt_name = "{0} [{1}]"
# Initialize column widths with the length of the
# corresponding headers, as they cannot be shorter
# than that
self.column_widt... | identifier_body |
info.py | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from __future__ import print_function
import inspect
import textwrap
from six.moves import zip_longest
import llnl.util... | (self, v):
s = "on" if v.default is True else "off"
if not isinstance(v.default, bool):
s = v.default
return s
@property
def lines(self):
if not self.variants:
yield " None"
else:
yield " " + self.fmt % self.headers
u... | default | identifier_name |
info.py | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from __future__ import print_function
import inspect
import textwrap
from six.moves import zip_longest
import llnl.util... |
color.cprint(section_title("Homepage: ") + pkg.homepage)
# Now output optional information in expected order
sections = [
(args.all or args.maintainers, print_maintainers),
(args.all or args.detectable, print_detectable),
(args.all or args.tags, print_tags),
(args.all or n... | color.cprint(" None") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.