hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
2b03c71f1fa0572827c99ff87100d7f1e086f110
941
sql
SQL
schema.sql
ide-an/tootexporter
6fc232303780894140f012d155fc06fd4a445ed1
[ "MIT" ]
1
2017-12-23T16:37:34.000Z
2017-12-23T16:37:34.000Z
schema.sql
ide-an/tootexporter
6fc232303780894140f012d155fc06fd4a445ed1
[ "MIT" ]
1
2021-06-01T21:40:04.000Z
2021-06-01T21:40:04.000Z
schema.sql
ide-an/tootexporter
6fc232303780894140f012d155fc06fd4a445ed1
[ "MIT" ]
null
null
null
create table users ( id bigserial not null, access_token varchar(255), mastodon_id bigint, created_at timestamp not null, updated_at timestamp not null, constraint pk_users primary key (id)) ; create unique index idx_users_mastodon_id on users (mastodon_id); create table snapshots ( id bigserial not null, owner bigint, snap_type varchar(16), -- toot or fav status varchar(16), -- wait, doing, done, fail bucket varchar(255), -- AWS S3 bucket key varchar(255), -- AWS S3 key created_at timestamp not null, updated_at timestamp not null, constraint pk_snapshots primary key (id)) ; alter table snapshots add constraint fk_snapshots_owner foreign key (owner) references users (id);
40.913043
98
0.568544
1a6b424be4bcf4853505ce2d9e68268f8bc06dd5
59,076
py
Python
src/models/infection_model.py
MOCOS-COVID19/modelling-ncov2019
c47a2c980713da970b67db851a95eb68727517a9
[ "MIT" ]
7
2020-04-02T15:23:28.000Z
2021-11-28T16:32:46.000Z
src/models/infection_model.py
MOCOS-COVID19/modelling-ncov2019
c47a2c980713da970b67db851a95eb68727517a9
[ "MIT" ]
19
2020-03-17T08:46:06.000Z
2020-10-13T07:58:27.000Z
src/models/infection_model.py
eMaerthin/modelling-ncov2019
c47a2c980713da970b67db851a95eb68727517a9
[ "MIT" ]
5
2020-03-13T20:32:39.000Z
2020-08-24T18:40:01.000Z
""" This is mostly based on references/infection_alg.pdf """ import ast from functools import (lru_cache, partial) import json import logging import mocos_helper #import random import time from collections import defaultdict import pickle import psutil from shutil import copyfile from math import log from git import Repo import pandas as pd import scipy.optimize import scipy.stats from src.models.schemas import * from src.models.defaults import * from src.models.states_and_functions import * from src.visualization.visualize import Visualize import click from dotenv import find_dotenv, load_dotenv from queue import (PriorityQueue) q = PriorityQueue() class InfectionModel: def __init__(self, params_path: str, df_individuals_path: str, df_households_path: str = '') -> None: self.params_path = params_path self.df_individuals_path = df_individuals_path self.df_households_path = df_households_path logger.info('Loading params...') self._params = dict() with open(params_path, 'r') as params_file: params = json.loads( params_file.read() ) # TODO: check whether this should be moved to different place logger.info('Parsing params...') for key, schema in infection_model_schemas.items(): self._params[key] = schema.validate(params.get(key, defaults[key])) default_household_input_path = os.path.join(self._params[OUTPUT_ROOT_DIR], self._params[EXPERIMENT_ID], 'input_df_households.csv') # TODO: ensure households are valid! if df_households_path == '': self.df_households_path = default_household_input_path self._global_time = None self._max_time = None self._vis = None self._max_time_offset = 0.0 self._expected_case_severity = None self._df_individuals = None self._df_households = None #self._individuals_gender = None self._individuals_age = None self._individuals_household_id = None self._individuals_indices = None self._households_capacities = None self._households_inhabitants = None self._init_for_stats = None self._affected_people = 0 self._active_people = 0 self._quarantined_people = 0 self._detected_people = 0 self._immune_people = 0 self._deaths = 0 self._icu_needed = 0 self._disable_friendship_kernel = False self._set_up_data_frames() self._infection_status = None self._detection_status = None self._quarantine_status = None self._expected_case_severity = None if self._params[REUSE_EXPECTED_CASE_SEVERITIES]: self._expected_case_severity = self.draw_expected_case_severity() self._infections_dict = None self._progression_times_dict = None t0_f, t0_args, t0_kwargs = self.setup_random_distribution(T0) self.rv_t0 = lambda: t0_f(*t0_args, **t0_kwargs) t1_f, t1_args, t1_kwargs = self.setup_random_distribution(T1) self.rv_t1 = lambda: t1_f(*t1_args, **t1_kwargs) t2_f, t2_args, t2_kwargs = self.setup_random_distribution(T2) self.rv_t2 = lambda: t2_f(*t2_args, **t2_kwargs) tdeath_f, tdeath_args, tdeath_kwargs = self.setup_random_distribution(TDEATH) self.rv_tdeath = lambda: tdeath_f(*tdeath_args, **tdeath_kwargs) # TODO: This should be refactored self.fear_fun = dict() self.fear_weights_detected = dict() self.fear_weights_deaths = dict() self.fear_scale = dict() self.fear_loc = dict() self.fear_limit_value = dict() self.serial_intervals = [] self.band_time = None self._last_affected = None self._per_day_increases = {} self._disable_constant_age_kernel = False self._constant_age_helper_age_dict = {} self._constant_age_individuals = defaultdict(list) self._setup_constant_age_kernel() def _setup_constant_age_kernel(self): if self._params[CONSTANT_AGE_SETUP] is None: self._disable_constant_age_kernel = True return if isinstance(self._params[CONSTANT_AGE_SETUP][AGE], int): self._constant_age_helper_age_dict[self._params[CONSTANT_AGE_SETUP][AGE]] = 0 else: if self._params[CONSTANT_AGE_SETUP][INTER_AGE_CONTACTS]: # so all ages specified can be mixed for age in self._params[CONSTANT_AGE_SETUP][AGE]: self._constant_age_helper_age_dict[age] = 0 else: for i, age in enumerate(self._params[CONSTANT_AGE_SETUP][AGE]): self._constant_age_helper_age_dict[age] = i for age, individual_list_key in self._constant_age_helper_age_dict.items(): self._constant_age_individuals[individual_list_key].extend([ k for k, v in self._individuals_age_dct.items() if v==age ]) def get_detection_status_(self, person_id): return self._detection_status.get(person_id, default_detection_status) def get_quarantine_status_(self, person_id): return self._quarantine_status.get(person_id, default_quarantine_status) def get_infection_status(self, person_id): return self._infection_status.get(person_id, InfectionStatus.Healthy.value) @staticmethod def parse_random_seed(random_seed): mocos_helper.seed(random_seed) def _set_up_data_frames(self) -> None: """ The purpose of this method is to set up two dataframes. One is self._df_individuals that stores features for the population Second is self._df_households that stores list of people idx per household building df_households is time consuming, therefore we try to reuse previously computed df_households :return: """ logger.info('Set up data frames: Reading population csv...') self._df_individuals = pd.read_csv(self.df_individuals_path) self._df_individuals.index = self._df_individuals.idx self._individuals_age = self._df_individuals[AGE].values self._individuals_age_dct = self._df_individuals[AGE].to_dict() self._individuals_gender_dct = self._df_individuals[GENDER].to_dict() self._individuals_household_id = self._df_individuals[HOUSEHOLD_ID].to_dict() self._individuals_indices = self._df_individuals.index.values if SOCIAL_COMPETENCE in self._df_individuals.columns: if self._params[TRANSMISSION_PROBABILITIES][FRIENDSHIP] == 0: logger.info('Friendship = 0.0 - Disable friendship kernel...') self._disable_friendship_kernel = True else: logger.info('Set up data frames: Social competence and loading social activity sampler...') self._social_activity_scores = self._df_individuals[SOCIAL_COMPETENCE].to_dict() self._social_activity_sampler = mocos_helper.AgeDependentFriendSampler( self._individuals_indices, self._individuals_age, self._df_individuals[GENDER].values, self._df_individuals[SOCIAL_COMPETENCE].values ) self._disable_friendship_kernel = False else: logger.info('Social competence missing - Disable friendship kernel...') self._disable_friendship_kernel = True logger.info('Set up data frames: Building households df...') if os.path.exists(self.df_households_path): self._df_households = pd.read_csv(self.df_households_path, index_col=HOUSEHOLD_ID, converters={ID: ast.literal_eval}) else: self._df_households = pd.DataFrame({ID: self._df_individuals.groupby(HOUSEHOLD_ID)[ID].apply(list)}) os.makedirs(os.path.dirname(self.df_households_path), exist_ok=True) self._df_households.to_csv(self.df_households_path) self._df_households[CAPACITY] = self._df_households[ID].apply(lambda x: len(x)) d = self._df_households.to_dict() self._households_inhabitants = d[ID] #self._df_households[ID] self._households_capacities = d[CAPACITY] #self._df_households[CAPACITY] if not self._params[LOG_OUTPUTS]: self._df_households = None self._df_individuals = None @staticmethod def append_event(event: Event) -> None: q.put(event) def _fill_queue_based_on_auxiliary_functions(self) -> None: # TODO: THIS IS NOT WORKING WHEN CAP = INF, let's fix it # (one possible way to fix it: generate say first N events and a followup "filling EVENT" # on time T(N) of N-th event - at T(N) generate N more events and enqueue next portion. # Alternatively add just one event of type AUXILIARY_FUNCTION/IMPORT_INTENSITY # that will then draw time of next event of that type """ The purpose of this method is to mark some people of the population as sick according to provided function. Possible functions: see possible values of ImportIntensityFunctions enum Outcome of the function can be adjusted by overriding default parameters: multiplier, rate, cap, infectious_probability. :return: """ def _generate_event_times(func, rate, multiplier, cap, root_buffer=100, root_guess=0) -> list: """ Here a naive way of generating event times is proposed. The idea is to generate N events :param func: currently two functions are supported: exponential a*exp(r*t) and polynomial a*r^t :param rate: a parameter that is making the slope more steep :param multiplier: a parameter that scales the time down :param cap: the maximum amount of cases generated and added to queue list :param root_buffer: one-directional range to find roots in :param root_guess: guess on first solution (i=1) :return: """ root_min = root_guess - root_buffer root_max = root_guess + root_buffer time_events_ = [] def bisect_fun(x, integer): return func(x, rate=rate, multiplier=multiplier) - integer for i in range(1, 1 + cap): bisect_fun = partial(bisect_fun, integer=i) root = scipy.optimize.bisect(bisect_fun, root_min, root_max) time_events_.append(root) root_min = root root_max = root + root_buffer return time_events_ import_intensity = self._params[IMPORT_INTENSITY] f_choice = ImportIntensityFunctions(import_intensity[FUNCTION]) if f_choice == ImportIntensityFunctions.NoImport: return func = import_intensity_functions[f_choice] multiplier = import_intensity[MULTIPLIER] rate = import_intensity[RATE] cap = import_intensity[CAP] infectious_prob = import_intensity[INFECTIOUS] event_times = _generate_event_times(func=func, rate=rate, multiplier=multiplier, cap=cap) for event_time in event_times: person_id = self._individuals_indices[mocos_helper.randint(0, len(self._individuals_indices))] t_state = TMINUS1 if mocos_helper.rand() < infectious_prob: t_state = T0 self.append_event(Event(event_time, person_id, t_state, None, IMPORT_INTENSITY, self.global_time)) def _fill_queue_based_on_initial_conditions(self): """ The purpose of this method is to mark some people of the population as sick according to provided initial conditions. Conditions can be provided using one of two supported schemas. schema v1 is list with details per person, while schema v2 is dictionary specifying selection algorithm and cardinalities of each group of patients (per symptom). :return: """ def _assign_t_state(status): if status == CONTRACTION: return TMINUS1 if status == INFECTIOUS: return T0 if status == IMMUNE: return TRECOVERY raise ValueError(f'invalid initial infection status {status}') initial_conditions = self._params[INITIAL_CONDITIONS] if isinstance(initial_conditions, list): # schema v1 for initial_condition in initial_conditions: person_idx = initial_condition[PERSON_INDEX] t_state = _assign_t_state(initial_condition[INFECTION_STATUS]) if EXPECTED_CASE_SEVERITY in initial_condition: self._expected_case_severity[person_idx] = initial_condition[EXPECTED_CASE_SEVERITY] self.append_event(Event(initial_condition[CONTRACTION_TIME], person_idx, t_state, None, INITIAL_CONDITIONS, self.global_time)) elif isinstance(initial_conditions, dict): # schema v2 if initial_conditions[SELECTION_ALGORITHM] == InitialConditionSelectionAlgorithms.RandomSelection.value: # initially all indices can be drawn #choice_set = self._individuals_indices# self._df_individuals.index.values choice_set = list(self._individuals_indices) for infection_status, cardinality in initial_conditions[CARDINALITIES].items(): if cardinality > 0: if cardinality < 1: c = cardinality cardinality = int(cardinality * len(choice_set)) if cardinality == 0: logger.info(f"too small cardinality provided {cardinality} ({c})") continue else: cardinality = int(cardinality) #selected_rows = np.random.choice(choice_set, cardinality, replace=False) # now only previously unselected indices can be drawn in next steps #choice_set = np.array(list(set(choice_set) - set(selected_rows))) choice_set, selected_rows = mocos_helper.randomly_split_list(choice_set, howmuch=cardinality) t_state = _assign_t_state(infection_status) for row in selected_rows: whom = None if t_state == TRECOVERY: whom = row self.append_event(Event(self.global_time, row, t_state, whom, INITIAL_CONDITIONS, self.global_time)) else: err_msg = f'Unsupported selection algorithm provided {initial_conditions[SELECTION_ALGORITHM]}' logger.error(err_msg) raise ValueError(err_msg) else: err_msg = f'invalid schema provided {initial_conditions}' logger.error(err_msg) raise ValueError(err_msg) @property def global_time(self): return self._global_time @property def df_individuals(self): return self._df_individuals @property def stop_simulation_threshold(self): return self._params[STOP_SIMULATION_THRESHOLD] @property def case_severity_distribution(self): return self._params[CASE_SEVERITY_DISTRIBUTION] @property def disease_progression(self): return self._params[DISEASE_PROGRESSION][DEFAULT] @property def affected_people(self): return self._affected_people @property def detected_people(self): return self._detected_people @property def quarantined_people(self): return self._quarantined_people @property def active_people(self): return self._active_people @property def deaths(self): return self._deaths def draw_expected_case_severity(self): case_severity_dict = self.case_severity_distribution keys = list(case_severity_dict.keys()) d = {} for age_min, age_max, fatality_prob in default_age_induced_fatality_rates: cond_lb = self._individuals_age >= age_min cond_ub = self._individuals_age < age_max cond = np.logical_and(cond_lb, cond_ub) if np.count_nonzero(cond) == 0: continue age_induced_severity_distribution = dict() age_induced_severity_distribution[CRITICAL] = fatality_prob/self._params[DEATH_PROBABILITY][CRITICAL] for x in case_severity_dict: if x != CRITICAL: age_induced_severity_distribution[x] = case_severity_dict[x] / (1 - case_severity_dict[CRITICAL]) * (1 - age_induced_severity_distribution[CRITICAL]) realizations = mocos_helper.sample_with_replacement_shuffled((age_induced_severity_distribution[x] for x in case_severity_dict), len(self._individuals_indices[cond])) values = [keys[r] for r in realizations] df = pd.DataFrame(values, index=self._individuals_indices[cond]) d = {**d, **df.to_dict()[0]} return d def setup_random_distribution(self, t): params = self.disease_progression[t] distribution = params.get(DISTRIBUTION, default_distribution[DISTRIBUTION]) if distribution == FROM_FILE: filepath = params.get('filepath', None).replace('$ROOT_DIR', config.ROOT_DIR) Schema(lambda x: os.path.exists(x)).validate(filepath) array = np.load(filepath) approximate_distribution = params.get('approximate_distribution', None) if approximate_distribution == LOGNORMAL: shape, loc, scale = scipy.stats.lognorm.fit(array, floc=0) return mocos_helper.lognormal, [], {'mean': log(scale), 'sigma': shape} if approximate_distribution == GAMMA: shape, loc, scale = scipy.stats.gamma.fit(array, floc=0) return mocos_helper.gamma, [], {'alpha': shape, 'beta': scale} if approximate_distribution: raise NotImplementedError(f'Approximating to this distribution {approximate_distribution}' f'is not yet supported but we can quickly add it if needed') raise NotImplementedError(f'Currently not supporting empirical distribution' f' without approximating it') if distribution == LOGNORMAL: mean = params.get('mean', 0.0) sigma = params.get('sigma', 1.0) return mocos_helper.lognormal, [], {'mean': mean, 'sigma': sigma} if distribution == EXPONENTIAL: lambda_ = params.get('lambda', 1.0) return mocos_helper.exponential, [], {'scale': 1/lambda_} if distribution == POISSON: lambda_ = params.get('lambda', 1.0) return mocos_helper.poisson, [], {'lam': lambda_} raise ValueError(f'Sampling from distribution {distribution} is not yet supported but we can quickly add it') def add_potential_contractions_from_transport_kernel(self, person_id): pass def set_up_internal_fear(self, kernel_id): fear_factors = self._params[FEAR_FACTORS] fear_factor = fear_factor_schema.validate(fear_factors.get(kernel_id, fear_factors.get(DEFAULT, None))) if not fear_factor: return fear_functions[FearFunctions.FearDisabled], 0, 0, 0, 0, 0 f = fear_functions[FearFunctions(fear_factor[FEAR_FUNCTION])] limit_value = fear_factor[LIMIT_VALUE] scale = fear_factor[SCALE_FACTOR] loc = fear_factor[LOC_FACTOR] weights_deaths = fear_factor[DEATHS_MULTIPLIER] weights_detected = fear_factor[DETECTED_MULTIPLIER] return f, weights_detected, weights_deaths, scale, loc, limit_value def fear(self, kernel_id) -> float: if kernel_id not in self.fear_fun: res = self.set_up_internal_fear(kernel_id) (self.fear_fun[kernel_id], self.fear_weights_detected[kernel_id], self.fear_weights_deaths[kernel_id], self.fear_scale[kernel_id], self.fear_loc[kernel_id], self.fear_limit_value[kernel_id]) = res detected = self.detected_people deaths = self.deaths time = self._global_time if self._params[MOVE_ZERO_TIME_ACCORDING_TO_DETECTED]: if self._max_time_offset != np.inf: time -= self._max_time_offset else: time = -np.inf return self.fear_fun[kernel_id](detected, deaths, time, self.fear_weights_detected[kernel_id], self.fear_weights_deaths[kernel_id], self.fear_loc[kernel_id], self.fear_scale[kernel_id], self.fear_limit_value[kernel_id]) def gamma(self, kernel_id): return self._params[TRANSMISSION_PROBABILITIES][kernel_id] def household_kernel_old_implementation(self, person_id): prog_times = self._progression_times_dict[person_id] start = prog_times[T0] end = prog_times[T2] or prog_times[TRECOVERY] total_infection_rate = (end - start) * self.gamma('household') infected = mocos_helper.poisson(total_infection_rate) if infected == 0: return household_id = self._individuals_household_id[person_id] inhabitants = self._households_inhabitants[household_id] possible_choices = [i for i in inhabitants if i != person_id] for choice_idx in mocos_helper.sample_idxes_with_replacement_uniform(len(possible_choices), infected): person_idx = possible_choices[choice_idx] if self.get_infection_status(person_idx) == InfectionStatus.Healthy: contraction_time = mocos_helper.uniform(low=start, high=end) self.append_event(Event(contraction_time, person_idx, TMINUS1, person_id, HOUSEHOLD, self.global_time)) def add_potential_contractions_from_household_kernel(self, person_id): if self._params[OLD_IMPLEMENTATION_FOR_HOUSEHOLD_KERNEL]: self.household_kernel_old_implementation(person_id) return prog_times = self._progression_times_dict[person_id] start = prog_times[T0] end = prog_times[T2] or prog_times[TRECOVERY] household_id = self._individuals_household_id[person_id] inhabitants = self._households_inhabitants[household_id] possible_choices = [i for i in inhabitants if i != person_id] for person_idx in possible_choices: if self.get_infection_status(person_idx) == InfectionStatus.Healthy: scale = len(possible_choices) / self.gamma('household') contraction_time = start + mocos_helper.exponential(scale=scale) if contraction_time >= end: continue self.append_event(Event(contraction_time, person_idx, TMINUS1, person_id, HOUSEHOLD, self.global_time)) def add_potential_contractions_from_constant_kernel(self, person_id): """ Constant kernel draws a number of infections based on base gamma and enqueue randomly selected events """ prog_times = self._progression_times_dict[person_id] start = prog_times[T0] end = prog_times[T1] if end is None: end = prog_times[T2] total_infection_rate = (end - start) * self.gamma('constant') infected = mocos_helper.poisson(total_infection_rate) if infected == 0: return selected_rows = mocos_helper.nonreplace_sample_few(self._individuals_indices, infected, person_id) for person_idx in selected_rows: if self.get_infection_status(person_idx) == InfectionStatus.Healthy: contraction_time = mocos_helper.uniform(low=start, high=end) self.append_event(Event(contraction_time, person_idx, TMINUS1, person_id, CONSTANT, self.global_time)) def add_potential_contractions_from_constant_age_kernel(self, person_id): if self._disable_constant_age_kernel is True: return age = self._individuals_age_dct[person_id] if age not in self._constant_age_helper_age_dict: return prog_times = self._progression_times_dict[person_id] start = prog_times[T0] end = prog_times[T1] if end is None: end = prog_times[T2] total_infection_rate = (end - start) * self.gamma('constant_age') infected = mocos_helper.poisson(total_infection_rate) if infected == 0: return selected_rows = mocos_helper.nonreplace_sample_few( self._constant_age_individuals[self._constant_age_helper_age_dict[age]], infected, person_id ) for person_idx in selected_rows: if self.get_infection_status(person_idx) == InfectionStatus.Healthy: contraction_time = mocos_helper.uniform(low=start, high=end) self.append_event(Event(contraction_time, person_idx, TMINUS1, person_id, CONSTANT_AGE, self.global_time)) def add_potential_contractions_from_friendship_kernel(self, person_id): if self._disable_friendship_kernel is True: return prog_times = self._progression_times_dict[person_id] start = prog_times[T0] end = prog_times[T1] if end is None: end = prog_times[T2] total_infection_rate = (end - start) * self.gamma('friendship') no_infected = mocos_helper.poisson(total_infection_rate * self._social_activity_scores[person_id]) # Add a constant multiplicand above? age = self._individuals_age_dct[person_id] gender = self._individuals_gender_dct[person_id] for _ in range(no_infected): infected_idx = self._social_activity_sampler.gen(age, gender) if self.get_infection_status(infected_idx) == InfectionStatus.Healthy: contraction_time = mocos_helper.uniform(low=start, high=end) self.append_event(Event(contraction_time, infected_idx, TMINUS1, person_id, FRIENDSHIP, self.global_time)) def handle_t0(self, person_id): self._active_people += 1 if self.get_infection_status(person_id) in [ InfectionStatus.Healthy, InfectionStatus.Contraction ]: self._infection_status[person_id] = InfectionStatus.Infectious.value else: raise AssertionError(f'Unexpected state detected: {self.get_infection_status(person_id)}' f'person_id: {person_id}') household_id = self._individuals_household_id[person_id] # self._df_individuals.loc[person_id, HOUSEHOLD_ID] capacity = self._households_capacities[household_id] # self._df_households.loc[household_id][ID] if capacity > 1: self.add_potential_contractions_from_household_kernel(person_id) self.add_potential_contractions_from_constant_kernel(person_id) self.add_potential_contractions_from_friendship_kernel(person_id) self.add_potential_contractions_from_constant_age_kernel(person_id) def generate_disease_progression(self, person_id, event_time: float, initial_infection_status: str) -> None: """Returns list of disease progression events "future" disease_progression should be recalculated when the disease will be recognised at the state level t0 - time when individual becomes infectious (Mild symptoms) t1 - time when individual stay home/visit doctor due to Mild/Serious? symptoms t2 - time when individual goes to hospital due to Serious symptoms tdeath - time when individual dies (depending on death probability) trecovery - time when individual is recovered (in case the patient will not die from covid19) If person is Infected: A - tminus1 is known (event time), B - t0 is calculated as tminus1 + rv_t0, If person is added to population as Infectious: A - t0 is known (event time), B - tminus 1 is calculated as t0 - rv_t0 For all infected: A - t1 is calculated as t0 + rv_t1 If person will develop Severe or Critical symptoms: A - t2 is calculated as t0 + rv_t2 B - if t1 is larger than t2, discard t1 C - calculate trecovery time as t0 + 6 weeks <- these 6 weeks are from WHO report, in python we use uniform[4w,8w] D - calculate tdetection as t2 If person will develop Asymptomatic or Mild symptoms: A - calculate trecovery time as t0 + 2 weeks <- these 2 weeks are from WHO report, in python we use uniform[11d,17d] B - draw a random number uniform[0,1] and if less than detection_mild_proba, calculate tdetection as t0 + 2 Draw a random number uniform[0,1] and if less than death_probability[expected_case(person_id)]: A - calculate tdeath time as t0 + rv_tdeath, B - discard all times that are larger than tdeath """ if initial_infection_status == InfectionStatus.Contraction: tminus1 = event_time t0 = tminus1 + self.rv_t0() self.append_event(Event(t0, person_id, T0, person_id, DISEASE_PROGRESSION, tminus1)) self._infection_status[person_id] = initial_infection_status elif initial_infection_status == InfectionStatus.Infectious: t0 = event_time # tminus1 does not to be defined, but for completeness let's calculate it tminus1 = t0 - self.rv_t0() else: raise ValueError(f'invalid initial infection status {initial_infection_status}') t2 = None if self._expected_case_severity[person_id] in [ ExpectedCaseSeverity.Severe, ExpectedCaseSeverity.Critical ]: t2 = t0 + self.rv_t2() self.append_event(Event(t2, person_id, T2, person_id, DISEASE_PROGRESSION, t0)) t1 = t0 + self.rv_t1() if not t2 or t1 < t2: self.append_event(Event(t1, person_id, T1, person_id, DISEASE_PROGRESSION, t0)) else: # if t2 < t1 then we reset t1 to avoid misleading in data exported from the simulation t1 = None tdetection = None trecovery = None tdeath = None if mocos_helper.rand() <= self._params[DEATH_PROBABILITY][self._expected_case_severity[person_id]]: tdeath = t0 + self.rv_tdeath() self.append_event(Event(tdeath, person_id, TDEATH, person_id, DISEASE_PROGRESSION, t0)) else: if self._expected_case_severity[person_id] in [ ExpectedCaseSeverity.Mild, ExpectedCaseSeverity.Asymptomatic ]: trecovery = t0 + mocos_helper.uniform(14.0 - 3.0, 14.0 + 3.0) # TODO: this should not be hardcoded! else: trecovery = t0 + mocos_helper.uniform(42.0 - 14.0, 42.0 + 14.0) self.append_event(Event(trecovery, person_id, TRECOVERY, person_id, DISEASE_PROGRESSION, t0)) """ Following is for checking whther tdetection should be picked up""" calculate_tdetection = self._params[TURN_ON_DETECTION] if self._expected_case_severity[person_id] in [ ExpectedCaseSeverity.Mild, ExpectedCaseSeverity.Asymptomatic ]: if mocos_helper.rand() > self._params[DETECTION_MILD_PROBA]: calculate_tdetection = False if calculate_tdetection: """ If t2 is defined (severe/critical), then use this time; if not; use some offset from t0 """ tdetection = t2 or t0 + 2 # TODO: this should not be hardcoded ev = Event(tdetection, person_id, TDETECTION, person_id, DETECTION, t0) self.append_event(ev) self._progression_times_dict[person_id] = {ID: person_id, TMINUS1: tminus1, T0: t0, T1: t1, T2: t2, TDEATH: tdeath, TRECOVERY: trecovery, TDETECTION: tdetection} if initial_infection_status == InfectionStatus.Infectious: self.handle_t0(person_id) @property def df_infections(self): return pd.DataFrame.from_dict(self._infections_dict, orient='index') @property def df_progression_times(self): return pd.DataFrame.from_dict(self._progression_times_dict, orient='index') def save_progression_times(self, path): with open(path, "w") as f: f.write('idx,tminus1,t0,t1,t2,tdeath,trecovery,tdetection,quarantine\n') for elem in self._progression_times_dict.values(): str = f'{elem.get(ID, None)},{elem.get(TMINUS1, None)},{elem.get(T0, None)},'\ f'{elem.get(T1, None)},{elem.get(T2, None)},{elem.get(TDEATH, None)},'\ f'{elem.get(TRECOVERY, None)},{elem.get(TDETECTION, None)},{elem.get(QUARANTINE, None)}\n' f.write(str) def save_potential_contractions(self, path): with open(path, "w") as f: f.write('source_id,target_id,contraction_time,kernel\n') for elem in self._infections_dict.values(): if elem.get(CONTRACTION_TIME) <= self._global_time: # skiping events that were not realized yet str = f'{elem.get(SOURCE, None)},{elem.get(TARGET, None)},{elem.get(CONTRACTION_TIME, None)},'\ f'{elem.get(KERNEL, None)}\n' f.write(str) def prevalance_at(self, time): return len([1 for elem in self._infections_dict.values() if elem.get(CONTRACTION_TIME, np.inf) <= time]) def mean_day_increase_until(self, time): mean_increase = 0.0 i = 0 for k, v in self._per_day_increases.items(): if k <= time: mean_increase = (mean_increase * i + v) / (i + 1) return mean_increase def detected_cases(self, df_r1): cond1 = ~df_r1.tdetection.isna() cond2a = ~df_r1.trecovery.isna() cond2b = df_r1.tdetection > df_r1.trecovery cond2 = ~np.logical_and(cond2a, cond2b) if len(df_r1[~df_r1.tdeath.isna()]) > 0: cond3a = ~df_r1.tdeath.isna() cond3b = df_r1.tdetection > df_r1.tdeath cond3 = ~np.logical_and(cond3a, cond3b) cond23 = np.logical_and(cond2, cond3) else: cond23 = cond2 cond = np.logical_and(cond1, cond23) df = df_r1[cond] detected_cases = df.sort_values(by='tdetection').tdetection return detected_cases @staticmethod def store_parameter(simulation_output_dir, parameter, filename): save_path = os.path.join(simulation_output_dir, filename) with open(save_path, 'wb') as f: pickle.dump(parameter, f) def _save_population_parameters(self, simulation_output_dir): run_id = f'{int(time.monotonic() * 1e9)}_{self._params[RANDOM_SEED]}' if self._params[SAVE_EXPECTED_SEVERITY]: self.store_parameter(simulation_output_dir, self._expected_case_severity, 'expected_case_severity.pkl') self.store_parameter(simulation_output_dir, self._infection_status, 'infection_status.pkl') self.store_parameter(simulation_output_dir, self._detection_status, 'detection_status.pkl') self.store_parameter(simulation_output_dir, self._quarantine_status, 'quarantine_status.pkl') def _save_dir(self, prefix=''): underscore_if_prefix = '_' if len(prefix) > 0 else '' json_name = os.path.splitext(os.path.basename(self.params_path))[0] run_id = f'{prefix}{underscore_if_prefix}{json_name}_{int(time.monotonic() * 1e9)}_{self._params[RANDOM_SEED]}' simulation_output_dir = os.path.join(self._params[OUTPUT_ROOT_DIR], self._params[EXPERIMENT_ID], run_id) os.makedirs(simulation_output_dir) return simulation_output_dir def save_serial_interval(self, simulation_output_dir): if len(self.serial_intervals) == 0: return np.nan np_intervals = np.array(self.serial_intervals) serial_interval_median = np.median(np_intervals) description = scipy.stats.describe(np_intervals) serial_interval_str = f'serial interval: measured from {self._params[SERIAL_INTERVAL][MIN_TIME]}'\ f' to {self._params[SERIAL_INTERVAL][MAX_TIME]};'\ f' median={serial_interval_median}, stats describe: {description}' logger.info(serial_interval_str) np.save(os.path.join(simulation_output_dir, 'serial_intervals.npy'), np_intervals) output_log_file = os.path.join(simulation_output_dir, 'serial_interval_stats.txt') with open(output_log_file, "w") as out: out.write(serial_interval_str) return serial_interval_median def log_outputs(self, simulation_output_dir): self._save_population_parameters(simulation_output_dir) copyfile(self.params_path, os.path.join(simulation_output_dir, f'input_{os.path.basename(self.params_path)}')) if self._params[SAVE_INPUT_DATA]: copyfile(self.df_individuals_path, os.path.join(simulation_output_dir, f'input_{os.path.basename(self.df_individuals_path)}')) household_input_path = os.path.join(self._params[OUTPUT_ROOT_DIR], self._params[EXPERIMENT_ID], 'input_df_households.csv') if not os.path.exists(household_input_path): self._df_households.to_csv(household_input_path) repo = Repo(config.ROOT_DIR) git_active_branch_log = os.path.join(simulation_output_dir, 'git_active_branch_log.txt') with open(git_active_branch_log, 'w') as f: f.write(f'Active branch name {repo.active_branch.name}\n') f.write(str(repo.active_branch.log())) git_status = os.path.join(simulation_output_dir, 'git_status.txt') with open(git_status, 'w') as f: f.write(repo.git.status()) serial_interval = self.save_serial_interval(simulation_output_dir) if self._params[ENABLE_VISUALIZATION]: self._vis.visualize_simulation(simulation_output_dir, serial_interval, self.fear, self.active_people, self._max_time_offset, self.detected_cases, self.df_progression_times, self.df_infections ) def update_max_time_offset(self): if self._params[MOVE_ZERO_TIME_ACCORDING_TO_DETECTED]: if self._max_time_offset == np.inf: if self._params[NUMBER_OF_DETECTED_AT_ZERO_TIME] <= self._detected_people: self._max_time_offset = self._global_time self._init_for_stats = self._active_people def quick_return_condition(self, initiated_through): """ Checks if event of type 'initiated_through' should be abandoned given current situation """ if initiated_through == HOUSEHOLD: return False r = mocos_helper.rand() if initiated_through == CONSTANT and len(self._params[R_OUT_SCHEDULE]) > 0: t = self._global_time - self._max_time_offset for s in self._params[R_OUT_SCHEDULE]: if s[MIN_TIME] <= t <= s[MAX_TIME]: if r > s[OVERRIDE_R_FRACTION]: return True else: return False if r > self.fear(initiated_through): return True return False def add_new_infection(self, person_id, infection_status, initiated_by, initiated_through): self._detection_status[person_id] = DetectionStatus.NotDetected.value self._infections_dict[len(self._infections_dict)] = { SOURCE: initiated_by, TARGET: person_id, CONTRACTION_TIME: self.global_time, KERNEL: initiated_through } if self.global_time >= self._params[SERIAL_INTERVAL][MIN_TIME]: if self.global_time < self._params[SERIAL_INTERVAL][MAX_TIME]: if initiated_by is not None: serial_interval = self.global_time - self._progression_times_dict[initiated_by][TMINUS1] self.serial_intervals.append(serial_interval) self._affected_people += 1 self.generate_disease_progression(person_id, self.global_time, infection_status) # 'Event', [TIME, PERSON_INDEX, TYPE, INITIATED_BY, INITIATED_THROUGH, ISSUED_TIME]) def process_event(self, event) -> bool: type_ = getattr(event, TYPE) time = getattr(event, TIME) if int(time / self._params[LOG_TIME_FREQ]) != int(self._global_time / self._params[LOG_TIME_FREQ]): memory_use = ps.memory_info().rss / 1024 / 1024 fearC = self.fear(CONSTANT) fearH = self.fear(HOUSEHOLD) per_day_increase = 0 if self._last_affected: per_day_increase = (self.affected_people - self._last_affected)/self._last_affected*100 self._last_affected = self.affected_people self._per_day_increases[int(self._global_time)] = per_day_increase logger.info(f'Time: {time:.2f}' f'\tAffected: {self.affected_people}' f'\tDetected: {self.detected_people}' f'\tQuarantined: {self.quarantined_people}' f'\tPer-day-increase: {per_day_increase:.2f} %' f'\tActive: {self.active_people}' f'\tDeaths: {self.deaths}' f'\tFearC: {fearC}' f'\tFearH: {fearH}' f'\tPhysical memory use: {memory_use:.2f} MB') self._global_time = time if self._global_time > self._max_time + self._max_time_offset: return False person_id = getattr(event, PERSON_INDEX) initiated_by = getattr(event, INITIATED_BY) initiated_through = getattr(event, INITIATED_THROUGH) # TODO the remaining attribute will be useful when we will take into account for backtracing # issued_time = getattr(event, ISSUED_TIME) if initiated_by is None and initiated_through != DISEASE_PROGRESSION: if self.get_infection_status(person_id) == InfectionStatus.Healthy: if type_ == TMINUS1: self.add_new_infection(person_id, InfectionStatus.Contraction.value, initiated_by, initiated_through) elif type_ == T0: self.add_new_infection(person_id, InfectionStatus.Infectious.value, initiated_by, initiated_through) elif type_ == TMINUS1: # check if this action is still valid first try: initiated_inf_status = self._infection_status[initiated_by] except KeyError: logging.error(f'infection status should not be blank for infection! key: {initiated_by}') if initiated_inf_status in active_states: if self.quick_return_condition(initiated_through): return True current_status = self.get_infection_status(person_id) if current_status == InfectionStatus.Healthy: new_infection = False # TODO below is a spaghetti code that should be sorted out! SORRY! if initiated_through != HOUSEHOLD: if initiated_inf_status != InfectionStatus.StayHome: new_infection = True if self.get_quarantine_status_(initiated_by) == QuarantineStatus.Quarantine: new_infection = False if self.get_quarantine_status_(person_id) == QuarantineStatus.Quarantine: new_infection = False else: # HOUSEHOLD kernel: new_infection = True if new_infection: self.add_new_infection(person_id, InfectionStatus.Contraction.value, initiated_by, initiated_through) elif type_ == T0: if self.get_infection_status(person_id) == InfectionStatus.Contraction: self.handle_t0(person_id) elif type_ == T1: if self.get_infection_status(person_id) == InfectionStatus.Infectious: self._infection_status[person_id] = InfectionStatus.StayHome.value elif type_ == T2: if self.get_infection_status(person_id) in [ InfectionStatus.StayHome, InfectionStatus.Infectious ]: self._infection_status[person_id] = InfectionStatus.Hospital.value if self._expected_case_severity[person_id] == ExpectedCaseSeverity.Critical: self._icu_needed += 1 elif type_ == TDEATH: if self.get_infection_status(person_id) not in [ InfectionStatus.Death, InfectionStatus.Recovered ]: self._deaths += 1 if self._expected_case_severity[person_id] == ExpectedCaseSeverity.Critical: if self._progression_times_dict[person_id][T2] < self.global_time: self._icu_needed -= 1 self._active_people -= 1 self._infection_status[person_id] = InfectionStatus.Death.value elif type_ == TRECOVERY: # TRECOVERY is exclusive with regards to TDEATH (when this comment was added) if self.get_infection_status(person_id) not in [ InfectionStatus.Recovered, InfectionStatus.Death ]: if initiated_through != INITIAL_CONDITIONS: self._active_people -= 1 if self._expected_case_severity[person_id] == ExpectedCaseSeverity.Critical: if self._progression_times_dict[person_id][T2] < self.global_time: self._icu_needed -= 1 self._infection_status[person_id] = InfectionStatus.Recovered self._immune_people += 1 elif type_ == TDETECTION: if self.get_infection_status(person_id) not in [ InfectionStatus.Recovered, InfectionStatus.Healthy ]: if self.get_detection_status_(person_id) == DetectionStatus.NotDetected: self._detection_status[person_id] = DetectionStatus.Detected.value self._detected_people += 1 self.update_max_time_offset() household_id = self._individuals_household_id[person_id] for inhabitant in self._households_inhabitants[household_id]: if self.get_quarantine_status_(inhabitant) == QuarantineStatus.NoQuarantine: if self.get_infection_status(inhabitant) != InfectionStatus.Death: self._quarantine_status[inhabitant] = QuarantineStatus.Quarantine.value self._quarantined_people += 1 if inhabitant not in self._progression_times_dict: self._progression_times_dict[inhabitant] = {} self._progression_times_dict[inhabitant][QUARANTINE] = self.global_time if self.get_infection_status(inhabitant) in [InfectionStatus.Infectious, InfectionStatus.StayHome]: # TODO: this has to be implemented better, just a temporary solution: if self._progression_times_dict[inhabitant].get(TDETECTION, None) is None: new_detection_time = self.global_time + 2.0 self._progression_times_dict[inhabitant][TDETECTION] = new_detection_time ev = Event(new_detection_time, inhabitant, TDETECTION, person_id, 'quarantine_followed_detection', self.global_time) self.append_event(ev) else: raise ValueError(f'unexpected status of event: {event}') return True def run_simulation(self): def _inner_loop(iter): threshold_type = self._params[STOP_SIMULATION_THRESHOLD_TYPE] value_to_be_checked = None start = time.time() times_mean = 0.0 i = 0 while not q.empty(): event_start = time.time() if threshold_type == PREVALENCE: value_to_be_checked = self.affected_people elif threshold_type == DETECTIONS: value_to_be_checked = self.detected_people if value_to_be_checked is None: logging.error(f"we have an error here") if value_to_be_checked >= self.stop_simulation_threshold: logging.info( f"The outbreak reached a high number {self.stop_simulation_threshold} ({threshold_type})") break event = q.get() if not self.process_event(event): logging.info(f"Processing event {event} returned False") q.task_done() break q.task_done() event_end = time.time() elapsed = event_end - event_start times_mean = ( times_mean * i + elapsed ) / (i + 1) i += 1 end = time.time() print(f'Sim runtime {end - start}, event proc. avg time: {times_mean}') # cleaning up priority queue: while not q.empty(): q.get_nowait() q.task_done() simulation_output_dir = self._save_dir() self.save_progression_times(os.path.join(simulation_output_dir, 'output_df_progression_times.csv')) self.save_potential_contractions(os.path.join(simulation_output_dir, 'output_df_potential_contractions.csv')) if self._params[LOG_OUTPUTS]: logger.info('Log outputs') self.log_outputs(simulation_output_dir) if self._icu_needed >= self._params[ICU_AVAILABILITY]: return True if value_to_be_checked >= self.stop_simulation_threshold: return True return False seeds = None if isinstance(self._params[RANDOM_SEED], str): seeds = eval(self._params[RANDOM_SEED]) # TODO: warning, this is unsafe! not use in production elif isinstance(self._params[RANDOM_SEED], int): seeds = [self._params[RANDOM_SEED]] runs = 0 output_log = 'Last_processed_time;Total_#Affected;Total_#Detected;Total_#Deceased;Total_#Quarantined;'\ 'c;c_norm;Init_#people;Band_hit_time;Subcritical;runs;fear;detection_rate;'\ 'incidents_per_last_day;over_icu;hospitalized;zero_time_offset;total_#immune' if self._params[ENABLE_ADDITIONAL_LOGS]: output_log += ';Prevalence_30days;Prevalence_60days;Prevalence_90days;Prevalence_120days;'\ 'Prevalence_150days;Prevalence_180days;Prevalence_360days;'\ 'increase_10;increase_20;increase_30;increase_40;increase_50;increase_100;increase_150' output_log += '\n' for i, seed in enumerate(seeds): runs += 1 self.parse_random_seed(seed) self.setup_simulation() logger.info('Filling queue based on initial conditions...') self._fill_queue_based_on_initial_conditions() logger.info('Filling queue based on auxiliary functions...') self._fill_queue_based_on_auxiliary_functions() logger.info('Initialization step is done!') outbreak = _inner_loop(i + 1) last_processed_time = self._global_time c = self._params[TRANSMISSION_PROBABILITIES][CONSTANT] c_norm = c * self._params[AVERAGE_INFECTIVITY_TIME_CONSTANT_KERNEL] subcritical = self._active_people < self._init_for_stats / 2 # at 200 days bandtime = self.band_time #if bandtime: # return 0 fear_ = self.fear(CONSTANT) detection_rate = self._params[DETECTION_MILD_PROBA] affected = self.affected_people detected = self.detected_people deceased = self.deaths quarantined = self.quarantined_people incidents_per_last_day = self.prevalance_at(self._global_time) - self.prevalance_at(self._global_time - 1) hospitalized = self._icu_needed zero_time_offset = self._max_time_offset immune = self._immune_people output_add = f'{last_processed_time };{affected};{detected};{deceased};{quarantined};{c};{c_norm};'\ f'{self._init_for_stats};{bandtime};{subcritical};{runs};{fear_};{detection_rate};'\ f'{incidents_per_last_day};{outbreak};{hospitalized};{zero_time_offset};{immune}' if self._params[ENABLE_ADDITIONAL_LOGS]: prev30 = self.prevalance_at(30) prev60 = self.prevalance_at(60) prev90 = self.prevalance_at(90) prev120 = self.prevalance_at(120) prev150 = self.prevalance_at(150) prev180 = self.prevalance_at(180) prev360 = self.prevalance_at(360) mean_increase_at_10 = self.mean_day_increase_until(10) mean_increase_at_20 = self.mean_day_increase_until(20) mean_increase_at_30 = self.mean_day_increase_until(30) mean_increase_at_40 = self.mean_day_increase_until(40) mean_increase_at_50 = self.mean_day_increase_until(50) mean_increase_at_100 = self.mean_day_increase_until(100) mean_increase_at_150 = self.mean_day_increase_until(150) output_add += f'{prev30};{prev60};{prev90};{prev120};{prev150};{prev180};{prev360};'\ f'{mean_increase_at_10};{mean_increase_at_20};{mean_increase_at_30};'\ f'{mean_increase_at_40};{mean_increase_at_50};{mean_increase_at_100};'\ f'{mean_increase_at_150}' output_add += '\n' logger.info(output_add) output_log = f'{output_log}{output_add}' logger.info(output_log) simulation_output_dir = self._save_dir('aggregated_results') output_log_file = os.path.join(simulation_output_dir, 'results.txt') if self._params[ENABLE_VISUALIZATION]: self._vis.visualize_scenario(simulation_output_dir) with open(output_log_file, "w") as out: out.write(output_log) def setup_simulation(self): self._init_for_stats = 0 # TODO support different import methods if isinstance(self._params[INITIAL_CONDITIONS], dict): cardinalities = self._params[INITIAL_CONDITIONS][CARDINALITIES] self._init_for_stats = cardinalities.get(CONTRACTION, 0) + cardinalities.get(INFECTIOUS, 0) # TODO and think how to better group them, ie namedtuple state_stats? self._affected_people = 0 self._active_people = 0 self._detected_people = 0 self._quarantined_people = 0 self._immune_people = 0 self._deaths = 0 self._icu_needed = 0 self._max_time_offset = 0 if self._params[MOVE_ZERO_TIME_ACCORDING_TO_DETECTED]: self._max_time_offset = np.inf self._fear_factor = {} self._infection_status = {} self._infections_dict = {} self._progression_times_dict = {} self._per_day_increases = {} self._global_time = self._params[START_TIME] self._max_time = self._params[MAX_TIME] if not self._params[REUSE_EXPECTED_CASE_SEVERITIES]: self._expected_case_severity = self.draw_expected_case_severity() self._last_affected = None self.band_time = None self._quarantine_status = {} self._detection_status = {} if self._params[ENABLE_VISUALIZATION]: self._vis = Visualize(self._params, self.df_individuals, self._expected_case_severity, logger) logger = logging.getLogger(__name__) @click.command() @click.option('--params-path', type=click.Path(exists=True)) @click.option('--df-individuals-path', type=click.Path(exists=True)) @click.option('--df-households-path', type=click.Path()) @click.argument('run-simulation') #ignored def runner(params_path, df_individuals_path, run_simulation, df_households_path=''): im = InfectionModel(params_path=params_path, df_individuals_path=df_individuals_path, df_households_path=df_households_path or '') im.run_simulation() # TODO: think about separate thread/process to generate random numbers, facilitate sampling if __name__ == '__main__': log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=log_fmt) pid = os.getpid() ps = psutil.Process(pid) pd.set_option('display.max_columns', None) #fire.Fire(InfectionModel) # find .env automagically by walking up directories until it's found, then # load up the .env entries as environment variables load_dotenv(find_dotenv()) runner()
49.643697
178
0.629799
2c8c1948f6fe7de896948b63c3d5376e74c0e1d8
6,141
py
Python
Activities/models.py
tonyamf/LES
074807be27fe3ec61c744c674636a48df2264e67
[ "MIT" ]
null
null
null
Activities/models.py
tonyamf/LES
074807be27fe3ec61c744c674636a48df2264e67
[ "MIT" ]
null
null
null
Activities/models.py
tonyamf/LES
074807be27fe3ec61c744c674636a48df2264e67
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. class Tags(models.Model): name = models.IntegerField(db_column='Name', blank=True, null=True) id = models.AutoField(db_column='ID', primary_key=True) class Meta: managed = True db_table = 'Tags' class Pattern(models.Model): id = models.AutoField(db_column='ID', primary_key=True) userid = models.ForeignKey('Users.User', models.DO_NOTHING, db_column='UserID') patternname = models.CharField(db_column='PatternName', max_length=255, verbose_name='Padrão') image = models.TextField(db_column='Image', blank=True, null=True) description = models.CharField(db_column='Description', max_length=255) data_creation = models.DateField(db_column='Data Creation', null=True) groups = models.ManyToManyField('Group') class Meta: managed = True db_table = 'Pattern' ordering = ['-data_creation'] class Group(models.Model): id = models.AutoField(db_column='ID', primary_key=True) userid = models.ForeignKey('Users.User', models.DO_NOTHING, null=True, db_column='UserID') groupname = models.CharField(db_column='GroupName', unique=True, max_length=255, verbose_name='Agrupamento') creationdate = models.DateField(db_column='CreationDate', blank=True, null=True) name = models.CharField(db_column='Name', max_length=255) description = models.CharField(db_column='Description', max_length=255) tags = models.ManyToManyField('Tags') sentences = models.ManyToManyField('Sentence') class Meta: managed = True db_table = 'Group' ordering = ['-creationdate'] def __str__(self): return self.groupname class Sentence(models.Model): id = models.AutoField(db_column='ID', primary_key=True) userid = models.ForeignKey('Users.User', models.DO_NOTHING, db_column='UserID') sentencename = models.CharField(db_column='SentenceName', max_length=255, verbose_name="Frase") datecreated = models.DateField(db_column='DateCreated', null=True) subject = models.CharField(db_column='Subject', max_length=255, verbose_name="Sujeito") receiver = models.CharField(db_column='Receiver', max_length=255, blank=True, null=False, verbose_name="Recetor") datarealizado = models.DateField(db_column='DataRealizado',blank=True, null=True) verbid = models.ForeignKey('Verb', models.DO_NOTHING, db_column='VerbID', verbose_name="Verbo") resourceid = models.ForeignKey('Resource', models.DO_NOTHING, db_column='ResourceID', verbose_name="Recurso", null=True, blank=True) artefactid = models.ForeignKey('Artefact', models.DO_NOTHING, db_column='ArtefactID', verbose_name="Artefacto", null=True, blank=True) class Meta: managed = True db_table = 'Sentence' ordering = ['-datecreated'] def __str__(self): return self.sentencename class Verb(models.Model): verb_type_choices = (('Produtivo','Produtivo'), ('Comunicativo','Comunicativo')) id = models.AutoField(db_column='ID', primary_key=True) verbname = models.CharField(db_column='VerbName', unique=True, max_length=255, verbose_name='Verbo') verbtype = models.CharField(db_column='VerbType', max_length=255, choices=verb_type_choices, verbose_name='Tipo') class Meta: managed = True db_table = 'Verb' ordering = ['-id'] def __str__(self): return self.verbname class Resource(models.Model): id = models.AutoField(db_column='ID', primary_key=True) resourcename = models.CharField(db_column='ResourceName', unique=True, max_length=255, verbose_name='Recurso') datecreated = models.DateField(db_column='DateCreated') class Meta: managed = True db_table = 'Resource' ordering = ['-id'] def __str__(self): return self.resourcename class Artefact(models.Model): id = models.AutoField(db_column='ID', primary_key=True) artefactname = models.CharField(db_column='ArtefactName', unique=True, max_length=255, verbose_name='Artefacto') datecreated = models.DateField(db_column='DateCreated') class Meta: managed = True db_table = 'Artefacto' ordering = ['-id'] def __str__(self): return self.artefactname
35.912281
85
0.488845
c9a8d170e8b121494edd5c84a9776c0cdb0a3f39
473
ts
TypeScript
app/test/fixtures/team.ts
Nalhin/PokemonDreamTeams
1b83f879496a42961c2b14c7a0b7b806b870b224
[ "MIT" ]
2
2020-01-19T16:15:08.000Z
2020-01-19T22:48:02.000Z
app/test/fixtures/team.ts
Nalhin/PokemonDreamTeams
1b83f879496a42961c2b14c7a0b7b806b870b224
[ "MIT" ]
2
2019-10-27T20:16:32.000Z
2020-02-19T18:08:06.000Z
app/test/fixtures/team.ts
Nalhin/PokemonTeams
1b83f879496a42961c2b14c7a0b7b806b870b224
[ "MIT" ]
null
null
null
export const fakeTeam = { description: 'Team description', name: 'Team name', owner: { _id: '5da31dc6d5bdcf381c302469', login: '1' }, roster: [ { attack: 100, defense: 121, hp: 108, name: 'Zygarde', pokedexId: 718, speed: 95, spellAttack: 81, spellDefense: 95, tags: ['Dragon', 'Ground'], total: 600, _id: '5d9a6116f0a2d44fefa3b12c', }, ], type: 1, _id: '5da4eded265a603ad839b56e', };
20.565217
57
0.560254
8ea860a667ebfce36de5306ef5b54c8ef1826c5c
2,156
js
JavaScript
src/components/hero.js
zaneadix/qc-links
f9bc569e40ac86d6177a18a1f200034d40f537b9
[ "MIT" ]
null
null
null
src/components/hero.js
zaneadix/qc-links
f9bc569e40ac86d6177a18a1f200034d40f537b9
[ "MIT" ]
null
null
null
src/components/hero.js
zaneadix/qc-links
f9bc569e40ac86d6177a18a1f200034d40f537b9
[ "MIT" ]
null
null
null
import React from "react" import YouTube from "react-youtube" import { css } from "@emotion/core" import Image from "../components/image" import { colors, mediaQueries } from "../utils/styleVars" let containerStyles = css` background-color: ${colors.everglaze}; position: relative; margin: 0 -1rem; ${mediaQueries[2]} { margin: 0 0; } &::after { display: block; content: " "; width: 100%; padding-bottom: 56.25%; } .title-wrapper { position: absolute; left: 0; bottom: 0; padding: 2.5rem 1rem; z-index: 100; .title { font-size: 4.5rem; line-height: 4.5rem; color: white; font-weight: 900; } .preamble { color: ${colors.cremeDeMunch}; margin-bottom: 0.25rem; } ${mediaQueries[0]} { padding: 2.5rem 1.5rem; .title { font-size: 4.5rem; line-height: 4.5rem; } } ${mediaQueries[1]} { padding: 3rem 2.5rem; } ${mediaQueries[2]} { padding: 3.5rem; } } .gatsby-image-wrapper { z-index: 10; } .youtube-frame { // fuckin weird library styles? div & { margin-bottom: 0; } } .gatsby-image-wrapper, .youtube-frame { position: absolute !important; top: 0; left: 0; width: 100%; height: 100%; } ` export default ({ collapse = false, preamble, title, image, youtubeID }) => { return ( <div className="hero container fluid-1"> <div css={containerStyles} style={{ height: collapse ? "min-content" : null }} > {/* Need alternate text */} {image && !youtubeID ? <Image src={image}></Image> : null} {!youtubeID ? ( <div className="title-wrapper"> <h3 className="preamble sans">{preamble}</h3> <h1 className="title serif floor" dangerouslySetInnerHTML={{ __html: title }} ></h1> </div> ) : null} {/* NEED HEIGHT LOGIC */} {youtubeID ? ( <YouTube className="youtube-frame" videoId={youtubeID}></YouTube> ) : null} </div> </div> ) }
19.962963
77
0.536178
df1d85e096f476ced6d5dbbe3e883304dfcb986e
412
cs
C#
Pandaros.API/Extender/IOnConstructInventoryManageColonyUIExtender.cs
JBurlison/Pandaros.API
b76b966a1916005f695581f39a3512e8e5fa22cf
[ "MIT" ]
1
2019-12-27T19:37:27.000Z
2019-12-27T19:37:27.000Z
Pandaros.API/Extender/IOnConstructInventoryManageColonyUIExtender.cs
JBurlison/Pandaros.API
b76b966a1916005f695581f39a3512e8e5fa22cf
[ "MIT" ]
5
2020-09-07T22:30:59.000Z
2021-05-14T11:13:22.000Z
Pandaros.API/Extender/IOnConstructInventoryManageColonyUIExtender.cs
JBurlison/Pandaros.API
b76b966a1916005f695581f39a3512e8e5fa22cf
[ "MIT" ]
2
2019-08-09T00:11:36.000Z
2020-10-04T21:47:27.000Z
using NetworkUI; using NetworkUI.Items; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pandaros.API.Extender { public interface IOnConstructInventoryManageColonyUIExtender : IPandarosExtention { void OnConstructInventoryManageColonyUI(Players.Player player, NetworkMenu networkMenu, (Table, Table) table); } }
25.75
118
0.791262
e458c38e60f7f65fc13c85cd719d4d340322bd8e
4,771
swift
Swift
goSellAppClipSDK/Core/API/Internal/Data Managers/SettingsDataManager.swift
Tap-Payments/goSellSDKAppClips
a3f8362010c69e5d8c69253cc0ec59f5ddf301e0
[ "MIT" ]
1
2021-03-31T18:21:37.000Z
2021-03-31T18:21:37.000Z
goSellAppClipSDK/Core/API/Internal/Data Managers/SettingsDataManager.swift
Tap-Payments/goSellAppClipSDK
a3f8362010c69e5d8c69253cc0ec59f5ddf301e0
[ "MIT" ]
null
null
null
goSellAppClipSDK/Core/API/Internal/Data Managers/SettingsDataManager.swift
Tap-Payments/goSellAppClipSDK
a3f8362010c69e5d8c69253cc0ec59f5ddf301e0
[ "MIT" ]
null
null
null
// // SettingsDataManager.swift // goSellSDK // // Copyright © 2019 Tap Payments. All rights reserved. // import func TapSwiftFixesV2.synchronized /// Settings data manager. import UIKit internal final class SettingsDataManager { // MARK: - Internal - internal typealias OptionalErrorClosure = (TapSDKError?) -> Void // MARK: Properties /// SDK settings. internal private(set) var settings: SDKSettingsData? { didSet { if let deviceID = self.settings?.deviceID { KeychainManager.deviceID = deviceID } } } // MARK: Methods internal func checkInitializationStatus(_ completion: @escaping OptionalErrorClosure) { synchronized(self) { [unowned self] in switch self.status { case .notInitiated: self.append(completion) self.callInitializationAPI() case .initiated: self.append(completion) case .succeed: guard self.settings != nil else { completion(TapSDKUnknownError(dataTask: nil)) return } completion(nil) } } } internal static func resetAllSettings() { self.storages?.values.forEach { $0.reset() } } // MARK: - Private - // MARK: Properties private var status: InitializationStatus = .notInitiated private var pendingCompletions: [OptionalErrorClosure] = [] private static var storages: [SDKMode: SettingsDataManager]? = [:] // MARK: Methods private init() {} private func append(_ completion: @escaping OptionalErrorClosure) { self.pendingCompletions.append(completion) } private func callInitializationAPI() { self.status = .initiated APIClient.shared.initSDK { [unowned self] (settings, error) in self.update(settings: settings, error: error) } } private func update(settings updatedSettings: SDKSettings?, error: TapSDKError?) { let unVerifiedApplicationError = (SettingsDataManager.shared.settings?.verifiedApplication ?? true) ? nil : TapSDKError(type: .unVerifiedApplication) var finalError:TapSDKError? if let nonnullError = error { finalError = nonnullError }else if let nonnullError = unVerifiedApplicationError { finalError = nonnullError print(nonnullError.description) } if let nonnullError = finalError { self.status = .notInitiated if self.pendingCompletions.count > 0 { self.callAllPendingCompletionsAndEmptyStack(nonnullError) } else { ErrorDataManager.handle(nonnullError, retryAction: { self.callInitializationAPI() }, alertDismissButtonClickHandler: nil) } } else { self.settings = updatedSettings?.data self.status = .succeed self.callAllPendingCompletionsAndEmptyStack(nil) } } private func callAllPendingCompletionsAndEmptyStack(_ error: TapSDKError?) { synchronized(self) { [unowned self] in for completion in self.pendingCompletions { completion(error) } self.pendingCompletions.removeAll() } } private func reset() { let userInfo: [String: String] = [ NSLocalizedDescriptionKey: "Merchant account data is missing." ] let underlyingError = NSError(domain: ErrorConstants.internalErrorDomain, code: InternalError.noMerchantData.rawValue, userInfo: userInfo) let error = TapSDKKnownError(type: .internal, error: underlyingError, response: nil, body: nil) self.update(settings: nil, error: error) } } // MARK: - Singleton extension SettingsDataManager: Singleton { internal static var shared: SettingsDataManager { if let existing = self.storages?[GoSellSDK.mode] { return existing } let instance = SettingsDataManager() var stores = self.storages ?? [:] stores[GoSellSDK.mode] = instance self.storages = stores return instance } } // MARK: - ImmediatelyDestroyable extension SettingsDataManager: ImmediatelyDestroyable { internal static func destroyInstance() { self.storages = nil } internal static var hasAliveInstance: Bool { return !(self.storages?.isEmpty ?? true) } }
24.848958
158
0.590652
4dcdea84ed35e2582d42199ac0eb0b127a85c4af
2,847
cs
C#
InstantDelivery.Service/Controllers/UsersController.cs
Gourishanakr/user-management
979924d3588b224ecbfad9b7fdb6fb96ceee5f10
[ "MIT" ]
21
2017-02-05T09:09:39.000Z
2022-03-14T06:33:41.000Z
InstantDelivery.Service/Controllers/UsersController.cs
Gourishanakr/user-management
979924d3588b224ecbfad9b7fdb6fb96ceee5f10
[ "MIT" ]
1
2021-01-05T23:57:09.000Z
2021-01-12T14:16:44.000Z
InstantDelivery.Service/Controllers/UsersController.cs
Gourishanakr/user-management
979924d3588b224ecbfad9b7fdb6fb96ceee5f10
[ "MIT" ]
14
2017-11-04T15:01:37.000Z
2021-01-07T08:52:18.000Z
using AutoMapper.QueryableExtensions; using InstantDelivery.Common.Enums; using InstantDelivery.Domain; using InstantDelivery.Domain.Entities; using InstantDelivery.Model; using InstantDelivery.Model.Paging; using InstantDelivery.Service.Paging; using Microsoft.AspNet.Identity; using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace InstantDelivery.Service.Controllers { /// <summary> /// Kontroler użytkowników /// </summary> [Authorize(Roles = "Admin")] [RoutePrefix("Users")] public class UsersController : ApiController { private readonly InstantDeliveryContext context; private readonly UserManager<User, string> userManager; /// <summary> /// Konstruktor kontrolera /// </summary> /// <param name="context"></param> /// <param name="userManager"></param> public UsersController(InstantDeliveryContext context, UserManager<User, string> userManager) { this.context = context; this.userManager = userManager; } /// <summary> /// Zwraca stronę użytkowników /// </summary> /// <param name="query"></param> /// <returns></returns> [Route("Page"), HttpGet] public IHttpActionResult GetPage([FromUri] PageQuery query) { var dtos = context.Employees.Include(e => e.User) .AsQueryable() .Where(e => e.User != null) .ProjectTo<UserDto>(); var result = PagingHelper.GetPagedResult(dtos, query); foreach (var dto in result.PageCollection) { dto.Role = (Role)Enum.Parse(typeof(Role), userManager.GetRoles(dto.Id).First()); } return Ok(result); } /// <summary> /// Zmienia rolę użytkownika /// </summary> /// <param name="username">Nazwa użytkownika</param> /// <param name="newRole">Nowa rola</param> /// <returns></returns> [Route("ChangeRole/{username}"), HttpPost] public async Task<IHttpActionResult> ChangeRole(string username, [FromBody]Role newRole) { User user = await userManager.FindByNameAsync(username); if (user == null) { return NotFound(); } string[] allRoles = context.Roles.Select(r => r.Name).ToArray(); foreach (var role in allRoles) { await userManager.RemoveFromRoleAsync(user.Id, role); } var result = await userManager.AddToRoleAsync(user.Id, newRole.ToString()); if (result.Succeeded) { return Ok(); } return BadRequest(); } } }
33.104651
101
0.582367
a3c55351f480edd5591c58e49706631229c505b7
3,870
java
Java
src/com/github/anorber/argparse/ArgumentParser.java
anorber/argparse
7b29c645b7db8afb4ed1fb14ecd73ebdf2b7080f
[ "WTFPL" ]
null
null
null
src/com/github/anorber/argparse/ArgumentParser.java
anorber/argparse
7b29c645b7db8afb4ed1fb14ecd73ebdf2b7080f
[ "WTFPL" ]
null
null
null
src/com/github/anorber/argparse/ArgumentParser.java
anorber/argparse
7b29c645b7db8afb4ed1fb14ecd73ebdf2b7080f
[ "WTFPL" ]
1
2019-04-23T03:10:32.000Z
2019-04-23T03:10:32.000Z
package com.github.anorber.argparse; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * @author anorber * * @param <E> */ public class ArgumentParser<E> implements Iterable<Option<E>> { private final ArgumentList<E> arguments; private final FoundOpts<E> foundOpts; /** */ public ArgumentParser() { foundOpts = new FoundOpts<E>(); arguments = new ArgumentList<E>(foundOpts); } /** * @param other an ArgumentParser to clone */ public ArgumentParser(final ArgumentParser<E> other) { foundOpts = new FoundOpts<E>(other.foundOpts); arguments = new ArgumentList<E>(other.arguments, foundOpts); } /** * Adds an argument to this parser. * * @param argument an option argument */ public void addArgument(final Argument<? extends E> argument) { if (argument == null) { throw new IllegalArgumentException("argument should not be null"); } arguments.add(argument); } /** * Parses args for opts. * * @param args the args to be parsed * @return the rest of the args after that the opts was parsed * or null if args was null * @throws ArgumentParserException if somthing goes wrong */ public String[] parse(final String[] args) throws ArgumentParserException { if (args == null) { return null; } final int pos = arguments.parseOpts(args); return Arrays.copyOfRange(args, pos, args.length); } /** * Tells if this parser has seen <code>option</code>. * * @param option enum representing an option * @return true if this parser found the option */ public boolean hasOption(final E option) { return foundOpts.containsOption(option); } /** * Returns an array with the arguments given to this option. * * @param option enum representing an option * @return the arguments in the order they appeared */ public String[] getArguments(final E option) { final List<String> opt = foundOpts.getArgs(option); if (opt == null) { return null; } return opt.toArray(new String[opt.size()]); } /** * Returns all arguments for an option as an array. All strings are split * at the delimiter character. * * @param option the option who's args we want * @param delimiter character to use for splitting argument strings * @return string array of arguments */ public String[] getArguments(final E option, final char delimiter) { final List<String> buf = new ArrayList<String>(); final List<String> options = foundOpts.getArgs(option); if (options == null) { return new String[0]; } for (String arg : options) { for (String substr : arg.split("\\" + delimiter)) { buf.add(substr); } } return buf.toArray(new String[buf.size()]); } /** * Returns all arguments for an option as a string. * * @param option the option who's args we want * @param delimiter character to insert between arguments * @return string of all arguments */ public String getArgumentsString(final E option, final char delimiter) { final String[] args = getArguments(option); if (args == null) { return ""; } final StringBuilder buf = new StringBuilder(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(delimiter).append(args[i]); } return buf.toString(); } /* @see java.lang.Runnable#run() */ @Override public Iterator<Option<E>> iterator() { return foundOpts.getIterator(); } /* @see java.lang.Object#hashCode() */ @Override public int hashCode() { return arguments.hashCode() ^ foundOpts.hashCode(); } /* @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { return obj instanceof ArgumentParser && arguments.equals(((ArgumentParser<?>) obj).arguments) && foundOpts.equals(((ArgumentParser<?>) obj).foundOpts); } }
25.8
76
0.673127
6b3770444590dc9d093e047cce3765c2bc941472
576
js
JavaScript
types/tests/autogen.js
jamisoncozart/Chart.js
acd3b147a531b9362f03604b062067a4a9f9ee27
[ "MIT" ]
42,279
2016-04-24T22:47:13.000Z
2022-03-31T23:54:31.000Z
types/tests/autogen.js
jamisoncozart/Chart.js
acd3b147a531b9362f03604b062067a4a9f9ee27
[ "MIT" ]
6,522
2016-04-24T21:45:09.000Z
2022-03-31T16:32:50.000Z
types/tests/autogen.js
jamisoncozart/Chart.js
acd3b147a531b9362f03604b062067a4a9f9ee27
[ "MIT" ]
8,515
2016-04-25T04:55:38.000Z
2022-03-31T23:47:40.000Z
import * as fs from 'fs'; import * as path from 'path'; import * as helpers from '../../src/helpers/index.js'; let fd; try { const fn = path.resolve(__dirname, 'autogen_helpers.ts'); fd = fs.openSync(fn, 'w+'); fs.writeSync(fd, 'import * as helpers from \'../helpers\';\n\n'); fs.writeSync(fd, 'const testKeys = [];\n'); for (const key of Object.keys(helpers)) { if (key[0] !== '_' && typeof helpers[key] === 'function') { fs.writeSync(fd, `testKeys.push(helpers.${key});\n`); } } } finally { if (fd !== undefined) { fs.closeSync(fd); } }
25.043478
67
0.585069
6916eca49f48313405468ebb35a5fbd7cf5a2102
1,308
swift
Swift
Foundation/NetworkClient/Utils/Parameters/Parameters+Value.swift
ihor-yarovyi/ReduxStarter
c2096d7b90e887e216999bb14e777faa66ace673
[ "MIT" ]
null
null
null
Foundation/NetworkClient/Utils/Parameters/Parameters+Value.swift
ihor-yarovyi/ReduxStarter
c2096d7b90e887e216999bb14e777faa66ace673
[ "MIT" ]
null
null
null
Foundation/NetworkClient/Utils/Parameters/Parameters+Value.swift
ihor-yarovyi/ReduxStarter
c2096d7b90e887e216999bb14e777faa66ace673
[ "MIT" ]
null
null
null
// // Parameters+Value.swift // NetworkClient // // Created by Ihor Yarovyi on 8/23/21. // import Foundation extension NetworkClient.Utils.Parameters { struct Value: ParametersSubscript { // MARK: - Private let storage: Storage let keys: [String] var keyPath: String { keys.joined(separator: ".") } func getValue<T>() -> T? { storage.dictionary[keyPath: keyPath] as? T } func setValue<T: ParametersEncodable>(_ value: T, includeNull: Bool = false) { if let encodedValue = value.encodedValue { storage.dictionary[keyPath: keyPath] = encodedValue } else if includeNull { storage.dictionary[keyPath: keyPath] = NSNull() } else { storage.dictionary[keyPath: keyPath] = nil } } init(storage: Storage, keys: [String]) { self.storage = storage self.keys = keys } func parametersValue(for key: String) -> Value { NetworkClient.Utils.Parameters.Value(storage: storage, keys: keys + [key]) } var value: Any? { storage.dictionary[keyPath: keyPath] } } }
26.693878
86
0.526758
ef580fdd71dcf6ec46c513c0b96f07e2f4e3b95c
692
js
JavaScript
client/src/components/ListDeleterContainer.js
JonasImm/mega-app2020
b19c663710a8534fad4cdba0ff046152848b6e67
[ "MIT" ]
9
2020-09-09T07:22:08.000Z
2020-09-14T05:42:16.000Z
client/src/components/ListDeleterContainer.js
JonasImm/mega-app2020
b19c663710a8534fad4cdba0ff046152848b6e67
[ "MIT" ]
29
2020-09-06T15:24:37.000Z
2020-09-23T16:08:01.000Z
client/src/components/ListDeleterContainer.js
JonasImm/mega-app2020
b19c663710a8534fad4cdba0ff046152848b6e67
[ "MIT" ]
1
2020-09-29T13:02:18.000Z
2020-09-29T13:02:18.000Z
import React from "react"; import PropTypes from "prop-types"; import styled from "@emotion/styled"; import ListDeleter from "./ListDeleter"; function ListDeleterContainer({ onCancel, onDeleteConfirm }) { return ( <Container> <ListDeleter onCancel={onCancel} onDeleteConfirm={onDeleteConfirm} /> </Container> ); } export default ListDeleterContainer; ListDeleterContainer.propTypes = { onCancel: PropTypes.func, onDeleteConfirm: PropTypes.func, }; const Container = styled.div` position: fixed; z-index: 2; top: 0; left: 0; height: 100%; width: 100%; background: rgba(0, 0, 0, 0.8); display: flex; justify-content: center; align-items: center; `;
21.625
75
0.703757
a16069789117144f0ee1f4178284fd8184691288
962
tsx
TypeScript
packages/react-icons/src/components/StarOff16Regular.tsx
LiquidatorCoder/fluentui-system-icons
d3614e4e95f47d86b1d1f930c4925e513949da54
[ "MIT" ]
null
null
null
packages/react-icons/src/components/StarOff16Regular.tsx
LiquidatorCoder/fluentui-system-icons
d3614e4e95f47d86b1d1f930c4925e513949da54
[ "MIT" ]
null
null
null
packages/react-icons/src/components/StarOff16Regular.tsx
LiquidatorCoder/fluentui-system-icons
d3614e4e95f47d86b1d1f930c4925e513949da54
[ "MIT" ]
null
null
null
import * as React from "react"; import { JSX } from "react-jsx"; import { IFluentIconsProps } from '../IFluentIconsProps.types'; const StarOff16Regular = (iconProps: IFluentIconsProps, props: React.HTMLAttributes<HTMLElement>): JSX.Element => { const { primaryFill, className } = iconProps; return <svg {...props} width={16} height={16} viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" className={className}><path d="M12.36 13.06a.9.9 0 01-1.32.89L8 12.35l-3.04 1.6a.9.9 0 01-1.3-.95l.57-3.39-2.46-2.4a.9.9 0 01.5-1.53l2.36-.34-3.48-3.49a.5.5 0 11.7-.7l13 13a.5.5 0 01-.7.7l-1.8-1.79zm-1.22-1.22L5.5 6.22l-2.9.42 2.36 2.3c.21.2.3.5.26.79l-.56 3.24 2.91-1.53a.9.9 0 01.84 0l2.9 1.53-.18-1.13z" fill={primaryFill} /><path d="M13.39 6.64l-2.35 2.28.74.73-.01-.04 2.46-2.4a.9.9 0 00-.5-1.53l-3.4-.5L8.8 2.1a.9.9 0 00-1.62 0l-.98 2 .75.74L8 2.73l1.46 2.94a.9.9 0 00.67.5l3.26.47z" fill={primaryFill} /></svg>; }; export default StarOff16Regular;
74
621
0.661123
0dcb8d46853352ba2ea1a084d2ae23638b07a8b1
5,096
cs
C#
SalaryEntities/Entities/Salary.cs
chrisjsherm/Facsal
ab4aff2b5532ce6429b5d8f383fa14b34e5f3cfb
[ "MIT" ]
null
null
null
SalaryEntities/Entities/Salary.cs
chrisjsherm/Facsal
ab4aff2b5532ce6429b5d8f383fa14b34e5f3cfb
[ "MIT" ]
null
null
null
SalaryEntities/Entities/Salary.cs
chrisjsherm/Facsal
ab4aff2b5532ce6429b5d8f383fa14b34e5f3cfb
[ "MIT" ]
null
null
null
using DataAnnotationsExtensions; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; using ChrisJSherm.Filters; namespace SalaryEntities.Entities { [EitherPropertyGreaterThanZero("BaseAmount", "EminentAmount", "Either the base amount or eminent amount must be greater than zero.")] public class Salary : AuditEntityBase { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Index("IX_PersonAndCycleYear", 1, IsUnique = true, IsClustered = false)] [ForeignKey("Person")] public string PersonId { get; set; } [Index("IX_PersonAndCycleYear", 2, IsUnique = true, IsClustered = false)] [Max(2050)] [Min(2000)] public int CycleYear { get; set; } [StringLength(128)] public string Title { get; set; } [ForeignKey("FacultyType")] public int FacultyTypeId { get; set; } [ForeignKey("RankType")] [Display(Name = "Rank type")] public string RankTypeId { get; set; } [ForeignKey("AppointmentType")] public int AppointmentTypeId { get; set; } [ForeignKey("LeaveType")] public int LeaveTypeId { get; set; } [Required] [Max(1.00)] [Min(0.00)] [Display(Name = "FTE")] public decimal FullTimeEquivalent { get; set; } [Min(0)] public int? BannerBaseAmount { get; private set; } [Max(100000000)] [Min(0)] [Display(Name = "Base salary")] public int BaseAmount { get; set; } [Max(100000000)] [Min(0)] [Display(Name = "Admin salary")] public int AdminAmount { get; set; } [Max(100000000)] [Min(0)] [Display(Name = "Eminent salary")] public int EminentAmount { get; set; } [Max(100000000)] [Min(0)] [Display(Name = "Promotion salary")] public int PromotionAmount { get; set; } [Required] [Max(100000000)] [Min(0)] [Display(Name = "Merit Incr.", ShortName = "Merit")] public int MeritIncrease { get; set; } [Required] [Max(100000000)] [Min(0)] [Display(Name = "Special Incr.", ShortName = "Special")] public int SpecialIncrease { get; set; } [Required] [Max(100000000)] [Min(0)] [Display(Name = "Eminent increase", ShortName = "Eminent")] public int EminentIncrease { get; set; } [StringLength(1024)] public string BaseSalaryAdjustmentNote { get; set; } [ForeignKey("MeritAdjustmentType")] [Display(Name = "Merit adjustment type")] public int MeritAdjustmentTypeId { get; set; } [StringLength(1024)] public string MeritAdjustmentNote { get; set; } [StringLength(1024)] public string SpecialAdjustmentNote { get; set; } [StringLength(1024)] public string Comments { get; set; } public FacultyType FacultyType { get; set; } public RankType RankType { get; set; } public AppointmentType AppointmentType { get; set; } public MeritAdjustmentType MeritAdjustmentType { get; set; } public LeaveType LeaveType { get; set; } public Person Person { get; set; } public ICollection<BaseSalaryAdjustment> BaseSalaryAdjustments { get; set; } public ICollection<SpecialSalaryAdjustment> SpecialSalaryAdjustments { get; set; } public ICollection<SalaryModification> Modifications { get; set; } [Display(Name = "Starting salary")] public int TotalAmount { get { return BaseAmount + AdminAmount + EminentAmount + PromotionAmount; } } [Display(Name = "New eminent salary")] public int NewEminentAmount { get { try { return EminentAmount + (EminentAmount / TotalAmount) * (MeritIncrease + SpecialIncrease) + EminentIncrease; } catch (DivideByZeroException ex) { return 0; } } } [Display(Name = "New salary")] public int NewTotalAmount { get { return TotalAmount + MeritIncrease + SpecialIncrease + EminentIncrease; } } [Display(Name = "Total % Incr.")] public decimal TotalChange { get { try { return Math.Round(((decimal.Divide(NewTotalAmount, TotalAmount) - 1) * 100), 2); } catch (DivideByZeroException ex) { return 0; } } } } }
28.469274
100
0.551217
38bbe12e83d7129ab8c0bc9c1fa68397cab28fda
1,349
php
PHP
app/Http/Controllers/BackEnd/News/TagsController.php
sophanna999/smartcode_mef
bb4259294a105570ea138640ceb5861f939a5eee
[ "MIT" ]
null
null
null
app/Http/Controllers/BackEnd/News/TagsController.php
sophanna999/smartcode_mef
bb4259294a105570ea138640ceb5861f939a5eee
[ "MIT" ]
null
null
null
app/Http/Controllers/BackEnd/News/TagsController.php
sophanna999/smartcode_mef
bb4259294a105570ea138640ceb5861f939a5eee
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\BackEnd\News; use App\Http\Controllers\BackendController; use App\Models\BackEnd\News\TagsModel; use Illuminate\Http\Request; use Config; class TagsController extends BackendController { public function __construct(){ parent::__construct(); $this->constant = Config::get('constant'); $this->tags = new tagsModel(); } public function getIndex(){ return view($this->viewFolder.'.news.tags.index')->with($this->data); } public function postIndex(Request $request){ return $this->tags->getDataGrid($request->all()); } public function postNew(Request $request){ return $this->loadView($request); } public function postEdit(Request $request){ return $this->loadView($request); } private function loadView(Request $request){ $id = intval($request->Id); $this->data['user_mood'] = json_encode($this->constant['user_mood']); $this->data['row'] = $this->tags->getDataByRowId($id); return view($this->viewFolder.'.news.tags.new')->with($this->data); } public function postSave(Request $request){ return $this->tags->postSave($request->all()); } public function postDelete(Request $request){ $listId = isset($request['Id']) ? $request['Id']:''; return $this->tags->postDelete($listId); } }
31.372093
77
0.661231
beb25b0716c7434658ae032f0cf8a0b003f7a43e
460
ts
TypeScript
src/modules/functions/edit/Shift.test.ts
design-automation/mobius-sim-funcs
8e7a8a7b0f7f4d0f3f28746a2127e24500475214
[ "MIT" ]
null
null
null
src/modules/functions/edit/Shift.test.ts
design-automation/mobius-sim-funcs
8e7a8a7b0f7f4d0f3f28746a2127e24500475214
[ "MIT" ]
null
null
null
src/modules/functions/edit/Shift.test.ts
design-automation/mobius-sim-funcs
8e7a8a7b0f7f4d0f3f28746a2127e24500475214
[ "MIT" ]
null
null
null
import { SIMFuncs } from '../../../index' import * as qEnum from '../query/_enum'; const sf = new SIMFuncs(); const r_posis = sf.pattern.Rectangle([0, 0, 0],2); const r_pgon = sf.make.Polygon(r_posis); const check1 = sf.query.Get(qEnum._EEntType.EDGE, null); sf.edit.Shift(r_pgon, 2); const check2 = sf.query.Get(qEnum._EEntType.EDGE, null); test('Check that shift has shifted edges', () => { //@ts-ignore expect(check2).not.toEqual(check1) });
25.555556
56
0.665217
4612946c1e1230c0e6c33fa83bfc328e40e6d1f8
2,640
dart
Dart
lib/model/payload/category.dart
mjstel/health_kit_reporter
e35bd944a5b978281a2bfa581134323a82b20a74
[ "MIT" ]
null
null
null
lib/model/payload/category.dart
mjstel/health_kit_reporter
e35bd944a5b978281a2bfa581134323a82b20a74
[ "MIT" ]
null
null
null
lib/model/payload/category.dart
mjstel/health_kit_reporter
e35bd944a5b978281a2bfa581134323a82b20a74
[ "MIT" ]
null
null
null
import 'device.dart'; import 'sample.dart'; import 'source_revision.dart'; /// Equivalent of [Category] /// from [HealthKitReporter] https://cocoapods.org/pods/HealthKitReporter /// /// Supports [map] representation. /// /// Has a [Category.fromJson] constructor /// to create instances from JSON payload coming from iOS native code. /// And supports multiple object creation by [collect] method from JSON list. /// /// Requires [CategoryType] permissions provided. /// class Category extends Sample<CategoryHarmonized> { const Category( String uuid, String identifier, num startTimestamp, num endTimestamp, Device device, SourceRevision sourceRevision, CategoryHarmonized harmonized, ) : super( uuid, identifier, startTimestamp, endTimestamp, device, sourceRevision, harmonized, ); /// General map representation /// @override Map<String, dynamic> get map => { 'uuid': uuid, 'identifier': identifier, 'startTimestamp': startTimestamp, 'endTimestamp': endTimestamp, 'device': device.map, 'sourceRevision': sourceRevision.map, 'harmonized': harmonized.map, }; /// General constructor from JSON payload /// Category.fromJson(Map<String, dynamic> json) : super.fromJson(json, harmonized: CategoryHarmonized.fromJson(json['harmonized'])); /// Simplifies creating a list of objects from JSON payload. /// static List<Category> collect(List<dynamic> list) { final samples = <Category>[]; for (final Map<String, dynamic> map in list) { final sample = Category.fromJson(map); samples.add(sample); } return samples; } } /// Equivalent of [Category.Harmonized] /// from [HealthKitReporter] https://cocoapods.org/pods/HealthKitReporter /// /// Supports [map] representation. /// /// Has a [CategoryHarmonized.fromJson] constructor /// to create instances from JSON payload coming from iOS native code. /// class CategoryHarmonized { const CategoryHarmonized( this.value, this.description, this.metadata, ); final num value; final String description; final Map<String, dynamic> metadata; /// General map representation /// Map<String, dynamic> get map => { 'value': value, 'description': description, 'metadata': metadata, }; /// General constructor from JSON payload /// CategoryHarmonized.fromJson(Map<String, dynamic> json) : value = json['value'], description = json['description'], metadata = json['metadata']; }
26.4
77
0.655682
2cfb9af139ad425a03cf71bd0daefa032bb9e9dd
1,568
cpp
C++
6 复试/1 机试/资料/清华计算机考研机试/2018/cong.cpp
ladike/912_project
5178c1c93ac6ca30ffc72dd689f5c6932704b4ab
[ "MIT" ]
1
2022-03-02T16:05:49.000Z
2022-03-02T16:05:49.000Z
6 复试/1 机试/资料/清华计算机考研机试/2018/cong.cpp
ladike/912_project
5178c1c93ac6ca30ffc72dd689f5c6932704b4ab
[ "MIT" ]
null
null
null
6 复试/1 机试/资料/清华计算机考研机试/2018/cong.cpp
ladike/912_project
5178c1c93ac6ca30ffc72dd689f5c6932704b4ab
[ "MIT" ]
null
null
null
# include<iostream> # include<map> # include<vector> using namespace std; typedef struct{int x,y;} position; typedef struct{int id,f;} idfight; typedef struct{int id;position p;int d;int f;bool live;} cong; typedef vector<cong> conglist; conglist all_cong; map<int,vector<idfight> >war_map; int n,m,k,times; void init(){ cin>>n>>m>>k; for(int i=0;i<n;i++){ int x,y,d,f; cin >> x >>y>>d>>f; cong c1 ={i,{x,y},d,f,1}; all_cong.push_back(c1); } cin >> times; } void action(cong &c){ if(c.live){ switch(c.d){ case 0: if(c.p.y==m) c.d=1;else c.p.y++;break; case 1: if(c.p.y==1) c.d=0;else c.p.y--;break; case 2: if(c.p.x==1) c.d=3;else c.p.x--;break; case 3: if(c.p.y==n) c.d=2;else c.p.x++;break; default:;break; } int pi = c.p.x*1000+c.p.y; idfight idf = {c.id,c.f}; war_map[pi].push_back(idf); } } void printans(){ for(vector<cong>::iterator i = all_cong.begin();i!=all_cong.end();i++) cout<<(*i).p.y<<" "<<(*i).p.x<<endl; } void fight(){ map<int,vector<idfight> >::iterator it; it = war_map.begin(); while(it!=war_map.end()){ if((*it).second.size()>1){ int max = 0; for(vector<idfight>::iterator i = (*it).second.begin();i!=(*it).second.end();i++){ if((*i).f>max)max = (*i).f; } for(vector<idfight>::iterator i = (*it).second.begin();i!=(*it).second.end();i++){ if((*i).f<max) all_cong[(*i).id].live=0; } } it++; } } int main() { init(); while(times--){ for(vector<cong>::iterator i = all_cong.begin();i!=all_cong.end();i++){ action(*i); } fight(); war_map.clear(); } printans(); return 0; }
23.402985
87
0.586097
db8123183861d85991ad2a0ae02cc0823d427760
2,778
php
PHP
resources/views/manage/settings/roles-row.blade.php
mhrezaei/fiche
22ec179578a7aadeb8272fdd1aa16368ee4162fb
[ "MIT" ]
null
null
null
resources/views/manage/settings/roles-row.blade.php
mhrezaei/fiche
22ec179578a7aadeb8272fdd1aa16368ee4162fb
[ "MIT" ]
null
null
null
resources/views/manage/settings/roles-row.blade.php
mhrezaei/fiche
22ec179578a7aadeb8272fdd1aa16368ee4162fb
[ "MIT" ]
null
null
null
@include('manage.frame.widgets.grid-rowHeader') {{-- |-------------------------------------------------------------------------- | Title |-------------------------------------------------------------------------- | --}} <td> @include("manage.frame.widgets.grid-text" , [ 'text' => $model->title, 'link' => "modal:manage/upstream/edit/role/-id-", 'icon' => $model->icon, ]) </td> {{-- |-------------------------------------------------------------------------- | People Count |-------------------------------------------------------------------------- | --}} <td> @include("manage.frame.widgets.grid-text" , [ 'condition' => $count = $model->users()->count() , 'text' => number_format($count) .' '.trans('people.person'), 'link' => $model->trashed() ? '' : "url:$model->users_browse_link" , ] ) @include("manage.frame.widgets.grid-text" , [ 'condition' => !$count, 'text' => trans('forms.general.nobody') , 'link' => $model->trashed() ? '' : "url:$model->users_browse_link" , ] ) </td> {{-- |-------------------------------------------------------------------------- | Status |-------------------------------------------------------------------------- | --}} <td> @if($model->isDefault()) @include("manage.frame.widgets.grid-badge" , [ 'icon' => "check-square-o", 'text' => trans('people.default_role') , 'color' => "primary" , 'class' => "text-white" , ] ) @else @include("manage.frame.widgets.grid-badge" , [ 'icon' => trans("forms.status_icon.$model->status"), 'text' => trans("forms.status_text.$model->status"), 'link' => 'modal:manage/upstream/edit/role-activeness/-id-' , 'color' => trans("forms.status_color.$model->status"), ]) @endif @if($model->is_admin) @include("manage.frame.widgets.grid-badge" , [ 'icon' => "user-secret", 'text' => trans('people.is_admin') , 'color' => "warning" , ] ) @endif </td> {{-- |-------------------------------------------------------------------------- | Actions |-------------------------------------------------------------------------- | --}} @include("manage.frame.widgets.grid-actionCol" , [ 'refresh_action' => false , "actions" => [ ['pencil' , trans('forms.button.edit') , "modal:manage/upstream/edit/role/-id-" ], ['taxi' , trans('posts.types.locale_titles') , 'modal:manage/upstream/edit/role-titles/-id-' ], ['hand-pointer-o' , trans('people.choose_as_default_role') , 'modal:manage/upstream/edit/role-default/-id-'], ['trash-o' , trans('forms.button.soft_delete') , 'modal:manage/upstream/edit/role-activeness/-id-' , !$model->trashed() and !$model->isDefault() , $model::adminRoles()] , ['recycle' , trans('forms.button.undelete') , 'modal:manage/upstream/edit/role-activeness/-id-' , $model->trashed()], ] ])
31.568182
173
0.472282
96cc5c62d02a2f443c1a9ff48b95dee2037f4f3c
3,405
rb
Ruby
spec/requests/access_tokens_spec.rb
omisego/sample-server
26711a5a1684569c1e166bda6a5b21bc5b61be89
[ "Apache-2.0" ]
8
2018-02-28T09:19:12.000Z
2019-05-07T19:45:52.000Z
spec/requests/access_tokens_spec.rb
omisego/sample-server
26711a5a1684569c1e166bda6a5b21bc5b61be89
[ "Apache-2.0" ]
null
null
null
spec/requests/access_tokens_spec.rb
omisego/sample-server
26711a5a1684569c1e166bda6a5b21bc5b61be89
[ "Apache-2.0" ]
4
2018-03-23T09:29:56.000Z
2019-05-07T17:03:49.000Z
require 'rails_helper' RSpec.describe 'access tokens', type: :request do let(:api_key) { create(:api_key) } let(:keys) { Base64.encode64("#{api_key.id}:#{api_key.key}") } let(:headers) { { 'HTTP_AUTHORIZATION' => "OMGShop #{keys}" } } describe '/api/login' do include_examples 'client auth', '/api/login' context 'authenticated' do context 'invalid credentials' do before do VCR.use_cassette('access_token/authenticated/login/invalid') do post '/api/login', headers: headers, params: { email: '[email protected]', password: 'password' } end end it "receives a json with the 'success' root key" do expect(json_body['success']).to eq false end it 'receives an invalid credentials error' do expect(json_body['data']).to eq( 'object' => 'error', 'code' => 'client:invalid_credentials', 'description' => 'Incorrect username/password combination.', 'messages' => nil ) end end context 'valid credentials' do let(:params) do { email: '[email protected]', password: 'password' } end before do VCR.use_cassette('user/authenticated/login/valid') do post '/api/signup', headers: headers, params: params expect(json_body['success']).to eq true post '/api/login', headers: headers, params: params end end it "receives a json with the 'success' root key" do expect(json_body['success']).to eq true end it "receives a json with the 'version' root key" do expect(json_body['version']).to eq '1' end it "receives a json with the 'data' root key" do expect(json_body['data']).to_not be nil end it 'receives an auth token back' do expect(json_body['data']['object']).to eq('authentication_token') expect(json_body['data']['user_id']).to eq(User.last.id.to_s) expect(json_body['data']['authentication_token']).not_to eq nil expect(json_body['data']['omisego_authentication_token']).not_to eq nil end end end end describe '/api/logout' do include_examples 'client auth', '/api/logout' context 'user authenticated' do let(:user) { create(:user) } let(:api_key) { create(:api_key) } let(:access_token) do token = create(:access_token, user: user, api_key: api_key) token.generate_token end let(:keys) do keys_string = "#{api_key.id}:#{api_key.key}" tokens_string = "#{user.id}:#{access_token}" Base64.encode64("#{keys_string}:#{tokens_string}") end let(:headers) { { 'HTTP_AUTHORIZATION' => "OMGShop #{keys}" } } before { post '/api/logout', headers: headers } it "receives a json with the 'success' root key" do expect(json_body['success']).to eq true end it "receives a json with the 'version' root key" do expect(json_body['version']).to eq '1' end it "receives a json with the 'data' root key" do expect(json_body['data']).to eq({}) end it 'deletes the access token' do expect(AccessToken.count).to eq 0 end end end end
30.132743
81
0.575624
248549cab2ffe9d8b8633d6782fb819fbf31ecd3
2,609
php
PHP
vendor/php-di/php-di/tests/UnitTest/Definition/Resolver/ArrayResolverTest.php
james-ransom/mysql-to-google-bigquery
ee5f6f3a8a380b797b902e538021adb78d1b0dcc
[ "MIT" ]
1
2019-07-08T00:20:00.000Z
2019-07-08T00:20:00.000Z
vendor/php-di/php-di/tests/UnitTest/Definition/Resolver/ArrayResolverTest.php
james-ransom/mysql-to-google-bigquery
ee5f6f3a8a380b797b902e538021adb78d1b0dcc
[ "MIT" ]
null
null
null
vendor/php-di/php-di/tests/UnitTest/Definition/Resolver/ArrayResolverTest.php
james-ransom/mysql-to-google-bigquery
ee5f6f3a8a380b797b902e538021adb78d1b0dcc
[ "MIT" ]
null
null
null
<?php namespace DI\Test\UnitTest\Definition\Resolver; use DI\Definition\AliasDefinition; use DI\Definition\ArrayDefinition; use DI\Definition\ObjectDefinition; use DI\Definition\Resolver\ArrayResolver; use DI\Definition\Resolver\DefinitionResolver; use EasyMock\EasyMock; use PHPUnit_Framework_MockObject_MockObject; /** * @covers \DI\Definition\Resolver\ArrayResolver */ class ArrayResolverTest extends \PHPUnit_Framework_TestCase { use EasyMock; /** * @var DefinitionResolver|PHPUnit_Framework_MockObject_MockObject */ private $parentResolver; /** * @var ArrayResolver */ private $resolver; public function setUp() { $this->parentResolver = $this->easyMock(DefinitionResolver::class); $this->resolver = new ArrayResolver($this->parentResolver); } /** * @test */ public function should_resolve_array_of_values() { $definition = new ArrayDefinition('foo', [ 'bar', 42, ]); $value = $this->resolver->resolve($definition); $this->assertEquals(['bar', 42], $value); } /** * @test */ public function should_resolve_nested_definitions() { $this->parentResolver->expects($this->exactly(2)) ->method('resolve') ->withConsecutive( $this->isInstanceOf(AliasDefinition::class), $this->isInstanceOf(ObjectDefinition::class) ) ->willReturnOnConsecutiveCalls(42, new \stdClass()); $definition = new ArrayDefinition('foo', [ 'bar', \DI\get('bar'), \DI\object('bar'), ]); $value = $this->resolver->resolve($definition); $this->assertEquals(['bar', 42, new \stdClass()], $value); } /** * @test */ public function resolve_should_preserve_keys() { $definition = new ArrayDefinition('foo', [ 'hello' => 'world', ]); $value = $this->resolver->resolve($definition); $this->assertEquals(['hello' => 'world'], $value); } /** * @test * @expectedException \DI\DependencyException * @expectedExceptionMessage Error while resolving foo[0]. This is a message */ public function should_throw_with_a_nice_message() { $this->parentResolver->expects($this->once()) ->method('resolve') ->willThrowException(new \Exception('This is a message')); $this->resolver->resolve(new ArrayDefinition('foo', [ \DI\get('bar'), ])); } }
24.847619
80
0.592181
14157ec7ef78413a969490e1de8cf0be88c07725
218
ts
TypeScript
src/modules/atom/RadixEmission.ts
jaeminkim-com/radixdlt-js
4a25f83dff8fd32336c80ae9daaead0565b8a85a
[ "MIT" ]
null
null
null
src/modules/atom/RadixEmission.ts
jaeminkim-com/radixdlt-js
4a25f83dff8fd32336c80ae9daaead0565b8a85a
[ "MIT" ]
null
null
null
src/modules/atom/RadixEmission.ts
jaeminkim-com/radixdlt-js
4a25f83dff8fd32336c80ae9daaead0565b8a85a
[ "MIT" ]
null
null
null
import { RadixConsumable } from '../RadixAtomModel' export default class RadixEmission extends RadixConsumable { public static SERIALIZER = 1782261127 constructor(json?: object) { super(json) } }
21.8
60
0.706422
5d04df8ec0c0ac777f13f832d2da1fea6659ef6c
7,106
hpp
C++
dakota-6.3.0.Windows.x86/include/DLSfuncs.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/DLSfuncs.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/DLSfuncs.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
#ifndef DLSfuncs.hpp #define DLSfuncs.hpp #include <stdio.h> #include <iostream> #include "dakota_data_types.hpp" namespace Dakota { class Optimizer1; // treated as anonymous here struct Opt_Info { char *begin; // I/O, updated by dlsolver_option for use in next dlsolver_option call char *name; // out: option name char *val; // out: start of value (null if no value found) // output _len values are int rather than size_t for format %.*s int name_len; // out: length of name int val_len; // out: length of value (0 if val is null) int all_len; // out: length of entire name = value phrase int eq_repl; // in: change '=' to this value int und_repl; // in: change '_' to this value // constructor... inline Opt_Info(char *begin1, int undval = ' ', int eqval = ' '): begin(begin1), eq_repl(eqval), und_repl(undval) {} }; struct Dakota_probsize { int n_var; // number of continuous variables int n_linc; // number of linear constraints int n_nlinc; // number of nonlinear constraints int n_obj; // number of objectives int maxfe; // maximum function evaluations int numgflag; // numerical gradient flag int objrecast; // local objective recast flag }; struct Dakota_funcs { int (*Fprintf)(FILE*, const char*, ...); void (*abort_handler1)(int); int (*dlsolver_option1)(Opt_Info*); RealVector const * (*continuous_lower_bounds)(Optimizer1*); RealVector const * (*continuous_upper_bounds)(Optimizer1*); RealVector const * (*nonlinear_ineq_constraint_lower_bounds)(Optimizer1*); RealVector const * (*nonlinear_ineq_constraint_upper_bounds)(Optimizer1*); RealVector const * (*nonlinear_eq_constraint_targets)(Optimizer1*); RealVector const * (*linear_ineq_constraint_lower_bounds)(Optimizer1*); RealVector const * (*linear_ineq_constraint_upper_bounds)(Optimizer1*); RealVector const * (*linear_eq_constraint_targets)(Optimizer1*); RealMatrix const * (*linear_ineq_constraint_coeffs)(Optimizer1*); RealMatrix const * (*linear_eq_constraint_coeffs)(Optimizer1*); void (*ComputeResponses1)(Optimizer1*, int mode, int n, double *x); // ComputeResponses uses x[i], 0 <= i < n void (*GetFuncs1)(Optimizer1*, int m0, int m1, double *f); // GetFuncs sets f[i] <-- response(m+i), m0 <= i < m1 void (*GetGrads1)(Optimizer1*, int m0, int m1, int n, int is, int js, double *g); // g[(i-m0)*is + j*js] <-- partial(Response i)/partial(var j), // m0 <= i < m1, 0 <= j < n void (*GetContVars)(Optimizer1*, int n, double *x); void (*SetBestContVars)(Optimizer1*, int n, double *x); // set best continuous var values void (*SetBestDiscVars)(Optimizer1*, int n, int *x); // set best discrete var values void (*SetBestRespFns)(Optimizer1*, int n, double *x); // set best resp func values double (*get_real)(Optimizer1*, const char*); // for probDescDB.get_real() int (*get_int) (Optimizer1*, const char*); // for probDescDB.get_int() bool (*get_bool)(Optimizer1*, const char*); // for probDescDB.get_bool() Dakota_probsize *ps; std::ostream *dakota_cerr, *dakota_cout; FILE *Stderr; }; #ifdef NO_DAKOTA_DLSOLVER_FUNCS_INLINE extern int dlsolver_option(Opt_Info *); #else //!NO_DAKOTA_DLSOLVER_FUNCS_INLINE extern Dakota_funcs *DF; #undef Cout #define Cout (*DF->dakota_cout) #if 0 // "inline" is not inlined at low optimization levels, // causing confusion in gdb. It's less confusing to use #define; // we get type checking in this case much as with inline. inline void abort_handler(int n) { DF->abort_handler1(n); } inline int dlsolver_option(Opt_Info *oi) { return DF->dlsolver_option1(oi); } inline RealVector const * continuous_lower_bounds(Optimizer1 *o) { return DF->continuous_lower_bounds(o); } inline RealVector const * continuous_upper_bounds(Optimizer1 *o) { return DF->continuous_upper_bounds(o); } inline RealVector const * nonlinear_ineq_constraint_lower_bounds(Optimizer1 *o) { return DF->nonlinear_ineq_constraint_lower_bounds(o); } inline RealVector const * nonlinear_ineq_constraint_upper_bounds(Optimizer1 *o) { return DF->nonlinear_ineq_constraint_upper_bounds(o); } inline RealVector const * nonlinear_eq_constraint_targets(Optimizer1 *o) { return DF->nonlinear_eq_constraint_targets(o); } inline RealVector const * linear_ineq_constraint_lower_bounds(Optimizer1 *o) { return DF->linear_ineq_constraint_lower_bounds(o); } inline RealVector const * linear_ineq_constraint_upper_bounds(Optimizer1 *o) { return DF->linear_ineq_constraint_upper_bounds(o); } inline RealVector const * linear_eq_constraint_targets(Optimizer1 *o) { return DF->linear_eq_constraint_targets(o); } inline RealMatrix const * linear_ineq_constraint_coeffs(Optimizer1 *o) { return DF->linear_ineq_constraint_coeffs(o); } inline RealMatrix const * linear_eq_constraint_coeffs(Optimizer1 *o) { return DF->linear_eq_constraint_coeffs(o); } inline void ComputeResponses(Optimizer1 *o, int mode, int n, double *x) { DF->ComputeResponses1(o, mode, n, x); } inline void GetFuncs(Optimizer1 *o, int m0, int m1, double *f) { DF->GetFuncs1(o, m0, m1, f); } inline void GetGrads(Optimizer1 *o, int m0, int m1, int n, int is, int js, double *g) { DF->GetGrads1(o, m0, m1, n, is, js, g); } inline void GetContVars(Optimizer1 *o, int n, double *x) { DF->GetContVars(o, n, x); } inline void SetBestContVars(Optimizer1 *o, int n, double *x) { DF->SetBestContVars(o, n, x); } inline void SetBestRespFns(Optimizer1 *o, int n, double *x) { DF->SetBestRespFns(o, n, x); } #else // use #define to really inline #define abort_handler(n) DF->abort_handler1(n) #define dlsolver_option(oi) DF->dlsolver_option1(oi) #define continuous_lower_bounds(o) DF->continuous_lower_bounds(o) #define continuous_upper_bounds(o) DF->continuous_upper_bounds(o) #define nonlinear_ineq_constraint_lower_bounds(o) DF->nonlinear_ineq_constraint_lower_bounds(o) #define nonlinear_ineq_constraint_upper_bounds(o) DF->nonlinear_ineq_constraint_upper_bounds(o) #define nonlinear_eq_constraint_targets(o) DF->nonlinear_eq_constraint_targets(o) #define linear_ineq_constraint_lower_bounds(o) DF->linear_ineq_constraint_lower_bounds(o) #define linear_ineq_constraint_upper_bounds(o) DF->linear_ineq_constraint_upper_bounds(o) #define linear_eq_constraint_targets(o) DF->linear_eq_constraint_targets(o) #define linear_ineq_constraint_coeffs(o) DF->linear_ineq_constraint_coeffs(o) #define linear_eq_constraint_coeffs(o) DF->linear_eq_constraint_coeffs(o) #define ComputeResponses(o,mode,n,x) DF->ComputeResponses1(o, mode, n, x) #define GetFuncs(o,m0,m1,f) DF->GetFuncs1(o, m0, m1, f) #define GetGrads(o,m0,m1,n,is,js,g) DF->GetGrads1(o, m0, m1, n, is, js, g) #define GetContVars(o,n,x) DF->GetContVars(o, n, x) #define SetBestContVars(o,n,x) DF->SetBestContVars(o, n, x) #define SetBestDiscVars(o,n,x) DF->SetBestDiscVars(o, n, x) #define SetBestRespFns(o,n,x) DF->SetBestRespFns(o, n, x) #endif #endif //NO_DAKOTA_DLSOLVER_FUNCS_INLINE typedef void (*dl_find_optimum_t)(void*, Optimizer1*, char*); typedef void (*dl_destructor_t)(void**); extern "C" void *dl_constructor(Optimizer1 *, Dakota_funcs*, dl_find_optimum_t *, dl_destructor_t *); } // namespace Dakota #endif //DLSfuncs.hpp
39.921348
101
0.753307
e1f1f39213fbd0b0812d3664a0f9b7629948fa12
621
gemspec
Ruby
b3s_emoticons.gemspec
b3s/b3s_emoticons
590e1c2248fb1f335fb7b6fcb8f0091fbb060879
[ "MIT" ]
null
null
null
b3s_emoticons.gemspec
b3s/b3s_emoticons
590e1c2248fb1f335fb7b6fcb8f0091fbb060879
[ "MIT" ]
null
null
null
b3s_emoticons.gemspec
b3s/b3s_emoticons
590e1c2248fb1f335fb7b6fcb8f0091fbb060879
[ "MIT" ]
null
null
null
# frozen_string_literal: true $LOAD_PATH.push File.expand_path("lib", __dir__) require "b3s_emoticons/version" Gem::Specification.new do |s| s.name = "b3s_emoticons" s.version = B3sEmoticons::VERSION s.authors = ["Inge Jørgensen"] s.email = ["[email protected]"] s.summary = "B3S Emoticons" s.description = "B3S Emoticons" s.homepage = "" s.license = "MIT" s.required_ruby_version = ">= 2.7.0" s.files = Dir[ "{app,config,db,lib,vendor}/**/*", "LICENSE.txt", "Rakefile", "README.md" ] s.add_development_dependency "rake" end
23
48
0.611916
df10e4ebbe3bcd6cd335d70c4c629029acddf84e
3,093
cs
C#
src/BizTalk.Common.Tests/Tracking/Messaging/ActivityFactoryFixture.cs
icraftsoftware/BizTalk.Factory
7584592b505299d0d689cb8a5d53135298e58dff
[ "Apache-2.0" ]
4
2020-02-17T12:54:47.000Z
2021-05-31T08:42:44.000Z
src/BizTalk.Common.Tests/Tracking/Messaging/ActivityFactoryFixture.cs
icraftsoftware/BizTalk.Factory
7584592b505299d0d689cb8a5d53135298e58dff
[ "Apache-2.0" ]
2
2019-10-22T20:29:14.000Z
2020-02-25T17:38:57.000Z
src/BizTalk.Common.Tests/Tracking/Messaging/ActivityFactoryFixture.cs
icraftsoftware/BizTalk.Factory
7584592b505299d0d689cb8a5d53135298e58dff
[ "Apache-2.0" ]
1
2018-05-31T13:40:05.000Z
2018-05-31T13:40:05.000Z
#region Copyright & License // Copyright © 2012 - 2013 François Chabot, Yves Dierick // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using Microsoft.BizTalk.Bam.EventObservation; using Microsoft.BizTalk.Component.Interop; using Microsoft.BizTalk.Message.Interop; using Moq; using NUnit.Framework; namespace Be.Stateless.BizTalk.Tracking.Messaging { [TestFixture] public class ActivityFactoryFixture { #region Setup/Teardown [SetUp] public void SetUp() { PipelineContextMock = new Mock<IPipelineContext>(); PipelineContextMock.Setup(pc => pc.GetEventStream()).Returns(new Mock<EventStream>().Object); } #endregion [Test] public void CreateMessagingStepReturnsRegularMessagingStep() { var messageMock = new Unit.Message.Mock<IBaseMessage>(); var factory = new ActivityFactory(PipelineContextMock.Object); Assert.That(factory.CreateMessagingStep(messageMock.Object), Is.TypeOf<MessagingStep>()); } [Test] public void CreateProcessReturnsRegularBatchReleaseProcess() { var messageMock = new Unit.Message.Mock<IBaseMessage>(); var factory = (IBatchProcessActivityFactory) new ActivityFactory(PipelineContextMock.Object); Assert.That(factory.CreateProcess(messageMock.Object, "name"), Is.TypeOf<BatchReleaseProcess>()); } [Test] public void CreateProcessReturnsRegularProcess() { var messageMock = new Unit.Message.Mock<IBaseMessage>(); var factory = new ActivityFactory(PipelineContextMock.Object); Assert.That(factory.CreateProcess(messageMock.Object, "name"), Is.TypeOf<Process>()); } [Test] public void FindMessagingStepReturnsMessagingStepReference() { var factory = new ActivityFactory(PipelineContextMock.Object); Assert.That(factory.FindMessagingStep(new TrackingContext { MessagingStepActivityId = "pseudo-activity-id" }), Is.TypeOf<MessagingStepReference>()); } [Test] public void FindProcessReturnsBatchReleaseProcessReference() { var factory = (IBatchProcessActivityFactory) new ActivityFactory(PipelineContextMock.Object); Assert.That(factory.FindProcess("pseudo-activity-id"), Is.TypeOf<BatchReleaseProcessReference>()); } [Test] public void FindProcessReturnsProcessReference() { var factory = new ActivityFactory(PipelineContextMock.Object); Assert.That(factory.FindProcess(new TrackingContext { ProcessActivityId = "pseudo-activity-id" }), Is.TypeOf<ProcessReference>()); } private Mock<IPipelineContext> PipelineContextMock { get; set; } } }
34.752809
152
0.741998
f5b8b4ef87f3fb64bb05515aa62f85a7149a65c0
10,859
go
Go
codegen/go/xr/63x/cisco_ios_xr_ip_udp_oper/udp_connection/nodes/node/pcb_details/pcb_detail/udp_sh_table_bag.pb.go
cisco-ie/cisco-proto
9cc3967cb1cabbb3e9f92f2c46ed96edf8a0a78b
[ "Apache-2.0" ]
6
2019-06-06T04:30:27.000Z
2021-02-21T22:41:00.000Z
codegen/go/xr/63x/cisco_ios_xr_ip_udp_oper/udp_connection/nodes/node/pcb_details/pcb_detail/udp_sh_table_bag.pb.go
cisco-ie/cisco-proto
9cc3967cb1cabbb3e9f92f2c46ed96edf8a0a78b
[ "Apache-2.0" ]
3
2019-04-01T23:07:32.000Z
2019-06-04T13:42:52.000Z
codegen/go/xr/63x/cisco_ios_xr_ip_udp_oper/udp_connection/nodes/node/pcb_details/pcb_detail/udp_sh_table_bag.pb.go
cisco-ie/cisco-proto
9cc3967cb1cabbb3e9f92f2c46ed96edf8a0a78b
[ "Apache-2.0" ]
1
2020-02-28T21:16:30.000Z
2020-02-28T21:16:30.000Z
/* Copyright 2019 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by protoc-gen-go. DO NOT EDIT. // source: udp_sh_table_bag.proto package cisco_ios_xr_ip_udp_oper_udp_connection_nodes_node_pcb_details_pcb_detail import ( fmt "fmt" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type UdpShTableBag_KEYS struct { NodeName string `protobuf:"bytes,1,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` PcbAddress string `protobuf:"bytes,2,opt,name=pcb_address,json=pcbAddress,proto3" json:"pcb_address,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UdpShTableBag_KEYS) Reset() { *m = UdpShTableBag_KEYS{} } func (m *UdpShTableBag_KEYS) String() string { return proto.CompactTextString(m) } func (*UdpShTableBag_KEYS) ProtoMessage() {} func (*UdpShTableBag_KEYS) Descriptor() ([]byte, []int) { return fileDescriptor_dbae815597458c95, []int{0} } func (m *UdpShTableBag_KEYS) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UdpShTableBag_KEYS.Unmarshal(m, b) } func (m *UdpShTableBag_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UdpShTableBag_KEYS.Marshal(b, m, deterministic) } func (m *UdpShTableBag_KEYS) XXX_Merge(src proto.Message) { xxx_messageInfo_UdpShTableBag_KEYS.Merge(m, src) } func (m *UdpShTableBag_KEYS) XXX_Size() int { return xxx_messageInfo_UdpShTableBag_KEYS.Size(m) } func (m *UdpShTableBag_KEYS) XXX_DiscardUnknown() { xxx_messageInfo_UdpShTableBag_KEYS.DiscardUnknown(m) } var xxx_messageInfo_UdpShTableBag_KEYS proto.InternalMessageInfo func (m *UdpShTableBag_KEYS) GetNodeName() string { if m != nil { return m.NodeName } return "" } func (m *UdpShTableBag_KEYS) GetPcbAddress() string { if m != nil { return m.PcbAddress } return "" } type UdpAddressType struct { AfName string `protobuf:"bytes,1,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"` Ipv4Address string `protobuf:"bytes,2,opt,name=ipv4_address,json=ipv4Address,proto3" json:"ipv4_address,omitempty"` Ipv6Address string `protobuf:"bytes,3,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UdpAddressType) Reset() { *m = UdpAddressType{} } func (m *UdpAddressType) String() string { return proto.CompactTextString(m) } func (*UdpAddressType) ProtoMessage() {} func (*UdpAddressType) Descriptor() ([]byte, []int) { return fileDescriptor_dbae815597458c95, []int{1} } func (m *UdpAddressType) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UdpAddressType.Unmarshal(m, b) } func (m *UdpAddressType) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UdpAddressType.Marshal(b, m, deterministic) } func (m *UdpAddressType) XXX_Merge(src proto.Message) { xxx_messageInfo_UdpAddressType.Merge(m, src) } func (m *UdpAddressType) XXX_Size() int { return xxx_messageInfo_UdpAddressType.Size(m) } func (m *UdpAddressType) XXX_DiscardUnknown() { xxx_messageInfo_UdpAddressType.DiscardUnknown(m) } var xxx_messageInfo_UdpAddressType proto.InternalMessageInfo func (m *UdpAddressType) GetAfName() string { if m != nil { return m.AfName } return "" } func (m *UdpAddressType) GetIpv4Address() string { if m != nil { return m.Ipv4Address } return "" } func (m *UdpAddressType) GetIpv6Address() string { if m != nil { return m.Ipv6Address } return "" } type UdpShTableBag struct { AfName string `protobuf:"bytes,50,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"` LocalProcessId uint32 `protobuf:"varint,51,opt,name=local_process_id,json=localProcessId,proto3" json:"local_process_id,omitempty"` LocalAddress *UdpAddressType `protobuf:"bytes,52,opt,name=local_address,json=localAddress,proto3" json:"local_address,omitempty"` ForeignAddress *UdpAddressType `protobuf:"bytes,53,opt,name=foreign_address,json=foreignAddress,proto3" json:"foreign_address,omitempty"` LocalPort uint32 `protobuf:"varint,54,opt,name=local_port,json=localPort,proto3" json:"local_port,omitempty"` ForeignPort uint32 `protobuf:"varint,55,opt,name=foreign_port,json=foreignPort,proto3" json:"foreign_port,omitempty"` ReceiveQueue uint32 `protobuf:"varint,56,opt,name=receive_queue,json=receiveQueue,proto3" json:"receive_queue,omitempty"` SendQueue uint32 `protobuf:"varint,57,opt,name=send_queue,json=sendQueue,proto3" json:"send_queue,omitempty"` VrfId uint32 `protobuf:"varint,58,opt,name=vrf_id,json=vrfId,proto3" json:"vrf_id,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UdpShTableBag) Reset() { *m = UdpShTableBag{} } func (m *UdpShTableBag) String() string { return proto.CompactTextString(m) } func (*UdpShTableBag) ProtoMessage() {} func (*UdpShTableBag) Descriptor() ([]byte, []int) { return fileDescriptor_dbae815597458c95, []int{2} } func (m *UdpShTableBag) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UdpShTableBag.Unmarshal(m, b) } func (m *UdpShTableBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UdpShTableBag.Marshal(b, m, deterministic) } func (m *UdpShTableBag) XXX_Merge(src proto.Message) { xxx_messageInfo_UdpShTableBag.Merge(m, src) } func (m *UdpShTableBag) XXX_Size() int { return xxx_messageInfo_UdpShTableBag.Size(m) } func (m *UdpShTableBag) XXX_DiscardUnknown() { xxx_messageInfo_UdpShTableBag.DiscardUnknown(m) } var xxx_messageInfo_UdpShTableBag proto.InternalMessageInfo func (m *UdpShTableBag) GetAfName() string { if m != nil { return m.AfName } return "" } func (m *UdpShTableBag) GetLocalProcessId() uint32 { if m != nil { return m.LocalProcessId } return 0 } func (m *UdpShTableBag) GetLocalAddress() *UdpAddressType { if m != nil { return m.LocalAddress } return nil } func (m *UdpShTableBag) GetForeignAddress() *UdpAddressType { if m != nil { return m.ForeignAddress } return nil } func (m *UdpShTableBag) GetLocalPort() uint32 { if m != nil { return m.LocalPort } return 0 } func (m *UdpShTableBag) GetForeignPort() uint32 { if m != nil { return m.ForeignPort } return 0 } func (m *UdpShTableBag) GetReceiveQueue() uint32 { if m != nil { return m.ReceiveQueue } return 0 } func (m *UdpShTableBag) GetSendQueue() uint32 { if m != nil { return m.SendQueue } return 0 } func (m *UdpShTableBag) GetVrfId() uint32 { if m != nil { return m.VrfId } return 0 } func init() { proto.RegisterType((*UdpShTableBag_KEYS)(nil), "cisco_ios_xr_ip_udp_oper.udp_connection.nodes.node.pcb_details.pcb_detail.udp_sh_table_bag_KEYS") proto.RegisterType((*UdpAddressType)(nil), "cisco_ios_xr_ip_udp_oper.udp_connection.nodes.node.pcb_details.pcb_detail.udp_address_type") proto.RegisterType((*UdpShTableBag)(nil), "cisco_ios_xr_ip_udp_oper.udp_connection.nodes.node.pcb_details.pcb_detail.udp_sh_table_bag") } func init() { proto.RegisterFile("udp_sh_table_bag.proto", fileDescriptor_dbae815597458c95) } var fileDescriptor_dbae815597458c95 = []byte{ // 390 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x93, 0xbf, 0x4f, 0xe3, 0x30, 0x14, 0xc7, 0x95, 0xab, 0xae, 0x77, 0x75, 0xda, 0x5e, 0x15, 0xa9, 0x77, 0x91, 0x4e, 0xa7, 0x2b, 0x65, 0xc9, 0x94, 0xa1, 0x2d, 0xe5, 0xc7, 0xc6, 0xc0, 0x50, 0x21, 0x21, 0x28, 0x62, 0x40, 0x0c, 0x96, 0x63, 0xbf, 0x14, 0x4b, 0x69, 0xec, 0xda, 0x69, 0x04, 0x1b, 0x03, 0x7f, 0x36, 0x03, 0xb2, 0xe3, 0x54, 0xa1, 0x33, 0x2c, 0x91, 0xf5, 0x7d, 0x9f, 0x7c, 0xbf, 0xcf, 0xef, 0xc9, 0xe8, 0xf7, 0x96, 0x49, 0xac, 0x1f, 0x71, 0x41, 0x92, 0x0c, 0x70, 0x42, 0x56, 0xb1, 0x54, 0xa2, 0x10, 0xc1, 0x82, 0x72, 0x4d, 0x05, 0xe6, 0x42, 0xe3, 0x27, 0x85, 0xb9, 0xc4, 0x86, 0x13, 0x12, 0x54, 0x6c, 0x0e, 0x54, 0xe4, 0x39, 0xd0, 0x82, 0x8b, 0x3c, 0xce, 0x05, 0x03, 0x6d, 0xbf, 0xb1, 0xa4, 0x09, 0x66, 0x50, 0x10, 0x9e, 0xe9, 0xc6, 0x79, 0x7c, 0x87, 0x86, 0xfb, 0x21, 0xf8, 0xf2, 0xe2, 0xfe, 0x36, 0xf8, 0x8b, 0x3a, 0xe6, 0x3f, 0x9c, 0x93, 0x35, 0x84, 0xde, 0xc8, 0x8b, 0x3a, 0xcb, 0x9f, 0x46, 0xb8, 0x22, 0x6b, 0x08, 0xfe, 0x23, 0xdf, 0x78, 0x10, 0xc6, 0x14, 0x68, 0x1d, 0x7e, 0xb3, 0x65, 0x24, 0x69, 0x72, 0x5e, 0x29, 0xe3, 0x0d, 0x1a, 0x18, 0x5b, 0x07, 0xe0, 0xe2, 0x59, 0x42, 0xf0, 0x07, 0xfd, 0x20, 0x69, 0xd3, 0xaf, 0x4d, 0x52, 0xeb, 0x76, 0x80, 0xba, 0x5c, 0x96, 0xb3, 0x3d, 0x3b, 0xdf, 0x68, 0xce, 0xcf, 0x21, 0xf3, 0x1d, 0xd2, 0xda, 0x21, 0xf3, 0x3a, 0xf2, 0xad, 0x55, 0x65, 0x36, 0xaf, 0xd2, 0xcc, 0x9c, 0x7c, 0xc8, 0x8c, 0xd0, 0x20, 0x13, 0x94, 0x64, 0x58, 0x2a, 0x41, 0x4d, 0x8b, 0x9c, 0x85, 0xd3, 0x91, 0x17, 0xf5, 0x96, 0x7d, 0xab, 0x5f, 0x57, 0xf2, 0x82, 0x05, 0x2f, 0x1e, 0xea, 0x55, 0x68, 0x1d, 0x3e, 0x1b, 0x79, 0x91, 0x3f, 0x79, 0x88, 0x3f, 0x6d, 0x0b, 0xf1, 0xfe, 0xac, 0x96, 0x5d, 0x9b, 0x58, 0xdf, 0xfe, 0xd5, 0x43, 0xbf, 0x52, 0xa1, 0x80, 0xaf, 0xf2, 0x5d, 0x13, 0x47, 0x5f, 0xdf, 0x44, 0xdf, 0x65, 0xd6, 0x6d, 0xfc, 0x43, 0xc8, 0xcd, 0x4c, 0xa8, 0x22, 0x9c, 0xdb, 0x69, 0x75, 0xaa, 0x69, 0x09, 0x55, 0x98, 0x1d, 0xd5, 0x4d, 0x5a, 0xe0, 0xd8, 0x02, 0xbe, 0xd3, 0x2c, 0x72, 0x88, 0x7a, 0x0a, 0x28, 0xf0, 0x12, 0xf0, 0x66, 0x0b, 0x5b, 0x08, 0x4f, 0x2c, 0xd3, 0x75, 0xe2, 0x8d, 0xd1, 0x4c, 0x8c, 0x86, 0x9c, 0x39, 0xe2, 0xb4, 0x8a, 0x31, 0x4a, 0x55, 0x1e, 0xa2, 0x76, 0xa9, 0x52, 0xb3, 0xaf, 0x33, 0x5b, 0xfa, 0x5e, 0xaa, 0x74, 0xc1, 0x92, 0xb6, 0x7d, 0x1a, 0xd3, 0xf7, 0x00, 0x00, 0x00, 0xff, 0xff, 0x58, 0xdb, 0x2e, 0x54, 0x34, 0x03, 0x00, 0x00, }
38.782143
147
0.718851
e7074a75ed9a92f427b2b63f8b5b558f43580697
118
php
PHP
app/Services/Notifications/Exceptions/UserDoesNotHaveNumberException.php
aliseymi/Notification_Service
33cfa8b6c90b7c2392d7d9a0bcb3a48619d85289
[ "MIT" ]
null
null
null
app/Services/Notifications/Exceptions/UserDoesNotHaveNumberException.php
aliseymi/Notification_Service
33cfa8b6c90b7c2392d7d9a0bcb3a48619d85289
[ "MIT" ]
null
null
null
app/Services/Notifications/Exceptions/UserDoesNotHaveNumberException.php
aliseymi/Notification_Service
33cfa8b6c90b7c2392d7d9a0bcb3a48619d85289
[ "MIT" ]
null
null
null
<?php namespace App\Services\Notifications\Exceptions; class UserDoesNotHaveNumberException extends \Exception { }
13.111111
55
0.822034
32fbff890d88a6394f4f3c086e5aee123a41ab40
1,425
lua
Lua
[FE] Kill All [Need Sword].lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
70
2021-02-09T17:21:32.000Z
2022-03-28T12:41:42.000Z
[FE] Kill All [Need Sword].lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
4
2021-08-19T22:05:58.000Z
2022-03-19T18:58:01.000Z
[FE] Kill All [Need Sword].lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
325
2021-02-26T22:23:41.000Z
2022-03-31T19:36:12.000Z
-- Objects local ScreenGui = Instance.new("ScreenGui") local Frame = Instance.new("Frame") local TextButton = Instance.new("TextButton") -- Properties ScreenGui.Parent = game.CoreGui Frame.Parent = ScreenGui Frame.BackgroundColor3 = Color3.new(1, 0.388235, 0.368627) Frame.BorderColor3 = Color3.new(0.67451, 0.211765, 0.152941) Frame.Position = UDim2.new(0.293040276, 0, 0.491666675, 0) Frame.Size = UDim2.new(0.106227107, 0, 0.0833333284, 0) Frame.Active = true Frame.Draggable = true TextButton.Parent = Frame TextButton.BackgroundColor3 = Color3.new(1, 1, 1) TextButton.BackgroundTransparency = 0.80000001192093 TextButton.Position = UDim2.new(0.103524067, 0, 0.200333327, 0) TextButton.Size = UDim2.new(0.793684483, 0, 0.601000011, 0) TextButton.Font = Enum.Font.SourceSansLight TextButton.FontSize = Enum.FontSize.Size14 TextButton.Text = "Freeze!" TextButton.TextScaled = true TextButton.TextSize = 14 TextButton.TextWrapped = true run = false TextButton.MouseButton1Click:connect(function() run = not run local function tp() for i, player in ipairs(game.Players:GetChildren()) do if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then player.Character.HumanoidRootPart.CFrame = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame + game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame.lookVector * 1 end end end if run then while wait() do if run then tp() end end end end)
29.6875
177
0.78386
e2a7ab88cf63fb3e1d0e4cc1c45e4b7f59a5f9fe
392
js
JavaScript
packages/ipfs-cli/src/commands/cid.js
kvutien/js-ipfs
54d1ed33f5974c4e7616138560bae559ee99cda4
[ "Apache-2.0", "MIT" ]
1
2021-06-21T20:45:43.000Z
2021-06-21T20:45:43.000Z
packages/ipfs-cli/src/commands/cid.js
kvutien/js-ipfs
54d1ed33f5974c4e7616138560bae559ee99cda4
[ "Apache-2.0", "MIT" ]
1
2021-04-18T15:04:04.000Z
2021-04-18T15:04:04.000Z
packages/ipfs-cli/src/commands/cid.js
yurtsiv/js-ipfs
74bfce3c12f743b8c1cda4b2160b25802f9f27d6
[ "Apache-2.0", "MIT" ]
1
2022-02-13T07:51:05.000Z
2022-02-13T07:51:05.000Z
'use strict' const path = require('path') const cidCommandsPath = path.join( path.dirname(require.resolve('cid-tool')), 'cli', 'commands' ) module.exports = { command: 'cid <command>', description: 'Convert, format and discover properties of CIDs.', /** * @param {import('yargs').Argv} yargs */ builder (yargs) { return yargs .commandDir(cidCommandsPath) } }
17.818182
66
0.647959
0eb1bc96b558edb319dfe0011670c4a5bfc5b69d
337
sql
SQL
Workload 15 Second IO.sql
grrlgeek/extended-events
a4707c541e64add883c8a5b7954b8a7fe8d7cd01
[ "MIT" ]
36
2016-04-05T17:39:18.000Z
2022-03-23T15:04:17.000Z
Workload 15 Second IO.sql
grrlgeek/extended-events
a4707c541e64add883c8a5b7954b8a7fe8d7cd01
[ "MIT" ]
null
null
null
Workload 15 Second IO.sql
grrlgeek/extended-events
a4707c541e64add883c8a5b7954b8a7fe8d7cd01
[ "MIT" ]
9
2015-12-31T20:48:36.000Z
2021-08-23T14:49:00.000Z
/* Workload for 15 Second I/O Error */ --How can I get I/O to last 15 seconds? /*nope USE AdventureWorks2014; GO BEGIN TRANSACTION SELECT * FROM Person.Person; WAITFOR DELAY '00:00:15' COMMIT TRANSACTION */ USE AdventureWorks2012; GO SELECT * FROM bigProduct; SELECT * FROM bigTransactionHistory; --Still got nothin'
12.035714
40
0.715134
2d7ae418b1cebf4e9eb40cb39c85af6ffbcff61f
1,169
go
Go
example/example.go
kibaamor/golog
ee92c16f5ccbe42b6e3870aaf337f8407d8aa045
[ "MIT" ]
null
null
null
example/example.go
kibaamor/golog
ee92c16f5ccbe42b6e3870aaf337f8407d8aa045
[ "MIT" ]
null
null
null
example/example.go
kibaamor/golog
ee92c16f5ccbe42b6e3870aaf337f8407d8aa045
[ "MIT" ]
null
null
null
package main import ( "context" "os" "github.com/kibaamor/golog" ) func main() { // basic logger logger := golog.NewTermLogger(os.Stderr, true) // got: `[INFO] 1:1 k1:v1 k2:[1 1]` _ = logger.Log(context.Background(), golog.LevelInfo, 1, 1, "k1", "v1", "k2", []int{1, 1}) // combine multiple logger // Discard is logger with discard everything logger = golog.MultiLogger(logger, golog.Discard) // got: `[INFO] 1:1 k1:v1 k2:[1 1]` _ = logger.Log(context.Background(), golog.LevelInfo, 1, 1, "k1", "v1", "k2", []int{1, 1}) // filter with log level logger = golog.WithFilter(logger, golog.FilterLevel(golog.LevelWarn)) // got: `` _ = logger.Log(context.Background(), golog.LevelInfo, 1, 1) // auto add timestamp and caller information logger = golog.WithHandler(logger, golog.HandlerDefaultTimestamp, golog.HandlerDefaultCaller) // got:`[2021-12-10 12:33:26.968][example.go:24][WARN] 1:1` _ = logger.Log(context.Background(), golog.LevelWarn, 1, 1) // Helper provides useful apis, such as Info, Infow. helper := golog.NewHelper(logger) // got: `[2021-12-10 12:37:52.699][helper.go:76][ERROR] golog: hi` helper.Errorf("golog: %v", "hi") }
28.512195
94
0.673225
ebfcee70c3ad410f0497777290f99f003ed22531
2,430
css
CSS
css/contact.css
rilindpozhegu/CMS-EM
6b10d10696ad9b1935ce5f58aaaf92c855552c20
[ "MIT" ]
null
null
null
css/contact.css
rilindpozhegu/CMS-EM
6b10d10696ad9b1935ce5f58aaaf92c855552c20
[ "MIT" ]
null
null
null
css/contact.css
rilindpozhegu/CMS-EM
6b10d10696ad9b1935ce5f58aaaf92c855552c20
[ "MIT" ]
null
null
null
/*Fonts*/ @font-face { font-family: 'OpenSans-Light'; src: url('../fonts/OpenSans-Light.ttf'); } @font-face { font-family: 'HelveticaLTStd-Bold'; src: url('../fonts/HelveticaLTStd-Bold.otf'); } @font-face { font-family: 'HelveticaLTStd-Light'; src: url('../fonts/HelveticaLTStd-Light.otf'); } @font-face { font-family: 'Montserrat-Bold'; src: url('../fonts/Montserrat-Bold.ttf'); } @font-face { font-family: 'Montserrat-Regular'; src: url('../fonts/Montserrat-Regular.ttf'); } body { font-family: 'HelveticaLTStd-Light'; } .no-padding { padding: 0px; } /*==========================================*/ /* ** Header */ .header-section { background-image: url('../../../../../public/assets/img/backgorund/contact-top-bg-01.png'); background-repeat: no-repeat; background-size: cover; margin-top: 7%; padding: 70px 0px; } .header_panel_section { padding: 30px; /*background: rgba(35, 53, 136, 0.55);*/ } .header_panel_section h4 { color: white; font-family: 'Montserrat-Bold'; font-size: 40px; } .header_panel_section span { color: white; font-size: 35px; } .header_panel_section p { padding: 10px 0px; color: rgba(255, 255, 255, 0.69); font-size: 20px; } .header-section button { color: white; background-color: #d4145a; border: none; width: 110px; height: 30px; font-size: 10px; font-family:"Montserrat-Regular"; border-radius: 5px; } /*first seciton news*/ .medium-panel { margin-top: 20px; margin-bottom: 20px; box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 6px; padding: 20px; height: 280px; } .medium-panel h5 { color: #324099; font-size: 15px; font-family: "Montserrat-Regular"; } .medium-panel p { color: #808285; font-size: 15px; font-family: "HelveticaLTStd-Light"; } /*Desktop Version*/ @media only screen and (min-width: 844px) { .desktop-d-n { display: none; } } /*Mobile Version*/ @media only screen and (max-width: 844px) { .mobile-d-n { display: none; } .home-bigpanel span { font-size: 25px; } .home-bigpanel h1 { margin: 0px 0px; font-size: 30px; } .home-bigpanel p { font-family: "HelveticaLTStd-Light"; color: #808285; font-size: 12px; } .panel-homepage p { font-family: "HelveticaLTStd-Light"; color: #808285; font-size: 12px; } .header_panel_section p { font-size: 17px; } }
18.837209
93
0.611523
ca9c141ac7939d7097ec1ac8881f5c10ced6db3b
1,184
kt
Kotlin
src/main/kotlin/io/openapiprocessor/core/processor/MappingConverter.kt
hauner/openapi-processor-core
de1f30c5926b699bdc9e22ec99eb47218c0c3dfe
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/io/openapiprocessor/core/processor/MappingConverter.kt
hauner/openapi-processor-core
de1f30c5926b699bdc9e22ec99eb47218c0c3dfe
[ "Apache-2.0" ]
5
2020-06-06T08:00:01.000Z
2020-06-13T15:13:02.000Z
src/main/kotlin/io/openapiprocessor/core/processor/MappingConverter.kt
hauner/openapi-processor-core
de1f30c5926b699bdc9e22ec99eb47218c0c3dfe
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 https://github.com/openapi-processor/openapi-processor-core * PDX-License-Identifier: Apache-2.0 */ @file:Suppress("DEPRECATION") package io.openapiprocessor.core.processor import io.openapiprocessor.core.converter.mapping.Mapping import io.openapiprocessor.core.processor.mapping.v1.MappingConverter as MappingConverterV1 import io.openapiprocessor.core.processor.mapping.v1.Mapping as MappingV1 import io.openapiprocessor.core.processor.mapping.MappingVersion import io.openapiprocessor.core.processor.mapping.v2.MappingConverter as MappingConverterV2 import io.openapiprocessor.core.processor.mapping.v2.Mapping as MappingV2 /** * Converter for the type mapping from the mapping yaml. It converts the type mapping information * into the format used by [io.openapiprocessor.core.converter.DataTypeConverter]. */ class MappingConverter { fun convert(source: MappingVersion?): List<Mapping> { if (source == null) { return emptyList() } return if (source.v2) { MappingConverterV2(source as MappingV2).convert() } else { MappingConverterV1().convert(source as MappingV1) } } }
32.888889
98
0.753378
0abe1c0e00853bba9a8dafb6fe2c3611418f7f85
5,751
cs
C#
Avalonia.ExtendedToolkit/Controls/Flyout/FlyoutsControl.cs
FCUnlimited/Avalonia.ExtendedToolkit
c88181fb263916d67c467893efee5da4b04a1c8b
[ "MIT" ]
137
2020-02-02T19:01:36.000Z
2022-03-30T07:24:00.000Z
Avalonia.ExtendedToolkit/Controls/Flyout/FlyoutsControl.cs
FCUnlimited/Avalonia.ExtendedToolkit
c88181fb263916d67c467893efee5da4b04a1c8b
[ "MIT" ]
54
2020-04-15T17:38:13.000Z
2022-03-24T14:30:18.000Z
Avalonia.ExtendedToolkit/Controls/Flyout/FlyoutsControl.cs
FCUnlimited/Avalonia.ExtendedToolkit
c88181fb263916d67c467893efee5da4b04a1c8b
[ "MIT" ]
13
2020-03-29T14:55:18.000Z
2022-03-30T07:24:01.000Z
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using Avalonia.Controls.Generators; using Avalonia.ExtendedToolkit.Extensions; using Avalonia.Input; namespace Avalonia.ExtendedToolkit.Controls { //ported from https://github.com/MahApps/MahApps.Metro /// <summary> /// A FlyoutsControl is for displaying flyouts in a MetroWindow. /// <see cref="MetroWindow"/> /// </summary> public class FlyoutsControl : ItemsControl { /// <summary> /// Gets/sets whether /// <see cref="Avalonia.ExtendedToolkit.Controls.Flyout.ExternalCloseButton"/> /// is ignored and all flyouts behave as if it was set to the value of this property. /// </summary> public MouseButton? OverrideExternalCloseButton { get { return (MouseButton?)GetValue(OverrideExternalCloseButtonProperty); } set { SetValue(OverrideExternalCloseButtonProperty, value); } } /// <summary> /// <see cref="OverrideExternalCloseButton"/> /// </summary> public static readonly StyledProperty<MouseButton?> OverrideExternalCloseButtonProperty = AvaloniaProperty.Register<FlyoutsControl, MouseButton?>(nameof(OverrideExternalCloseButton)); /// <summary> /// Gets/sets whether /// <see cref="Avalonia.ExtendedToolkit.Controls.Flyout.IsPinned"/> /// is ignored and all flyouts behave as if it was set false. /// </summary> public bool OverrideIsPinned { get { return (bool)GetValue(OverrideIsPinnedProperty); } set { SetValue(OverrideIsPinnedProperty, value); } } /// <summary> /// <see cref="OverrideIsPinned"/> /// </summary> public static readonly StyledProperty<bool> OverrideIsPinnedProperty = AvaloniaProperty.Register<FlyoutsControl, bool>(nameof(OverrideIsPinned)); /// <summary> /// registers changed events /// </summary> public FlyoutsControl() { //ItemsPanelProperty.OverrideDefaultValue<FlyoutsControl>(DefaultPanel); ItemsProperty.Changed.AddClassHandler<FlyoutsControl>((o, e) => OnItemsChaned(o, e)); } private void OnItemsChaned(FlyoutsControl o, AvaloniaPropertyChangedEventArgs e) { this.IsVisible = true; } /// <summary> /// use FlyoutContainerGenerator as container generator /// </summary> /// <returns></returns> protected override IItemContainerGenerator CreateItemContainerGenerator() { return new FlyoutContainerGenerator(this); } /// <summary> /// called from the <see cref="FlyoutContainerGenerator.CreateContainer(object)"/> only. /// </summary> /// <param name="flyout"></param> internal void AttachHandlers(Flyout flyout) { flyout.IsOpenChanged -= FlyoutStatusChanged; flyout.FlyoutThemeChanged -= FlyoutStatusChanged; flyout.IsOpenChanged += FlyoutStatusChanged; flyout.FlyoutThemeChanged += FlyoutStatusChanged; //var isOpenNotifier = new PropertyChangeNotifier(flyout, Flyout.IsOpenProperty); //isOpenNotifier.ValueChanged += FlyoutStatusChanged; //flyout.IsOpenPropertyChangeNotifier = isOpenNotifier; //var themeNotifier = new PropertyChangeNotifier(flyout, Flyout.FlyoutThemeProperty); //themeNotifier.ValueChanged += FlyoutStatusChanged; //flyout.ThemePropertyChangeNotifier = themeNotifier; } private void FlyoutStatusChanged(object sender, EventArgs e) { var flyout = this.GetFlyout(sender); //Get the flyout that raised the handler. this.HandleFlyoutStatusChange(flyout, this.TryFindParent<MetroWindow>()); } internal void HandleFlyoutStatusChange(Flyout flyout, MetroWindow parentWindow) { if (flyout == null || parentWindow == null) { return; } this.ReorderZIndices(flyout); var visibleFlyouts = this.GetFlyouts(this.Items).Where(i => i.IsOpen).OrderBy(x => x.ZIndex).ToList(); parentWindow.HandleFlyoutStatusChange(flyout, visibleFlyouts); } private Flyout GetFlyout(object item) { var flyout = item as Flyout; if (flyout != null) { return flyout; } return (Flyout)item; //int index = this.ItemContainerGenerator.IndexFromContainer(DefaultPanel); //return (Flyout)this.ItemContainerGenerator.ContainerFromIndex(index); } internal IEnumerable<Flyout> GetFlyouts() { return GetFlyouts(this.Items); } private IEnumerable<Flyout> GetFlyouts(IEnumerable items) { return from object item in items select this.GetFlyout(item); } private void ReorderZIndices(Flyout lastChanged) { var openFlyouts = this.GetFlyouts(this.Items).Where(i => i.IsOpen && i != lastChanged).OrderBy(x => x.ZIndex); var index = 0; foreach (var openFlyout in openFlyouts) { openFlyout.ZIndex = index; //Panel.SetZIndex(openFlyout, index); index++; } if (lastChanged.IsOpen) { lastChanged.IsVisible = true; lastChanged.ZIndex = index; //Panel.SetZIndex(lastChanged, index); } } } }
35.067073
122
0.611546
4f9d4a538d47d8e23176dd386c548a73e4e247be
159
sql
SQL
src/main/resources/META-INF/create-script.sql
asiexplore/restfultest
abe2b5d8a00a698b56f1d9366bf6176d46a4df55
[ "MIT" ]
5
2016-11-07T09:28:43.000Z
2020-09-02T04:01:39.000Z
src/main/resources/META-INF/create-script.sql
asiexplore/restfultest
abe2b5d8a00a698b56f1d9366bf6176d46a4df55
[ "MIT" ]
null
null
null
src/main/resources/META-INF/create-script.sql
asiexplore/restfultest
abe2b5d8a00a698b56f1d9366bf6176d46a4df55
[ "MIT" ]
9
2017-01-15T17:44:24.000Z
2020-06-15T12:13:55.000Z
CREATE TABLE CUSTOMER("ID" BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (start with 1, increment by 1), "FIRST_NAME" VARCHAR(255), "LAST_NAME" VARCHAR(255))
159
159
0.773585
8e8df6b74210f112b441c8461f69e4bbe43cdc17
751
js
JavaScript
src/components/TextBlock.js
archilkarchava/stolyarka-gatsby
c087e1af7db138a2ceaad2597899495a41c3f788
[ "MIT" ]
null
null
null
src/components/TextBlock.js
archilkarchava/stolyarka-gatsby
c087e1af7db138a2ceaad2597899495a41c3f788
[ "MIT" ]
null
null
null
src/components/TextBlock.js
archilkarchava/stolyarka-gatsby
c087e1af7db138a2ceaad2597899495a41c3f788
[ "MIT" ]
null
null
null
import styled from 'styled-components' import setTextColor from '../utils/setTextColor' import media from '../utils/media' const TextBlock = styled.div` background-color: ${props => (props.primaryBg && props.theme.primary) || (props.lightBg && props.theme.light) || (props.darkBg && props.theme.dark) || props.theme.primary}; color: ${props => setTextColor( (props.primaryBg && props.theme.primary) || (props.lightBg && props.theme.light) || (props.darkBg && props.theme.dark) || props.theme.primary )}; text-align: center; font-size: 30px; padding: 100px 20px; ${media.tablet` font-size: 18px; padding: 50px 20px; `}; ` export default TextBlock
26.821429
50
0.617843
a923341b5770c07c176a6ea327641577fc08af5f
1,197
css
CSS
src/components/Projects/Projects.css
siddhant-roy/portfolio
6353398757590260097c4e54b110e9bbad8d1154
[ "MIT" ]
null
null
null
src/components/Projects/Projects.css
siddhant-roy/portfolio
6353398757590260097c4e54b110e9bbad8d1154
[ "MIT" ]
null
null
null
src/components/Projects/Projects.css
siddhant-roy/portfolio
6353398757590260097c4e54b110e9bbad8d1154
[ "MIT" ]
null
null
null
.project-cards-container { display: flex; flex-direction: row; flex-wrap: wrap; padding: 44px; align-self: center; justify-content: center; } .project-card { width: 500px; min-height: 550px; background: #fff; box-shadow: 10px 40px 50px rgba(229, 233, 246, 0.4); border-radius: 20px; display: flex; flex-direction: column; margin: 20px; } .project-card:hover { box-shadow: 0px 40px 50px rbga(0, 0, 0, 0.4); transition: all 0.3s; } .image-container { width: 100%; border-radius: 20px 20px 0 0; } .project-external-link { border-radius: inherit; } .project-image { display: block; border-radius: inherit; max-height: 100%; max-width: 100%; } .project-details-container { display: flex; flex-direction: column; justify-content: flex-start; align-self: flex-start; padding: 20px; } .project-yt-link { font-weight: 600; color: #4089ed; } .project-heading { margin: 0; } .project-details { font-weight: 300; font-size: 16px; line-height: 28px; color: #7d7987; } @media only screen and (max-width: 640px) { .project-cards-container { padding: 20px; } .project-card { width: 290px; min-height: 500px; } }
15.75
54
0.651629
4aaf3192b0fbc97845b8aa665c571ce52f670461
175
sql
SQL
data/db/65-inttofloat.sql
buse974/twic-api
e1edb6060def641977c8d7d25ab0fb0bf8512c1e
[ "MIT" ]
null
null
null
data/db/65-inttofloat.sql
buse974/twic-api
e1edb6060def641977c8d7d25ab0fb0bf8512c1e
[ "MIT" ]
1
2017-12-19T15:37:43.000Z
2017-12-19T15:56:21.000Z
data/db/65-inttofloat.sql
buse974/twic-api
e1edb6060def641977c8d7d25ab0fb0bf8512c1e
[ "MIT" ]
3
2017-12-10T22:16:23.000Z
2017-12-15T08:58:25.000Z
ALTER TABLE `bank_answer_item` CHANGE COLUMN `percent` `percent` FLOAT NULL DEFAULT NULL ; ALTER TABLE `bank_question` CHANGE COLUMN `point` `point` FLOAT NULL DEFAULT NULL ;
58.333333
90
0.782857
b052201ee391d75833617480f014228469bd71e1
661
py
Python
benchmarks/Evolution/both/evo_tests/constants.py
nuprl/retic_performance
621211c2f40251ce5364c33e72e4067e34a32013
[ "MIT" ]
3
2018-08-03T02:41:29.000Z
2021-03-19T03:18:47.000Z
benchmarks/Evolution/both/evo_tests/constants.py
nuprl/retic_performance
621211c2f40251ce5364c33e72e4067e34a32013
[ "MIT" ]
3
2018-02-04T17:53:56.000Z
2018-11-10T17:06:57.000Z
benchmarks/Evolution/both/evo_tests/constants.py
nuprl/retic_performance
621211c2f40251ce5364c33e72e4067e34a32013
[ "MIT" ]
1
2018-08-04T00:14:12.000Z
2018-08-04T00:14:12.000Z
__author__ = 'Edwin Cowart, Kevin McDonough' # The URL that the Test Cases are received from as HTML TEST_CASES_URL = "http://www.ccs.neu.edu/home/tonyg/cs4500/6.html" GEN_TEST_STR = 'test_*.py' # JSON Directory Names JSON_STREAM_DIR = "json_streams" JSON_SITUATION_DIR = "json_situations" JSON_FEEDING_6_DIR = "json_feedings_6" JSON_FEEDING_7_DIR = "json_feedings_7" JSON_FEEDING_DIR = "json_feedings" JSON_CONFIG_DIR = "json_configs" JSON_STEP4_DIR = "json_step4" JSON_SILLY_CHOICE_DIR = "json_silly" # Python import module separator MODULE_SEP = "." # JSON In/Out Filename ending IN_JSON = "in.json" OUT_JSON = "out.json" TEST_CASES_DIR = "test_cases"
25.423077
66
0.77761
447a084bb3d50424a483e401e93fb5de6c9bdd6c
1,941
py
Python
meteor_reasoner/utils/loader.py
wdimmy/MeTeoR
7d0b48bf32eca17a1d507476112379daa3dafc31
[ "MIT" ]
8
2021-12-01T14:17:06.000Z
2022-03-05T13:22:27.000Z
meteor_reasoner/utils/loader.py
wdimmy/MeTeoR
7d0b48bf32eca17a1d507476112379daa3dafc31
[ "MIT" ]
null
null
null
meteor_reasoner/utils/loader.py
wdimmy/MeTeoR
7d0b48bf32eca17a1d507476112379daa3dafc31
[ "MIT" ]
null
null
null
from meteor_reasoner.utils.parser import * from collections import defaultdict def load_dataset(lines): """ Read string-like facts into a dictionary object. Args: lines (list of strings): a list of facts in the form of A(x,y,z)@[1,2] or A@[1,2) Returns: A defaultdict object, in which the key is the predicate and the value is a dictionary (key is the entity and the value is a list of Interval instances) or a list of Interval instance when there is no entity. """ D = defaultdict(lambda: defaultdict(list)) for line in lines: line = line.strip().replace(" ","") if line == "": continue try: predicate, entity, interval = parse_str_fact(line) except: continue if predicate not in D: if entity: D[predicate][entity] = [interval] else: D[predicate] = [interval] else: if isinstance(D[predicate], list) and entity is not None: raise ValueError("One predicate can not have both entity and Null cases!") if not isinstance(D[predicate], list) and entity is None: raise ValueError("One predicate can not have both entity and Null cases!") if entity: if entity in D[predicate]: D[predicate][entity].append(interval) else: D[predicate][entity] = [interval] else: D[predicate].append(interval) return D def load_program(rules): """ Format each string-like rule into a rule instance. Args: rules (list of strings): each string represents a rule, e.g. A(X):- Boxminus[1,2]B(X) Returns: list of rule instances """ program = [] for line in rules: rule = parse_rule(line) program.append(rule) return program
28.970149
101
0.574446
71ff0e4788665b8bb7811227c7a59ac3cd152964
5,038
lua
Lua
app/handlers/ddl_handler.lua
datamarts/kafka-tarantool-loader
c4de2d70b8a2a36555807b1e97acddb1a1cf4b82
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
app/handlers/ddl_handler.lua
datamarts/kafka-tarantool-loader
c4de2d70b8a2a36555807b1e97acddb1a1cf4b82
[ "ECL-2.0", "Apache-2.0" ]
5
2021-05-25T14:53:11.000Z
2021-08-23T13:32:46.000Z
app/handlers/ddl_handler.lua
datamarts/kafka-tarantool-loader
c4de2d70b8a2a36555807b1e97acddb1a1cf4b82
[ "ECL-2.0", "Apache-2.0" ]
4
2021-06-22T11:30:52.000Z
2022-02-08T11:41:40.000Z
-- Copyright 2021 Kafka-Tarantool-Loader -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. --- --- Created by ashitov. --- DateTime: 6/29/20 1:03 PM --- local cartridge = require("cartridge") local uuid = require("uuid") local error_repository = require("app.messages.error_repository") local json = require("json") local function add_table_to_delete_batch(req) local table_name = req:stash("tableName") local batch_id = req:query_param("batchId") or uuid.str() if table_name == nil then return error_repository.return_http_response("API_DDL_TABLE_DELETE_BATCH_ADD_001") end local _, err = cartridge.rpc_call( "app.roles.adg_state", "update_delete_batch_storage", { batch_id, { table_name } }, { leader_only = true, timeout = 30 } ) if err ~= nil then return error_repository.return_http_response("API_DDL_TABLE_DELETE_BATCH_ADD_003", { error = err }) end return { status = 200, body = json.encode({ batchId = batch_id }) } end local function queued_prefix_delete(req) local prefix = req:stash("tablePrefix") if prefix == nil then return error_repository.return_http_response( "API_DDL_TABLE_DELETE_BATCH_ADD_006", nil, json.encode({ code = "API_DDL_TABLE_DELETE_BATCH_ADD_006", message = "ERROR: prefix param not found in the query.", }) ) end local waiting_operation_timeout = _G.api_timeouts:get_ddl_operation_timeout() local _, err = cartridge.rpc_call( "app.roles.adg_state", "delayed_delete_prefix", { prefix, waiting_operation_timeout }, { leader_only = true, timeout = waiting_operation_timeout + 10 } ) if err ~= nil then if err["code"] == "API_DDL_QUEUE_004" then return error_repository.return_http_response(err["code"], nil, err) end return error_repository.return_http_response("API_DDL_QUEUE_003", nil, err) end return { status = 200, body = json.encode({}) } end local function queued_tables_delete(req) local body = req:json() if body.tableList == nil then return error_repository.return_http_response("API_DDL_QUEUE_001") end if type(body.tableList) ~= "table" then return error_repository.return_http_response("API_DDL_QUEUE_002") end local waiting_operation_timeout = _G.api_timeouts:get_ddl_operation_timeout() local _, err = cartridge.rpc_call( "app.roles.adg_state", "delayed_delete", { body.tableList, waiting_operation_timeout }, { leader_only = true, timeout = waiting_operation_timeout + 10 } ) if err ~= nil then if err["code"] == "API_DDL_QUEUE_004" then return error_repository.return_http_response(err["code"], nil, err) end return error_repository.return_http_response("API_DDL_QUEUE_003", nil, err) end return { status = 200, body = json.encode({}) } end local function queued_tables_create(req) local body = req:json() if body.spaces == nil then return error_repository.return_http_response("API_DDL_QUEUE_001") end if type(body.spaces) ~= "table" then return error_repository.return_http_response("API_DDL_QUEUE_002") end local waiting_operation_timeout = _G.api_timeouts:get_ddl_operation_timeout() local _, err = cartridge.rpc_call( "app.roles.adg_state", "delayed_create", { body.spaces, waiting_operation_timeout }, { leader_only = true, timeout = waiting_operation_timeout + 10 } ) if err ~= nil then if err["code"] == "API_DDL_QUEUE_004" then return error_repository.return_http_response(err["code"], nil, err) end return error_repository.return_http_response("API_DDL_QUEUE_003", nil, err) end return { status = 200, body = json.encode({}) } end local function get_storage_space_schema(req) local body = req:json() if body.spaces == nil then return { status = 500, body = json.encode({ error = "Empty spaces parameter" }) } end local res = _G.get_storage_space_schema(body.spaces) return { status = 200, body = res } end return { add_table_to_delete_batch = add_table_to_delete_batch, queued_tables_delete = queued_tables_delete, queued_tables_create = queued_tables_create, queued_prefix_delete = queued_prefix_delete, get_storage_space_schema = get_storage_space_schema, }
32.928105
107
0.682612
ef1d2b289a50d0621dcdf6358e1b4068a88f2b00
2,333
c
C
Homework/SimpleShell/simpleshell.c
gajavegr/csse332
060d3cf18cd38d9f4524c42f1e755f5d24de2c51
[ "MIT" ]
null
null
null
Homework/SimpleShell/simpleshell.c
gajavegr/csse332
060d3cf18cd38d9f4524c42f1e755f5d24de2c51
[ "MIT" ]
null
null
null
Homework/SimpleShell/simpleshell.c
gajavegr/csse332
060d3cf18cd38d9f4524c42f1e755f5d24de2c51
[ "MIT" ]
null
null
null
/* Copyright 2016 Rose-Hulman But based on idea from http://cnds.eecs.jacobs-university.de/courses/caoslab-2007/ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <stdbool.h> #include <string.h> void handler(){ wait(NULL); } int main() { char command[82]; char *parsed_command[2]; //takes at most two input arguments // infinite loop but ^C quits while (1) { printf("SHELL%% "); fgets(command, 82, stdin); command[strlen(command) - 1] = '\0';//remove the \n int len_1; for(len_1 = 0;command[len_1] != '\0';len_1++){ if(command[len_1] == ' ') break; } command[len_1] = '\0'; parsed_command[0] = command; if(len_1 == strlen(command)){ printf("Command is '%s' with no arguments\n", parsed_command[0]); parsed_command[1] = NULL; } else{ parsed_command[1] = command + len_1 + 1; printf("Command is '%s' with argument '%s'\n", parsed_command[0], parsed_command[1]); } char *const command2[] = {parsed_command[0],parsed_command[1], NULL}; char b = parsed_command[0][0]; char g = parsed_command[0][1]; bool background = (b=='B')&&(g == 'G'); // printf("background: %d",background); int childnum = fork(); // printf("%d\n",childnum); int childnum2; // int grandchild; // int child; if (childnum == 0 && background){ childnum2 = fork(); if (childnum2 == 0){ char* stringWithoutPrefix = &parsed_command[0][2]; execvp(stringWithoutPrefix,command2); exit(0); } else{ wait(&childnum); printf("Background command finished\n"); exit(0); } } else if (childnum == 0 && !background){ execvp(parsed_command[0],command2); signal(SIGCHLD, handler); exit(0); } else if (childnum !=0 && !background){ signal(SIGCHLD, handler); wait(NULL); } } // wait(NULL); }
30.298701
98
0.498928
185148363bc6d250cef3df19f1b67fc4855578f4
1,776
ts
TypeScript
element-template/src/element-template.ts
pearlbea/nutmeg-cli
c745cd7afb4d35d828d042d93cd660a50b46d24d
[ "MIT" ]
null
null
null
element-template/src/element-template.ts
pearlbea/nutmeg-cli
c745cd7afb4d35d828d042d93cd660a50b46d24d
[ "MIT" ]
null
null
null
element-template/src/element-template.ts
pearlbea/nutmeg-cli
c745cd7afb4d35d828d042d93cd660a50b46d24d
[ "MIT" ]
null
null
null
import { Seed, Property, html, TemplateResult } from '@nutmeg/seed'; export class <%= name %> extends Seed { <% properties.properties.forEach((property) => { print(` @Property() public ${property.name}: ${property.type};\n`); }); %> constructor() { super(); } /** The component instance has been inserted into the DOM. */ public connectedCallback() { super.connectedCallback(); } /** The component instance has been removed from the DOM. */ public disconnectedCallback() { super.disconnectedCallback() } /** Watch for changes to these attributes. */ public static get observedAttributes(): string[] { return super.observedAttributes; } /** Rerender when the observed attributes change. */ public attributeChangedCallback(name: string, oldValue: any, newValue: any) { super.attributeChangedCallback(name, oldValue, newValue) } /** Styling for the component. */ public get styles(): TemplateResult { return html` <style> :host { box-shadow: 0 3px 1px -2px rgba(0, 0, 0, .2), 0 2px 2px 0 rgba(0, 0 ,0, .14), 0 1px 5px 0 rgba(0, 0, 0, .12); } .content { background-color: var(--<%= tag %>-background-color, #FAFAFA); color: #212121; padding: 16px; } </style> `; } /** HTML Template for the component. */ public get template(): TemplateResult { return html` <div class="content"> Welcome to &lt;<%= tag %>&gt; <ul><% properties.primitive.forEach((property) => { print(`\n <li>${property.name}: \${this.${property.name}}</li>`); }); %> </ul> <slot></slot> </div> `; } } window.customElements.define('<%= tag %>', <%= name %>);
26.909091
119
0.581081
3d23b5f04895949c0fe458b413a813c244bff796
396
asm
Assembly
libsrc/_DEVELOPMENT/stdlib/c/sdcc_ix/_quicksort__callee.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
libsrc/_DEVELOPMENT/stdlib/c/sdcc_ix/_quicksort__callee.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
libsrc/_DEVELOPMENT/stdlib/c/sdcc_ix/_quicksort__callee.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
; void qsort_callee(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) SECTION code_stdlib PUBLIC __quicksort__callee, l0__quicksort__callee EXTERN asm_quicksort __quicksort__callee: pop af pop bc pop hl pop de exx pop bc push af l0__quicksort__callee: push bc exx ex (sp),ix call asm_quicksort pop ix ret
12.774194
101
0.679293
995fae73bf8a3b8fde6063a9927e84ca93e9dc7a
8,518
lua
Lua
nvim_2021/lua/core/galaxyline.lua
bamzi/dotconfig
4db4130e0a12a3c5aa1db05d353ee9c54fcff676
[ "MIT" ]
null
null
null
nvim_2021/lua/core/galaxyline.lua
bamzi/dotconfig
4db4130e0a12a3c5aa1db05d353ee9c54fcff676
[ "MIT" ]
null
null
null
nvim_2021/lua/core/galaxyline.lua
bamzi/dotconfig
4db4130e0a12a3c5aa1db05d353ee9c54fcff676
[ "MIT" ]
null
null
null
-- if not package.loaded['galaxyline'] then -- return -- end require "core.status_colors" local Log = require "core.log" local status_ok, gl = pcall(require, "galaxyline") if not status_ok then Log:get_default().error "Failed to load galaxyline" return end -- NOTE: if someone defines colors but doesn't have them then this will break local palette_status_ok, colors = pcall(require, color_theme .. ".palette") if not palette_status_ok then colors = galaxyline_config.colors end local condition = require "galaxyline.condition" local gls = gl.section gl.short_line_list = { "NvimTree", "vista", "dbui", "packer" } local function get_mode_name() local names = { n = "NORMAL", i = "INSERT", c = "COMMAND", v = "VISUAL", V = "VISUAL LINE", t = "TERMINAL", R = "REPLACE", [""] = "VISUAL BLOCK", } return names[vim.fn.mode()] end table.insert(gls.left, { ViMode = { provider = function() -- auto change color according the vim mode local mode_color = { n = colors.blue, i = colors.green, v = colors.purple, [""] = colors.purple, V = colors.purple, c = colors.magenta, no = colors.blue, s = colors.orange, S = colors.orange, [""] = colors.orange, ic = colors.yellow, R = colors.red, Rv = colors.red, cv = colors.blue, ce = colors.blue, r = colors.cyan, rm = colors.cyan, ["r?"] = colors.cyan, ["!"] = colors.blue, t = colors.blue, } if galaxyline_config.show_mode then local name = get_mode_name() -- Fall back to the default behavior is a name is not defined if name ~= nil then vim.api.nvim_command("hi GalaxyViMode guibg=" .. mode_color[vim.fn.mode()]) vim.api.nvim_command("hi GalaxyViMode guifg=" .. colors.alt_bg) return " " .. name .. " " end end vim.api.nvim_command("hi GalaxyViMode guibg=" .. colors.alt_bg) vim.api.nvim_command("hi GalaxyViMode guifg=" .. mode_color[vim.fn.mode()]) return "▊" end, separator_highlight = { "NONE", colors.alt_bg }, highlight = { "NONE", colors.alt_bg }, }, }) -- print(vim.fn.getbufvar(0, 'ts')) vim.fn.getbufvar(0, "ts") table.insert(gls.left, { GitIcon = { provider = function() return " " end, condition = condition.check_git_workspace, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.orange, colors.alt_bg }, }, }) table.insert(gls.left, { GitBranch = { provider = "GitBranch", condition = condition.check_git_workspace, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.left, { DiffAdd = { provider = "DiffAdd", condition = condition.hide_in_width, icon = "  ", highlight = { colors.green, colors.alt_bg }, }, }) table.insert(gls.left, { DiffModified = { provider = "DiffModified", condition = condition.hide_in_width, icon = " 柳", highlight = { colors.blue, colors.alt_bg }, }, }) table.insert(gls.left, { DiffRemove = { provider = "DiffRemove", condition = condition.hide_in_width, icon = "  ", highlight = { colors.red, colors.alt_bg }, }, }) table.insert(gls.left, { Filler = { provider = function() return " " end, highlight = { colors.grey, colors.alt_bg }, }, }) -- get output from shell command function os.capture(cmd, raw) local f = assert(io.popen(cmd, "r")) local s = assert(f:read "*a") f:close() if raw then return s end s = string.gsub(s, "^%s+", "") s = string.gsub(s, "%s+$", "") s = string.gsub(s, "[\n\r]+", " ") return s end -- cleanup virtual env local function env_cleanup(venv) if string.find(venv, "/") then local final_venv = venv for w in venv:gmatch "([^/]+)" do final_venv = w end venv = final_venv end return venv end local PythonEnv = function() if vim.bo.filetype == "python" then local venv = os.getenv "CONDA_DEFAULT_ENV" if venv ~= nil then return "  (" .. env_cleanup(venv) .. ")" end venv = os.getenv "VIRTUAL_ENV" if venv ~= nil then return "  (" .. env_cleanup(venv) .. ")" end return "" end return "" end table.insert(gls.left, { VirtualEnv = { provider = PythonEnv, event = "BufEnter", highlight = { colors.green, colors.alt_bg }, }, }) table.insert(gls.right, { DiagnosticError = { provider = "DiagnosticError", icon = "  ", highlight = { colors.red, colors.alt_bg }, }, }) table.insert(gls.right, { DiagnosticWarn = { provider = "DiagnosticWarn", icon = "  ", highlight = { colors.orange, colors.alt_bg }, }, }) table.insert(gls.right, { DiagnosticInfo = { provider = "DiagnosticInfo", icon = "  ", highlight = { colors.yellow, colors.alt_bg }, }, }) table.insert(gls.right, { DiagnosticHint = { provider = "DiagnosticHint", icon = "  ", highlight = { colors.blue, colors.alt_bg }, }, }) table.insert(gls.right, { TreesitterIcon = { provider = function() if next(vim.treesitter.highlighter.active) ~= nil then return " " end return "" end, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.green, colors.alt_bg }, }, }) local function get_attached_provider_name(msg) msg = msg or "LSP Inactive" local buf_clients = vim.lsp.buf_get_clients() if next(buf_clients) == nil then return msg end local buf_client_names = {} for _, client in pairs(buf_clients) do if client.name ~= "null-ls" then table.insert(buf_client_names, client.name) end end local null_ls = require "lsp.null-ls" local null_ls_providers = null_ls.list_supported_provider_names(vim.bo.filetype) vim.list_extend(buf_client_names, null_ls_providers) return table.concat(buf_client_names, ", ") end table.insert(gls.right, { ShowLspClient = { provider = get_attached_provider_name, condition = function() local tbl = { ["dashboard"] = true, [" "] = true } if tbl[vim.bo.filetype] then return false end return true end, icon = " ", highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.right, { LineInfo = { provider = "LineColumn", separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.right, { PerCent = { provider = "LinePercent", separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.right, { Tabstop = { provider = function() local label = "Spaces: " if not vim.api.nvim_buf_get_option(0, "expandtab") then label = "Tab size: " end return label .. vim.api.nvim_buf_get_option(0, "shiftwidth") .. " " end, condition = condition.hide_in_width, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.right, { BufferType = { provider = "FileTypeName", condition = condition.hide_in_width, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.right, { FileEncode = { provider = "FileEncode", condition = condition.hide_in_width, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.right, { Space = { provider = function() return " " end, separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.grey, colors.alt_bg }, }, }) table.insert(gls.short_line_left, { BufferType = { provider = "FileTypeName", separator = " ", separator_highlight = { "NONE", colors.alt_bg }, highlight = { colors.alt_bg, colors.alt_bg }, }, }) table.insert(gls.short_line_left, { SFileName = { provider = "SFileName", condition = condition.buffer_not_empty, highlight = { colors.alt_bg, colors.alt_bg }, }, }) --table.insert(gls.short_line_right[1] = {BufferIcon = {provider = 'BufferIcon', highlight = {colors.grey, colors.alt_bg}}})
24.267806
124
0.606715
9e2d3b68f493d5f6fc1681e96e9ca1b0ba80d115
307
cs
C#
src/Tinja.Abstractions/IContainer.cs
zuvys/Tinja
12d925dc5856dca1597af62701b5e7c878817da3
[ "MIT" ]
18
2018-04-02T09:43:06.000Z
2021-12-10T03:18:38.000Z
src/Tinja.Abstractions/IContainer.cs
zuvys/Tinja
12d925dc5856dca1597af62701b5e7c878817da3
[ "MIT" ]
null
null
null
src/Tinja.Abstractions/IContainer.cs
zuvys/Tinja
12d925dc5856dca1597af62701b5e7c878817da3
[ "MIT" ]
2
2019-05-07T03:32:40.000Z
2021-07-20T10:51:56.000Z
using System; using System.Collections.Concurrent; using System.Collections.Generic; using Tinja.Abstractions.Injection; namespace Tinja.Abstractions { public interface IContainer : IEnumerable<ServiceEntry> { ConcurrentDictionary<Type, List<ServiceEntry>> ServiceEntries { get; } } }
23.615385
78
0.762215
854aaf6ee38815128406a1b3c213544eb71339d6
1,094
cs
C#
Tests/TestPrograms/LinqTest6/LinqTest6.cs
ravimad/SEAL
41dcf675e988645d07844ae575a8b774c5ae3164
[ "MS-PL" ]
1
2016-03-13T23:19:45.000Z
2016-03-13T23:19:45.000Z
Tests/TestPrograms/LinqTest6/LinqTest6.cs
ravimad/SEAL
41dcf675e988645d07844ae575a8b774c5ae3164
[ "MS-PL" ]
null
null
null
Tests/TestPrograms/LinqTest6/LinqTest6.cs
ravimad/SEAL
41dcf675e988645d07844ae575a8b774c5ae3164
[ "MS-PL" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinqTest6 { public class LinqTest { public int f; public void foo(LinqTest lt) { var col = new List<LinqTest> { lt }; var y = new List<LinqTest>(RemoveDefaults(col)); var x = y[0]; x.f = 1; } /// <summary> /// Removes default values from a list /// </summary> /// <typeparam name="T">Value type</typeparam> /// <param name="Value">List to cull items from</param> /// <param name="EqualityComparer">Equality comparer used (defaults to GenericEqualityComparer)</param> /// <returns>An IEnumerable with the default values removed</returns> public IEnumerable<T> RemoveDefaults<T>(IEnumerable<T> Value) { if (Value == null) yield break; foreach (T Item in Value.Where(x => !x.Equals(default(T)))) yield return Item; } } }
33.151515
112
0.533821
b167f223733c1d3f888e92631f85bada5ba538f4
31
py
Python
autokey/CapsCtrl/caps_j.py
TeX2e/dotfiles
4e39b59623067fcb09ceaa7f4892ff7a2b285374
[ "WTFPL" ]
1
2017-04-17T16:24:23.000Z
2017-04-17T16:24:23.000Z
autokey/CapsCtrl/caps_j.py
TeX2e/dotfiles
4e39b59623067fcb09ceaa7f4892ff7a2b285374
[ "WTFPL" ]
null
null
null
autokey/CapsCtrl/caps_j.py
TeX2e/dotfiles
4e39b59623067fcb09ceaa7f4892ff7a2b285374
[ "WTFPL" ]
1
2021-02-23T07:51:32.000Z
2021-02-23T07:51:32.000Z
keyboard.send_keys("<ctrl>+j")
15.5
30
0.709677
dd576c7367022340c5dbe754d4f5432be2fcbe34
2,288
java
Java
Examples/src/main/java/com/aspose/slides/examples/Slides/Table/SettingTextFormattingInsideTable.java
Muhammad-Adnan-Ahmad/Aspose.Slides-for-Java
8ef35cedb58ded3d007c3dd18a16ed15edc08f40
[ "MIT" ]
1
2018-10-25T13:03:50.000Z
2018-10-25T13:03:50.000Z
Examples/src/main/java/com/aspose/slides/examples/Slides/Table/SettingTextFormattingInsideTable.java
Muhammad-Adnan-Ahmad/Aspose.Slides-for-Java
8ef35cedb58ded3d007c3dd18a16ed15edc08f40
[ "MIT" ]
null
null
null
Examples/src/main/java/com/aspose/slides/examples/Slides/Table/SettingTextFormattingInsideTable.java
Muhammad-Adnan-Ahmad/Aspose.Slides-for-Java
8ef35cedb58ded3d007c3dd18a16ed15edc08f40
[ "MIT" ]
2
2020-05-13T06:04:43.000Z
2020-10-26T07:26:15.000Z
package com.aspose.slides.examples.Slides.Table; import com.aspose.slides.IAutoShape; import com.aspose.slides.IParagraph; import com.aspose.slides.IPortion; import com.aspose.slides.ISlide; import com.aspose.slides.ITable; import com.aspose.slides.ITextFrame; import com.aspose.slides.ParagraphFormat; import com.aspose.slides.PortionFormat; import com.aspose.slides.Presentation; import com.aspose.slides.SaveFormat; import com.aspose.slides.ShapeType; import com.aspose.slides.TextAlignment; import com.aspose.slides.TextFrameFormat; import com.aspose.slides.TextVerticalType; import com.aspose.slides.examples.Utils; public class SettingTextFormattingInsideTable { public static void main(String[] args) { //ExStart:SettingTextFormattingInsideTable // The path to the documents directory. String dataDir = Utils.getDataDir(SettingTextFormattingInsideTable.class); // Instantiate Presentation class that represents PPTX Presentation pres = new Presentation(); // Access first slide ISlide sld = pres.getSlides().get_Item(0); ITable someTable = (ITable)pres.getSlides().get_Item(0).getShapes().get_Item(0); // let's say that the first shape on the first slide is a table // setting table cells' font height PortionFormat portionFormat = new PortionFormat(); portionFormat.setFontHeight(25); someTable.setTextFormat(portionFormat); // setting table cells' text alignment and right margin in one call ParagraphFormat paragraphFormat = new ParagraphFormat(); paragraphFormat.setAlignment(TextAlignment.Right); paragraphFormat.setMarginRight(20); someTable.setTextFormat(paragraphFormat); // setting table cells' text vertical type TextFrameFormat textFrameFormat = new TextFrameFormat(); textFrameFormat.setTextVerticalType(TextVerticalType.Vertical); someTable.setTextFormat(textFrameFormat); // Save the PPTX to Disk pres.save(dataDir + "Textbox.pptx", SaveFormat.Pptx); //ExEnd:SettingTextFormattingInsideTable } }
37.508197
161
0.689248
24364e4cd4e778af7e2fce184755a2e44e177713
37,124
lua
Lua
resources/[qb]/qb-garages/client/main.lua
p4zinee/server-data
b523650fc4b5a3465c7ffc1dde7330a16bb62d05
[ "CC0-1.0" ]
1
2022-01-05T15:17:06.000Z
2022-01-05T15:17:06.000Z
resources/[qb]/qb-garages/client/main.lua
p4zinee/server-data
b523650fc4b5a3465c7ffc1dde7330a16bb62d05
[ "CC0-1.0" ]
null
null
null
resources/[qb]/qb-garages/client/main.lua
p4zinee/server-data
b523650fc4b5a3465c7ffc1dde7330a16bb62d05
[ "CC0-1.0" ]
null
null
null
local currentHouseGarage = nil local hasGarageKey = nil local currentGarage = nil local OutsideVehicles = {} local PlayerGang = {} RegisterNetEvent('QBCore:Client:OnPlayerLoaded') AddEventHandler('QBCore:Client:OnPlayerLoaded', function() PlayerGang = QBCore.Functions.GetPlayerData().gang end) RegisterNetEvent('QBCore:Client:OnGangUpdate') AddEventHandler('QBCore:Client:OnGangUpdate', function(gang) PlayerGang = gang end) RegisterNetEvent('qb-garages:client:setHouseGarage') AddEventHandler('qb-garages:client:setHouseGarage', function(house, hasKey) currentHouseGarage = house hasGarageKey = hasKey end) RegisterNetEvent('qb-garages:client:houseGarageConfig') AddEventHandler('qb-garages:client:houseGarageConfig', function(garageConfig) HouseGarages = garageConfig end) RegisterNetEvent('qb-garages:client:addHouseGarage') AddEventHandler('qb-garages:client:addHouseGarage', function(house, garageInfo) HouseGarages[house] = garageInfo end) RegisterNetEvent('qb-garages:client:takeOutDepot') AddEventHandler('qb-garages:client:takeOutDepot', function(vehicle) if OutsideVehicles ~= nil and next(OutsideVehicles) ~= nil then if OutsideVehicles[vehicle.plate] ~= nil then local Engine = GetVehicleEngineHealth(OutsideVehicles[vehicle.plate]) QBCore.Functions.SpawnVehicle(vehicle.vehicle, function(veh) QBCore.Functions.TriggerCallback('qb-garage:server:GetVehicleProperties', function(properties) QBCore.Functions.SetVehicleProperties(veh, properties) enginePercent = round(vehicle.engine / 10, 0) bodyPercent = round(vehicle.body / 10, 0) currentFuel = vehicle.fuel if vehicle.plate ~= nil then DeleteVehicle(OutsideVehicles[vehicle.plate]) OutsideVehicles[vehicle.plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end SetVehicleNumberPlateText(veh, vehicle.plate) SetEntityHeading(veh, Depots[currentGarage].takeVehicle.w) TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) exports['LegacyFuel']:SetFuel(veh, vehicle.fuel) SetEntityAsMissionEntity(veh, true, true) doCarDamage(veh, vehicle) TriggerServerEvent('qb-garage:server:updateVehicleState', 0, vehicle.plate, vehicle.garage) QBCore.Functions.Notify("Vehicle Off:Engine " .. enginePercent .. "% Body: " .. bodyPercent.. "% Fuel: "..currentFuel.. "%", "primary", 4500) TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(veh)) closeMenuFull() SetVehicleEngineOn(veh, true, true) end, vehicle.plate) TriggerEvent("vehiclekeys:client:SetOwner", vehicle.plate) end, Depots[currentGarage].spawnPoint, true) SetTimeout(250, function() TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(GetVehiclePedIsIn(PlayerPedId(), false))) end) else QBCore.Functions.SpawnVehicle(vehicle.vehicle, function(veh) QBCore.Functions.TriggerCallback('qb-garage:server:GetVehicleProperties', function(properties) QBCore.Functions.SetVehicleProperties(veh, properties) enginePercent = round(vehicle.engine / 10, 0) bodyPercent = round(vehicle.body / 10, 0) currentFuel = vehicle.fuel if vehicle.plate ~= nil then OutsideVehicles[vehicle.plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end SetVehicleNumberPlateText(veh, vehicle.plate) SetEntityHeading(veh, Depots[currentGarage].takeVehicle.w) TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) exports['LegacyFuel']:SetFuel(veh, vehicle.fuel) SetEntityAsMissionEntity(veh, true, true) doCarDamage(veh, vehicle) TriggerServerEvent('qb-garage:server:updateVehicleState', 0, vehicle.plate, vehicle.garage) QBCore.Functions.Notify("Vehicle Off:Engine " .. enginePercent .. "% Body: " .. bodyPercent.. "% Fuel: "..currentFuel.. "%", "primary", 4500) TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(veh)) closeMenuFull() SetVehicleEngineOn(veh, true, true) end, vehicle.plate) TriggerEvent("vehiclekeys:client:SetOwner", vehicle.plate) end, Depots[currentGarage].spawnPoint, true) SetTimeout(250, function() TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(GetVehiclePedIsIn(PlayerPedId(), false))) end) end else QBCore.Functions.SpawnVehicle(vehicle.vehicle, function(veh) QBCore.Functions.TriggerCallback('qb-garage:server:GetVehicleProperties', function(properties) QBCore.Functions.SetVehicleProperties(veh, properties) enginePercent = round(vehicle.engine / 10, 0) bodyPercent = round(vehicle.body / 10, 0) currentFuel = vehicle.fuel if vehicle.plate ~= nil then OutsideVehicles[vehicle.plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end SetVehicleNumberPlateText(veh, vehicle.plate) SetEntityHeading(veh, Depots[currentGarage].takeVehicle.w) TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) exports['LegacyFuel']:SetFuel(veh, vehicle.fuel) SetEntityAsMissionEntity(veh, true, true) doCarDamage(veh, vehicle) TriggerServerEvent('qb-garage:server:updateVehicleState', 0, vehicle.plate, vehicle.garage) QBCore.Functions.Notify("Vehicle Off:Engine " .. enginePercent .. "% Body: " .. bodyPercent.. "% Fuel: "..currentFuel.. "%", "primary", 4500) TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(veh)) closeMenuFull() SetVehicleEngineOn(veh, true, true) end, vehicle.plate) TriggerEvent("vehiclekeys:client:SetOwner", vehicle.plate) end, Depots[currentGarage].spawnPoint, true) SetTimeout(250, function() TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(GetVehiclePedIsIn(PlayerPedId(), false))) end) end end) DrawText3Ds = function(x, y, z, text) SetTextScale(0.35, 0.35) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(true) AddTextComponentString(text) SetDrawOrigin(x,y,z, 0) DrawText(0.0, 0.0) local factor = (string.len(text)) / 370 DrawRect(0.0, 0.0+0.0125, 0.017+ factor, 0.03, 0, 0, 0, 75) ClearDrawOrigin() end Citizen.CreateThread(function() for k, v in pairs(Garages) do if v.showBlip then local Garage = AddBlipForCoord(Garages[k].takeVehicle.x, Garages[k].takeVehicle.y, Garages[k].takeVehicle.z) SetBlipSprite (Garage, 357) SetBlipDisplay(Garage, 4) SetBlipScale (Garage, 0.65) SetBlipAsShortRange(Garage, true) SetBlipColour(Garage, 3) BeginTextCommandSetBlipName("STRING") AddTextComponentSubstringPlayerName(Garages[k].label) EndTextCommandSetBlipName(Garage) end end for k, v in pairs(Depots) do if v.showBlip then local Depot = AddBlipForCoord(Depots[k].takeVehicle.x, Depots[k].takeVehicle.y, Depots[k].takeVehicle.z) SetBlipSprite (Depot, 68) SetBlipDisplay(Depot, 4) SetBlipScale (Depot, 0.7) SetBlipAsShortRange(Depot, true) SetBlipColour(Depot, 5) BeginTextCommandSetBlipName("STRING") AddTextComponentSubstringPlayerName(Depots[k].label) EndTextCommandSetBlipName(Depot) end end end) function MenuGarage() ped = PlayerPedId(); MenuTitle = "Garage" ClearMenu() Menu.addButton("My Vehicles", "VehicleList", nil) Menu.addButton("Close Menu", "close", nil) end function GangMenuGarage() ped = PlayerPedId(); MenuTitle = "Garage" ClearMenu() Menu.addButton("My Vehicles", "GangVehicleList", nil) Menu.addButton("Close Menu", "close", nil) end function MenuDepot() ped = PlayerPedId(); MenuTitle = "Impound" ClearMenu() Menu.addButton("Depot Vehicles", "DepotList", nil) Menu.addButton("Close Menu", "close", nil) end function MenuHouseGarage(house) ped = PlayerPedId(); MenuTitle = HouseGarages[house].label ClearMenu() Menu.addButton("My Vehicles", "HouseGarage", house) Menu.addButton("Close Menu", "close", nil) end function HouseGarage(house) QBCore.Functions.TriggerCallback("qb-garage:server:GetHouseVehicles", function(result) ped = PlayerPedId(); MenuTitle = "Depot Vehicles :" ClearMenu() if result == nil then QBCore.Functions.Notify("You have no vehicles in your garage", "error", 5000) closeMenuFull() else Menu.addButton(HouseGarages[house].label, "HouseGarage", HouseGarages[house].label) for k, v in pairs(result) do enginePercent = round(v.engine / 10, 0) bodyPercent = round(v.body / 10, 0) currentFuel = v.fuel curGarage = HouseGarages[house].label if v.state == 0 then v.state = "Out" elseif v.state == 1 then v.state = "Garaged" elseif v.state == 2 then v.state = "Impound" end Menu.addButton(QBCore.Shared.Vehicles[v.vehicle]["name"], "TakeOutGarageVehicle", v, v.state, " Motor: " .. enginePercent.."%", " Body: " .. bodyPercent.."%", " Fuel: "..currentFuel.."%") end end Menu.addButton("Back", "MenuHouseGarage", house) end, house) end function getPlayerVehicles(garage) local vehicles = {} return vehicles end function DepotList() QBCore.Functions.TriggerCallback("qb-garage:server:GetDepotVehicles", function(result) ped = PlayerPedId(); MenuTitle = "Impounded Vehicles :" ClearMenu() if result == nil then QBCore.Functions.Notify("There are no vehicles in the Impound", "error", 5000) closeMenuFull() else Menu.addButton(Depots[currentGarage].label, "DepotList", Depots[currentGarage].label) for k, v in pairs(result) do enginePercent = round(v.engine / 10, 0) bodyPercent = round(v.body / 10, 0) currentFuel = v.fuel if v.state == 0 then v.state = "Impound" end Menu.addButton(QBCore.Shared.Vehicles[v.vehicle]["name"], "TakeOutDepotVehicle", v, v.state .. " ($"..v.depotprice..",-)", " Motor: " .. enginePercent.."%", " Body: " .. bodyPercent.."%", " Fuel: "..currentFuel.."%") end end Menu.addButton("Back", "MenuDepot",nil) end) end function VehicleList() QBCore.Functions.TriggerCallback("qb-garage:server:GetUserVehicles", function(result) ped = PlayerPedId(); MenuTitle = "My Vehicles :" ClearMenu() if result == nil then QBCore.Functions.Notify("You have no vehicles in this garage", "error", 5000) closeMenuFull() else Menu.addButton(Garages[currentGarage].label, "VehicleList", Garages[currentGarage].label) for k, v in pairs(result) do enginePercent = round(v.engine / 10, 0) bodyPercent = round(v.body / 10, 0) currentFuel = v.fuel curGarage = Garages[v.garage].label if v.state == 0 then v.state = "Out" elseif v.state == 1 then v.state = "Garaged" elseif v.state == 2 then v.state = "Impound" end Menu.addButton(QBCore.Shared.Vehicles[v.vehicle]["name"], "TakeOutVehicle", v, v.state, " Motor: " .. enginePercent .. "%", " Body: " .. bodyPercent.. "%", " Fuel: "..currentFuel.. "%") end end Menu.addButton("Back", "MenuGarage",nil) end, currentGarage) end function GangVehicleList() QBCore.Functions.TriggerCallback("qb-garage:server:GetUserVehicles", function(result) ped = PlayerPedId(); MenuTitle = "My Vehicles :" ClearMenu() if result == nil then QBCore.Functions.Notify("You have no vehicles in this garage", "error", 5000) closeMenuFull() else Menu.addButton(GangGarages[currentGarage].label, "GangVehicleList", GangGarages[currentGarage].label) for k, v in pairs(result) do enginePercent = round(v.engine / 10, 0) bodyPercent = round(v.body / 10, 0) currentFuel = v.fuel curGarage = GangGarages[v.garage].label if v.state == 0 then v.state = "Out" elseif v.state == 1 then v.state = "Garaged" elseif v.state == 2 then v.state = "Impound" end Menu.addButton(QBCore.Shared.Vehicles[v.vehicle]["name"], "TakeOutGangVehicle", v, v.state, " Motor: " .. enginePercent .. "%", " Body: " .. bodyPercent.. "%", " Fuel: "..currentFuel.. "%") end end Menu.addButton("Back", "MenuGarage",nil) end, currentGarage) end function TakeOutVehicle(vehicle) if vehicle.state == "Garaged" then enginePercent = round(vehicle.engine / 10, 1) bodyPercent = round(vehicle.body / 10, 1) currentFuel = vehicle.fuel QBCore.Functions.SpawnVehicle(vehicle.vehicle, function(veh) QBCore.Functions.TriggerCallback('qb-garage:server:GetVehicleProperties', function(properties) if vehicle.plate ~= nil then OutsideVehicles[vehicle.plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end QBCore.Functions.SetVehicleProperties(veh, properties) SetVehicleNumberPlateText(veh, vehicle.plate) SetEntityHeading(veh, Garages[currentGarage].spawnPoint.w) exports['LegacyFuel']:SetFuel(veh, vehicle.fuel) doCarDamage(veh, vehicle) SetEntityAsMissionEntity(veh, true, true) TriggerServerEvent('qb-garage:server:updateVehicleState', 0, vehicle.plate, vehicle.garage) QBCore.Functions.Notify("Vehicle Off:Engine " .. enginePercent .. "% Body: " .. bodyPercent.. "% Fuel: "..currentFuel.. "%", "primary", 4500) closeMenuFull() TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(veh)) SetVehicleEngineOn(veh, true, true) end, vehicle.plate) end, Garages[currentGarage].spawnPoint, true) elseif vehicle.state == "Out" then QBCore.Functions.Notify("Is your vehicle in the Depot", "error", 2500) elseif vehicle.state == "Impound" then QBCore.Functions.Notify("This vehicle was impounded by the Police", "error", 4000) end end function TakeOutGangVehicle(vehicle) if vehicle.state == "Garaged" then enginePercent = round(vehicle.engine / 10, 1) bodyPercent = round(vehicle.body / 10, 1) currentFuel = vehicle.fuel QBCore.Functions.SpawnVehicle(vehicle.vehicle, function(veh) QBCore.Functions.TriggerCallback('qb-garage:server:GetVehicleProperties', function(properties) if vehicle.plate ~= nil then OutsideVehicles[vehicle.plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end QBCore.Functions.SetVehicleProperties(veh, properties) SetVehicleNumberPlateText(veh, vehicle.plate) SetEntityHeading(veh, GangGarages[currentGarage].spawnPoint.w) exports['LegacyFuel']:SetFuel(veh, vehicle.fuel) doCarDamage(veh, vehicle) SetEntityAsMissionEntity(veh, true, true) TriggerServerEvent('qb-garage:server:updateVehicleState', 0, vehicle.plate, vehicle.garage) QBCore.Functions.Notify("Vehicle Off:Engine " .. enginePercent .. "% Body: " .. bodyPercent.. "% Fuel: "..currentFuel.. "%", "primary", 4500) closeMenuFull() TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(veh)) SetVehicleEngineOn(veh, true, true) end, vehicle.plate) end, GangGarages[currentGarage].spawnPoint, true) elseif vehicle.state == "Out" then QBCore.Functions.Notify("Is your vehicle in the Depot", "error", 2500) elseif vehicle.state == "Impound" then QBCore.Functions.Notify("This vehicle was impounded by the Police", "error", 4000) end end function TakeOutDepotVehicle(vehicle) if vehicle.state == "Impound" then TriggerServerEvent("qb-garage:server:PayDepotPrice", vehicle) Citizen.Wait(1000) end end function TakeOutGarageVehicle(vehicle) if vehicle.state == "Garaged" then QBCore.Functions.SpawnVehicle(vehicle.vehicle, function(veh) QBCore.Functions.TriggerCallback('qb-garage:server:GetVehicleProperties', function(properties) QBCore.Functions.SetVehicleProperties(veh, properties) enginePercent = round(vehicle.engine / 10, 1) bodyPercent = round(vehicle.body / 10, 1) currentFuel = vehicle.fuel if vehicle.plate ~= nil then OutsideVehicles[vehicle.plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end SetVehicleNumberPlateText(veh, vehicle.plate) SetEntityHeading(veh, HouseGarages[currentHouseGarage].takeVehicle.w) TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) exports['LegacyFuel']:SetFuel(veh, vehicle.fuel) SetEntityAsMissionEntity(veh, true, true) doCarDamage(veh, vehicle) TriggerServerEvent('qb-garage:server:updateVehicleState', 0, vehicle.plate, vehicle.garage) QBCore.Functions.Notify("Vehicle Off:Engine " .. enginePercent .. "% Body: " .. bodyPercent.. "% Fuel: "..currentFuel.. "%", "primary", 4500) closeMenuFull() TriggerEvent("vehiclekeys:client:SetOwner", GetVehicleNumberPlateText(veh)) SetVehicleEngineOn(veh, true, true) end, vehicle.plate) end, HouseGarages[currentHouseGarage].takeVehicle, true) end end function doCarDamage(currentVehicle, veh) smash = false damageOutside = false damageOutside2 = false local engine = veh.engine + 0.0 local body = veh.body + 0.0 if engine < 200.0 then engine = 200.0 end if engine > 1000.0 then engine = 1000.0 end if body < 150.0 then body = 150.0 end if body < 900.0 then smash = true end if body < 800.0 then damageOutside = true end if body < 500.0 then damageOutside2 = true end Citizen.Wait(100) SetVehicleEngineHealth(currentVehicle, engine) if smash then SmashVehicleWindow(currentVehicle, 0) SmashVehicleWindow(currentVehicle, 1) SmashVehicleWindow(currentVehicle, 2) SmashVehicleWindow(currentVehicle, 3) SmashVehicleWindow(currentVehicle, 4) end if damageOutside then SetVehicleDoorBroken(currentVehicle, 1, true) SetVehicleDoorBroken(currentVehicle, 6, true) SetVehicleDoorBroken(currentVehicle, 4, true) end if damageOutside2 then SetVehicleTyreBurst(currentVehicle, 1, false, 990.0) SetVehicleTyreBurst(currentVehicle, 2, false, 990.0) SetVehicleTyreBurst(currentVehicle, 3, false, 990.0) SetVehicleTyreBurst(currentVehicle, 4, false, 990.0) end if body < 1000 then SetVehicleBodyHealth(currentVehicle, 985.1) end end function close() Menu.hidden = true end function closeMenuFull() Menu.hidden = true currentGarage = nil ClearMenu() end function ClearMenu() Menu.GUI = {} Menu.buttonCount = 0 Menu.selection = 0 end Citizen.CreateThread(function() Citizen.Wait(1000) while true do Citizen.Wait(5) local ped = PlayerPedId() local pos = GetEntityCoords(ped) local inGarageRange = false for k, v in pairs(Garages) do local takeDist = #(pos - vector3(Garages[k].takeVehicle.x, Garages[k].takeVehicle.y, Garages[k].takeVehicle.z)) if takeDist <= 15 then inGarageRange = true DrawMarker(2, Garages[k].takeVehicle.x, Garages[k].takeVehicle.y, Garages[k].takeVehicle.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.2, 0.15, 200, 0, 0, 222, false, false, false, true, false, false, false) if takeDist <= 1.5 then if not IsPedInAnyVehicle(ped) then DrawText3Ds(Garages[k].takeVehicle.x, Garages[k].takeVehicle.y, Garages[k].takeVehicle.z + 0.5, '~g~E~w~ - Garage') if IsControlJustPressed(1, 177) and not Menu.hidden then close() PlaySound(-1, "SELECT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 0, 0, 1) end if IsControlJustPressed(0, 38) then MenuGarage() Menu.hidden = not Menu.hidden currentGarage = k end else DrawText3Ds(Garages[k].takeVehicle.x, Garages[k].takeVehicle.y, Garages[k].takeVehicle.z, Garages[k].label) end end Menu.renderGUI() if takeDist >= 4 and not Menu.hidden then closeMenuFull() end end local putDist = #(pos - vector3(Garages[k].putVehicle.x, Garages[k].putVehicle.y, Garages[k].putVehicle.z)) if putDist <= 25 and IsPedInAnyVehicle(ped) then inGarageRange = true DrawMarker(2, Garages[k].putVehicle.x, Garages[k].putVehicle.y, Garages[k].putVehicle.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.2, 0.15, 255, 255, 255, 255, false, false, false, true, false, false, false) if putDist <= 1.5 then DrawText3Ds(Garages[k].putVehicle.x, Garages[k].putVehicle.y, Garages[k].putVehicle.z + 0.5, '~g~E~w~ - Park Vehicle') if IsControlJustPressed(0, 38) then local curVeh = GetVehiclePedIsIn(ped) local plate = GetVehicleNumberPlateText(curVeh) QBCore.Functions.TriggerCallback('qb-garage:server:checkVehicleOwner', function(owned) if owned then local bodyDamage = math.ceil(GetVehicleBodyHealth(curVeh)) local engineDamage = math.ceil(GetVehicleEngineHealth(curVeh)) local totalFuel = exports['LegacyFuel']:GetFuel(curVeh) local passenger = GetVehicleMaxNumberOfPassengers(curVeh) CheckPlayers(curVeh) TriggerServerEvent('qb-garage:server:updateVehicleStatus', totalFuel, engineDamage, bodyDamage, plate, k) TriggerServerEvent('qb-garage:server:updateVehicleState', 1, plate, k) if plate ~= nil then OutsideVehicles[plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end QBCore.Functions.Notify("Vehicle Parked In, "..Garages[k].label, "primary", 4500) else QBCore.Functions.Notify("Nobody owns this vehicle", "error", 3500) end end, plate) end end end end if not inGarageRange then Citizen.Wait(1000) end end end) function CheckPlayers(vehicle) for i = -1, 5,1 do seat = GetPedInVehicleSeat(vehicle,i) if seat ~= 0 then TaskLeaveVehicle(seat,vehicle,0) SetVehicleDoorsLocked(vehicle) Wait(1500) QBCore.Functions.DeleteVehicle(vehicle) end end end Citizen.CreateThread(function() Citizen.Wait(1000) while true do Citizen.Wait(5) local ped = PlayerPedId() local pos = GetEntityCoords(ped) local inGarageRange = false if PlayerGang.name ~= nil then Name = PlayerGang.name.."garage" end for k, v in pairs(GangGarages) do if PlayerGang.name == GangGarages[k].job then local ballasDist = #(pos - vector3(GangGarages[Name].takeVehicle.x, GangGarages[Name].takeVehicle.y, GangGarages[Name].takeVehicle.z)) if ballasDist <= 15 then inGarageRange = true DrawMarker(2, GangGarages[Name].takeVehicle.x, GangGarages[Name].takeVehicle.y, GangGarages[Name].takeVehicle.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.2, 0.15, 200, 0, 0, 222, false, false, false, true, false, false, false) if ballasDist <= 1.5 then if not IsPedInAnyVehicle(ped) then DrawText3Ds(GangGarages[Name].takeVehicle.x, GangGarages[Name].takeVehicle.y, GangGarages[Name].takeVehicle.z + 0.5, '~g~E~w~ - Garage') if IsControlJustPressed(1, 177) and not Menu.hidden then close() PlaySound(-1, "SELECT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 0, 0, 1) end if IsControlJustPressed(0, 38) then GangMenuGarage() Menu.hidden = not Menu.hidden currentGarage = Name end else DrawText3Ds(GangGarages[Name].takeVehicle.x, GangGarages[Name].takeVehicle.y, GangGarages[Name].takeVehicle.z, GangGarages[Name].label) end end Menu.renderGUI() if ballasDist >= 4 and not Menu.hidden then closeMenuFull() end end local putDist = #(pos - vector3(GangGarages[Name].putVehicle.x, GangGarages[Name].putVehicle.y, GangGarages[Name].putVehicle.z)) if putDist <= 25 and IsPedInAnyVehicle(ped) then inGarageRange = true DrawMarker(2, GangGarages[Name].putVehicle.x, GangGarages[Name].putVehicle.y, GangGarages[Name].putVehicle.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.2, 0.15, 255, 255, 255, 255, false, false, false, true, false, false, false) if putDist <= 1.5 then DrawText3Ds(GangGarages[Name].putVehicle.x, GangGarages[Name].putVehicle.y, GangGarages[Name].putVehicle.z + 0.5, '~g~E~w~ - Park Vehicle') if IsControlJustPressed(0, 38) then local curVeh = GetVehiclePedIsIn(ped) local plate = GetVehicleNumberPlateText(curVeh) QBCore.Functions.TriggerCallback('qb-garage:server:checkVehicleOwner', function(owned) if owned then local bodyDamage = math.ceil(GetVehicleBodyHealth(curVeh)) local engineDamage = math.ceil(GetVehicleEngineHealth(curVeh)) local totalFuel = exports['LegacyFuel']:GetFuel(curVeh) CheckPlayers(curVeh) Wait(500) if DoesEntityExist(curVeh) then QBCore.Functions.Notify("The wasn't deleted, please check if is someone inside the car.", "error", 4500) else TriggerServerEvent('qb-garage:server:updateVehicleStatus', totalFuel, engineDamage, bodyDamage, plate, Name) TriggerServerEvent('qb-garage:server:updateVehicleState', 1, plate, Name) if plate ~= nil then OutsideVehicles[plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end QBCore.Functions.Notify("Vehicle Parked In, "..GangGarages[Name].label, "primary", 4500) end else QBCore.Functions.Notify("Nobody owns this vehicle", "error", 3500) end end, plate) end end end end end if not inGarageRange then Citizen.Wait(1000) end end end) Citizen.CreateThread(function() Citizen.Wait(2000) while true do Citizen.Wait(5) local ped = PlayerPedId() local pos = GetEntityCoords(ped) local inGarageRange = false if HouseGarages ~= nil and currentHouseGarage ~= nil then if hasGarageKey and HouseGarages[currentHouseGarage] ~= nil and HouseGarages[currentHouseGarage].takeVehicle ~= nil then local takeDist = #(pos - vector3(HouseGarages[currentHouseGarage].takeVehicle.x, HouseGarages[currentHouseGarage].takeVehicle.y, HouseGarages[currentHouseGarage].takeVehicle.z)) if takeDist <= 15 then inGarageRange = true DrawMarker(2, HouseGarages[currentHouseGarage].takeVehicle.x, HouseGarages[currentHouseGarage].takeVehicle.y, HouseGarages[currentHouseGarage].takeVehicle.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.2, 0.15, 200, 0, 0, 222, false, false, false, true, false, false, false) if takeDist < 2.0 then if not IsPedInAnyVehicle(ped) then DrawText3Ds(HouseGarages[currentHouseGarage].takeVehicle.x, HouseGarages[currentHouseGarage].takeVehicle.y, HouseGarages[currentHouseGarage].takeVehicle.z + 0.5, '~g~E~w~ - Garage') if IsControlJustPressed(1, 177) and not Menu.hidden then close() PlaySound(-1, "SELECT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 0, 0, 1) end if IsControlJustPressed(0, 38) then MenuHouseGarage(currentHouseGarage) Menu.hidden = not Menu.hidden end elseif IsPedInAnyVehicle(ped) then DrawText3Ds(HouseGarages[currentHouseGarage].takeVehicle.x, HouseGarages[currentHouseGarage].takeVehicle.y, HouseGarages[currentHouseGarage].takeVehicle.z + 0.5, '~g~E~w~ - To Park') if IsControlJustPressed(0, 38) then local curVeh = GetVehiclePedIsIn(ped) local plate = GetVehicleNumberPlateText(curVeh) QBCore.Functions.TriggerCallback('qb-garage:server:checkVehicleHouseOwner', function(owned) if owned then local bodyDamage = round(GetVehicleBodyHealth(curVeh), 1) local engineDamage = round(GetVehicleEngineHealth(curVeh), 1) local totalFuel = exports['LegacyFuel']:GetFuel(curVeh) CheckPlayers(curVeh) if DoesEntityExist(curVeh) then QBCore.Functions.Notify("The Vehicle wasn't deleted, please check if is someone inside the car.", "error", 4500) else TriggerServerEvent('qb-garage:server:updateVehicleStatus', totalFuel, engineDamage, bodyDamage, plate, currentHouseGarage) TriggerServerEvent('qb-garage:server:updateVehicleState', 1, plate, currentHouseGarage) QBCore.Functions.DeleteVehicle(curVeh) if plate ~= nil then OutsideVehicles[plate] = veh TriggerServerEvent('qb-garages:server:UpdateOutsideVehicles', OutsideVehicles) end QBCore.Functions.Notify("Vehicle Parked In, "..HouseGarages[currentHouseGarage], "primary", 4500) end else QBCore.Functions.Notify("Nobody owns this vehicle", "error", 3500) end end, plate, currentHouseGarage) end end Menu.renderGUI() end if takeDist > 1.99 and not Menu.hidden then closeMenuFull() end end end end if not inGarageRange then Citizen.Wait(5000) end end end) Citizen.CreateThread(function() Citizen.Wait(1000) while true do Citizen.Wait(5) local ped = PlayerPedId() local pos = GetEntityCoords(ped) local inGarageRange = false for k, v in pairs(Depots) do local takeDist = #(pos - vector3(Depots[k].takeVehicle.x, Depots[k].takeVehicle.y, Depots[k].takeVehicle.z)) if takeDist <= 15 then inGarageRange = true DrawMarker(2, Depots[k].takeVehicle.x, Depots[k].takeVehicle.y, Depots[k].takeVehicle.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.2, 0.15, 200, 0, 0, 222, false, false, false, true, false, false, false) if takeDist <= 1.5 then if not IsPedInAnyVehicle(ped) then DrawText3Ds(Depots[k].takeVehicle.x, Depots[k].takeVehicle.y, Depots[k].takeVehicle.z + 0.5, '~g~E~w~ - Garage') if IsControlJustPressed(1, 177) and not Menu.hidden then close() PlaySound(-1, "SELECT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 0, 0, 1) end if IsControlJustPressed(0, 38) then MenuDepot() Menu.hidden = not Menu.hidden currentGarage = k end end end Menu.renderGUI() if takeDist >= 4 and not Menu.hidden then closeMenuFull() end end end if not inGarageRange then Citizen.Wait(5000) end end end) function round(num, numDecimalPlaces) return tonumber(string.format("%." .. (numDecimalPlaces or 0) .. "f", num)) end
45.053398
287
0.568042
c671cb5facf5eb5b1969379304b31fb0a2a4c6cc
5,291
py
Python
jackal/scripts/dns_discover.py
mwgielen/jackal
7fe62732eb5194b7246215d5277fb37c398097bf
[ "MIT" ]
10
2018-01-17T20:11:30.000Z
2022-02-20T21:31:37.000Z
jackal/scripts/dns_discover.py
mwgielen/jackal
7fe62732eb5194b7246215d5277fb37c398097bf
[ "MIT" ]
null
null
null
jackal/scripts/dns_discover.py
mwgielen/jackal
7fe62732eb5194b7246215d5277fb37c398097bf
[ "MIT" ]
1
2018-06-21T16:47:16.000Z
2018-06-21T16:47:16.000Z
#!/usr/bin/env python3 import argparse import ipaddress import re import socket import subprocess import dns.resolver import dns.zone import psutil from jackal import HostSearch, RangeSearch from jackal.utils import print_error, print_notification, print_success def get_configured_dns(): """ Returns the configured DNS servers with the use f nmcli. """ ips = [] try: output = subprocess.check_output(['nmcli', 'device', 'show']) output = output.decode('utf-8') for line in output.split('\n'): if 'DNS' in line: pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" for hit in re.findall(pattern, line): ips.append(hit) except FileNotFoundError: pass return ips def get_resolv_dns(): """ Returns the dns servers configured in /etc/resolv.conf """ result = [] try: for line in open('/etc/resolv.conf', 'r'): if line.startswith('search'): result.append(line.strip().split(' ')[1]) except FileNotFoundError: pass return result def zone_transfer(address, dns_name): """ Tries to perform a zone transfer. """ ips = [] try: print_notification("Attempting dns zone transfer for {} on {}".format(dns_name, address)) z = dns.zone.from_xfr(dns.query.xfr(address, dns_name)) except dns.exception.FormError: print_notification("Zone transfer not allowed") return ips names = z.nodes.keys() print_success("Zone transfer successfull for {}, found {} entries".format(address, len(names))) for n in names: node = z[n] data = node.get_rdataset(dns.rdataclass.IN, dns.rdatatype.A) if data: # TODO add hostnames to entries. # hostname = n.to_text() for item in data.items: address = item.address ips.append(address) return ips def resolve_domains(domains, disable_zone=False): """ Resolves the list of domains and returns the ips. """ dnsresolver = dns.resolver.Resolver() ips = [] for domain in domains: print_notification("Resolving {}".format(domain)) try: result = dnsresolver.query(domain, 'A') for a in result.response.answer[0]: ips.append(str(a)) if not disable_zone: ips.extend(zone_transfer(str(a), domain)) except dns.resolver.NXDOMAIN as e: print_error(e) return ips def parse_ips(ips, netmask, include_public): """ Parses the list of ips, turns these into ranges based on the netmask given. Set include_public to True to include public IP adresses. """ hs = HostSearch() rs = RangeSearch() ranges = [] ips = list(set(ips)) included_ips = [] print_success("Found {} ips".format(len(ips))) for ip in ips: ip_address = ipaddress.ip_address(ip) if include_public or ip_address.is_private: # To stop the screen filling with ranges. if len(ips) < 15: print_success("Found ip: {}".format(ip)) host = hs.id_to_object(ip) host.add_tag('dns_discover') host.save() r = str(ipaddress.IPv4Network("{}/{}".format(ip, netmask), strict=False)) ranges.append(r) included_ips.append(ip) else: print_notification("Excluding ip {}".format(ip)) ranges = list(set(ranges)) print_success("Found {} ranges".format(len(ranges))) for rng in ranges: # To stop the screen filling with ranges. if len(ranges) < 15: print_success("Found range: {}".format(rng)) r = rs.id_to_object(rng) r.add_tag('dns_discover') r.save() stats = {} stats['ips'] = included_ips stats['ranges'] = ranges return stats def main(): netmask = '255.255.255.0' interfaces = psutil.net_if_addrs() for _, details in interfaces.items(): for detail in details: if detail.family == socket.AF_INET: ip_address = ipaddress.ip_address(detail.address) if not (ip_address.is_link_local or ip_address.is_loopback): netmask = detail.netmask break parser = argparse.ArgumentParser( description="Uses the configured DNS servers to estimate ranges.") parser.add_argument( "--include-public", help="Include public IP addresses", action="store_true") parser.add_argument( "-nm", "--netmask", help="The netmask to use to create ranges, default: {}".format(netmask), type=str, default=netmask) parser.add_argument("--no-zone", help="Disable to attempt to get a zone transfer from the dns server.", action="store_true") arguments = parser.parse_args() ips = [] ips.extend(get_configured_dns()) domains = get_resolv_dns() ips.extend(resolve_domains(domains, arguments.no_zone)) stats = parse_ips(ips, arguments.netmask, arguments.include_public) print_notification("Found {} ips and {} ranges".format( len(stats['ips']), len(stats['ranges']))) if __name__ == '__main__': main()
31.873494
128
0.603289
b0e4e08d3f60d564ecc66b464d36e7a461cbc1b0
4,393
py
Python
hubot/settings/dev.py
kilinger/marathon-rocketchat-hubot
682454b90265eb2c66ea222cf0c970370816a9e1
[ "BSD-3-Clause" ]
1
2018-07-10T07:03:12.000Z
2018-07-10T07:03:12.000Z
hubot/settings/dev.py
kilinger/marathon-rocketchat-hubot
682454b90265eb2c66ea222cf0c970370816a9e1
[ "BSD-3-Clause" ]
null
null
null
hubot/settings/dev.py
kilinger/marathon-rocketchat-hubot
682454b90265eb2c66ea222cf0c970370816a9e1
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # flake8: noqa from .base import * # noqa SITE_TITLE = SITE_TITLE + gettext_noop(u'(开发版)') CACHES = { 'default': env.cache_url(default='memcache://127.0.0.1:11211'), 'redis': env.cache_url('REDIS_URL', default='redis://127.0.0.1:6379/0'), } DATABASES = { 'default': env.db_url(default='postgresql://postgres:@127.0.0.1:5432/hubot') } MEDIA_URL = env('MEDIA_URL', default='/media/') STATIC_URL = env('STATIC_URL', default='/static/') try: import debug_toolbar # noqa except ImportError: HAS_DEBUG_TOOLBAR = False else: HAS_DEBUG_TOOLBAR = True if HAS_DEBUG_TOOLBAR: INSTALLED_APPS += ('debug_toolbar', 'template_timings_panel') DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = [env('INTERNAL_IPS', default='127.0.0.1')] MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', 'template_timings_panel.panels.TemplateTimings.TemplateTimings', ] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } try: import django_extensions # noqa except ImportError: django_extensions = None else: INSTALLED_APPS += ('django_extensions', ) try: import dbbackup # noqa except ImportError: dbbackup = None else: INSTALLED_APPS += ('dbbackup', ) DBBACKUP_STORAGE = 'dbbackup.storage.filesystem_storage' DBBACKUP_FILESYSTEM_DIRECTORY = root('../backups', ensure=True) MARATHON_SERVERS = env.list('MARATHON_SERVERS', default=['http://127.0.0.1:8080']) MARATHON_USERNAME = env('MARATHON_USERNAME', default=None) MARATHON_PASSWORD = env('MARATHON_PASSWORD', default=None) OS_USER_NAME = env('OS_USERNAME', default=None) OS_PASSWORD = env('OS_PASSWORD', default=None) OS_TENANT_NAME = env('OS_TENANT_NAME', default=None) OS_AUTH_URL = env('OS_AUTH_URL', default=None) MIN_INSTANCES = env.int('MIN_INSTANCES', default=0) MIN_CPUS = env.float('MIN_CPUS', default=0) MAX_CPUS = env.float('MAX_CPUS', default=8) MIN_MEM = env.float('MIN_MEM', default=0) MAX_MEM = env.float('MAX_MEM', default=16 * 1024) MIN_SIZE = env.int('MIN_SIZE', default=0) MAX_SIZE = env.int('MAX_SIZE', default=1000) MIN_BACKUP_KEEP = env.int('MIN_BACKUP_KEEP', default=0) MAX_BACKUP_KEEP = env.int('MAX_BACKUP_KEEP', default=100) TIMEOUT_FOR_STATUS_FINISHED = env.int('TIMEOUT_FOR_STATUS_FINISHED', default=60 * 15) # seconds MINIMUM_HEALTH_CAPACITY = env.float('MINIMUM_HEALTH_CAPACITY', default=0.6) BUILD_CALLBACK_URI = env('BUILD_CALLBACK_URI', default="http://127.0.0.1:8000") BUILD_VOLUMES = env('BUILD_VOLUMES', default="/var/run/docker.sock:/var/run/docker.sock, /root/.docker:/.docker") BUILD_ENVS = env('BUILD_ENVS', default="DOCKER_DAEMON_ARGS=--mtu=1450") EREMETIC_URL = env('EREMETIC_URL', default="http://127.0.0.1:8000") EREMETIC_USERNAME = env('EREMETIC_USERNAME', default=None) EREMETIC_PASSWORD = env('EREMETIC_PASSWORD', default=None) BROKER_URL = env('BROKER_URL', default="amqp://username:[email protected]:5672/") # celery once ONCE_REDIS_URL = env('ONCE_REDIS_URL', default='redis://127.0.0.1:6379/0') ONCE_DEFAULT_TIMEOUT = env.int('ONCE_DEFAULT_TIMEOUT', default=60 * 60)
30.72028
113
0.684726
c8ccd3ae57dc78303573c7d6aceb486afb05a4d4
9,055
css
CSS
public/css/styles.css
Adry2612/LiveMore
c5c922366a015ff30ec90e4a76029486ca3295ea
[ "MIT" ]
null
null
null
public/css/styles.css
Adry2612/LiveMore
c5c922366a015ff30ec90e4a76029486ca3295ea
[ "MIT" ]
null
null
null
public/css/styles.css
Adry2612/LiveMore
c5c922366a015ff30ec90e4a76029486ca3295ea
[ "MIT" ]
null
null
null
@import url("https://fonts.googleapis.com/css2?family=Forum&family=Metrophobic&family=Montserrat&display=swap"); @import url("https://fonts.googleapis.com/css2?family=Raleway:wght@300;400;500&display=swap"); /* Colores */ html { -webkit-box-sizing: border-box; box-sizing: border-box; font-family: 'Montserrat', sans-serif; } *, *:before, *:after { -webkit-box-sizing: inherit; box-sizing: inherit; margin: 0; } body { font-size: 62.5%; } body .principal { background-image: url("../assets/img/landing-page.jpg"); background-size: cover; min-height: 100vh; opacity: 0.85; } body .principal .navegacion { width: 100vw; height: 10vh; } body .principal .navegacion .contenedor-navegacion { width: 100%; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; -webkit-box-align: center; -ms-flex-align: center; align-items: center; font-size: 1.2rem; } body .principal .navegacion .contenedor-navegacion .logo { display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-line-pack: center; align-content: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; width: 50%; height: 80%; padding: 0, 0.2rem; } body .principal .navegacion .contenedor-navegacion .enlaces { width: 50%; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } body .principal .navegacion .contenedor-navegacion .enlaces .close { display: none; } body .principal .navegacion .contenedor-navegacion .enlaces a { text-decoration: none; margin: 1.5rem; display: inline-block; position: relative; color: #433520; -webkit-transition: color 0.2s ease, -webkit-transform 0.2s ease; transition: color 0.2s ease, -webkit-transform 0.2s ease; transition: transform 0.2s ease, color 0.2s ease; transition: transform 0.2s ease, color 0.2s ease, -webkit-transform 0.2s ease; } body .principal .navegacion .contenedor-navegacion .enlaces a:hover { -webkit-transform: translateX(4px); transform: translateX(4px); color: #4AFF0B; } body .principal .navegacion .contenedor-navegacion .menu { display: none; } body .principal .eslogan { width: 45%; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: left; -ms-flex-align: left; align-items: left; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; position: absolute; top: 20%; left: 15%; } body .principal .eslogan span { font-family: 'Raleway', sans-serif; font-size: 4.5rem; line-height: 7rem; color: #025955; z-index: 2; } body .principal .eslogan span.light { font-weight: 300; } body .principal .eslogan span.regular { font-weight: 400; } body .principal .eslogan span.medium { font-weight: 500; } body .principal .eslogan svg { position: relative; bottom: 1rem; left: 3rem; fill: #433520; width: 15rem; overflow: visible; z-index: 1; } body .principal .registrate { position: absolute; left: 15%; bottom: 5rem; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; } body .principal .registrate p { font-size: 1rem; margin-bottom: 1rem; } body .principal .registrate button { overflow: hidden; padding: 12px 30px; border-radius: 6px; background-color: #4AFF0B; color: #433520; position: relative; display: inline-block; border: none; } body .principal .registrate button::before { content: ''; display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #5851ec; opacity: 0.1; -webkit-transform: scaleX(0); transform: scaleX(0); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; -webkit-transition: -webkit-transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); transition: -webkit-transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); transition: transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); transition: transform 0.6s cubic-bezier(0.53, 0.21, 0, 1), -webkit-transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); will-change: transform; } body .principal .registrate button:hover::before { -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transform: scaleX(1); transform: scaleX(1); } .horizontalOverlay { overflow: hidden; padding: 12px 30px; border-radius: 6px; border: none; background-color: #FDE8CD; color: #5851ec; position: relative; display: inline-block; } .horizontalOverlay::before { content: ''; display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #5851ec; opacity: 0.1; -webkit-transform: scaleX(0); transform: scaleX(0); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; -webkit-transition: -webkit-transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); transition: -webkit-transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); transition: transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); transition: transform 0.6s cubic-bezier(0.53, 0.21, 0, 1), -webkit-transform 0.6s cubic-bezier(0.53, 0.21, 0, 1); will-change: transform; } .horizontalOverlay:hover::before { -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transform: scaleX(1); transform: scaleX(1); } @media screen and (max-width: 1024px) { body .principal .navegacion.contenedor-navegacion .enlaces { display: -webkit-box; display: -ms-flexbox; display: flex; position: fixed; -ms-flex-pack: distribute; justify-content: space-around; width: 100%; height: 100%; left: 0; top: 0; background-color: #433520; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; -webkit-transform: translate(-100%); transform: translate(-100%); -webkit-transition: all 0.3s ease; transition: all 0.3s ease; z-index: 2; } body .principal .navegacion.contenedor-navegacion .enlaces.activo { -webkit-transform: translate(0%); transform: translate(0%); z-index: 5; } body .principal .navegacion.contenedor-navegacion .enlaces.activo .close { display: inline; position: fixed; top: 5%; right: 10%; } body .principal .navegacion.contenedor-navegacion .enlaces.activo .close svg { fill: wheat; -webkit-transition: color 0.2s ease, -webkit-transform 0.2s ease; transition: color 0.2s ease, -webkit-transform 0.2s ease; transition: transform 0.2s ease, color 0.2s ease; transition: transform 0.2s ease, color 0.2s ease, -webkit-transform 0.2s ease; } body .principal .navegacion.contenedor-navegacion .enlaces.activo .close svg:hover { -webkit-transform: translateX(4px); transform: translateX(4px); fill: red; cursor: pointer; } body .principal .navegacion.contenedor-navegacion .enlaces.activo a { position: relative; display: inline; color: wheat; } body .principal .navegacion.contenedor-navegacion .enlaces.activo a:hover { -webkit-transform: translateX(4px); transform: translateX(4px); color: #4AFF0B; } body .principal .navegacion.contenedor-navegacion .menu { position: relative; display: inline-block; -webkit-transition: color 0.2s ease, -webkit-transform 0.2s ease; transition: color 0.2s ease, -webkit-transform 0.2s ease; transition: transform 0.2s ease, color 0.2s ease; transition: transform 0.2s ease, color 0.2s ease, -webkit-transform 0.2s ease; right: 2rem; } body .principal .navegacion.contenedor-navegacion .menu:hover { -webkit-transform: translateX(4px); transform: translateX(4px); fill: #4AFF0B; cursor: pointer; } } @media screen and (max-height: 657px) and (max-width: 1024px) { body .principal .eslogan span { font-size: 3.5rem; line-height: 6rem; } body .principal .registrate { bottom: 3rem; } } @media screen and (max-width: 685px) { body .principal { background-image: url("../assets/img/landing-responsive.jpg"); } body .principal .eslogan span { font-size: 3rem; line-height: 4rem; } body .principal .eslogan svg { width: 12rem; bottom: 0.8rem; left: 2.5rem; } body .principal .registrate { left: 10%; } } /*# sourceMappingURL=styles.css.map */
25.945559
115
0.659194
a1831cf2e688420247b8b19a96f3272f844e47ba
4,261
tsx
TypeScript
components/src/hardware-sim/Pipette/__tests__/PipetteRender.test.tsx
anuwrag/opentrons
28c8d76a19e367c6bd38f5290faaa32abf378715
[ "Apache-2.0" ]
235
2017-10-27T20:37:27.000Z
2022-03-30T14:09:49.000Z
components/src/hardware-sim/Pipette/__tests__/PipetteRender.test.tsx
anuwrag/opentrons
28c8d76a19e367c6bd38f5290faaa32abf378715
[ "Apache-2.0" ]
8,425
2017-10-26T15:25:43.000Z
2022-03-31T23:54:26.000Z
components/src/hardware-sim/Pipette/__tests__/PipetteRender.test.tsx
anuwrag/opentrons
28c8d76a19e367c6bd38f5290faaa32abf378715
[ "Apache-2.0" ]
130
2017-11-09T21:02:37.000Z
2022-03-15T18:01:24.000Z
import * as React from 'react' import { when, resetAllWhenMocks } from 'jest-when' import { render } from '@testing-library/react' import _uncasted_fixtureTiprack300Ul from '@opentrons/shared-data/labware/fixtures/2/fixture_tiprack_300_ul.json' import { anyProps, partialComponentPropsMatcher } from '../../../testing/utils' import { RobotCoordsForeignDiv } from '../../Deck/RobotCoordsForeignDiv' import { PipetteRender } from '../PipetteRender' import { EmanatingNozzle } from '../EmanatingNozzle' import { EightEmanatingNozzles } from '../EightEmanatingNozzles' import { SINGLE_CHANNEL_PIPETTE_WIDTH, SINGLE_CHANNEL_PIPETTE_HEIGHT, MULTI_CHANNEL_PIPETTE_WIDTH, MULTI_CHANNEL_PIPETTE_HEIGHT, } from '../constants' import type { LabwareDefinition2 } from '@opentrons/shared-data' jest.mock('../../Deck/RobotCoordsForeignDiv') jest.mock('../EmanatingNozzle') jest.mock('../EightEmanatingNozzles') const fixtureTiprack300Ul = _uncasted_fixtureTiprack300Ul as LabwareDefinition2 const mockRobotCoordsForeignDiv = RobotCoordsForeignDiv as jest.MockedFunction< typeof RobotCoordsForeignDiv > const mockEmanatingNozzle = EmanatingNozzle as jest.MockedFunction< typeof EmanatingNozzle > const mockEightEmanatingNozzles = EightEmanatingNozzles as jest.MockedFunction< typeof EightEmanatingNozzles > describe('PipetteRender', () => { beforeEach(() => { when(mockRobotCoordsForeignDiv).mockReturnValue(<div></div>) }) afterEach(() => { resetAllWhenMocks() }) describe('when the pipette is single channel', () => { beforeEach(() => { when(mockRobotCoordsForeignDiv) .calledWith( partialComponentPropsMatcher({ width: SINGLE_CHANNEL_PIPETTE_WIDTH, height: SINGLE_CHANNEL_PIPETTE_HEIGHT, }) ) .mockImplementation(({ children }) => ( <div> {`rectangle with width ${SINGLE_CHANNEL_PIPETTE_WIDTH} and height ${SINGLE_CHANNEL_PIPETTE_HEIGHT}`}{' '} {children} </div> )) when(mockEmanatingNozzle) .calledWith(anyProps()) .mockReturnValue(<div>mock emanating nozzle</div>) }) it('should render a rectangle with the correct dimensions', () => { const { getByText } = render( <PipetteRender labwareDef={fixtureTiprack300Ul} pipetteName={'p1000_single'} /> ) getByText( `rectangle with width ${SINGLE_CHANNEL_PIPETTE_WIDTH} and height ${SINGLE_CHANNEL_PIPETTE_HEIGHT}` ) mockEmanatingNozzle.mockRestore() }) it('should render a single emanating nozzle', () => { const { getByText } = render( <PipetteRender labwareDef={fixtureTiprack300Ul} pipetteName={'p1000_single'} /> ) getByText('mock emanating nozzle') expect(mockEightEmanatingNozzles).not.toHaveBeenCalled() }) }) describe('when the pipette is 8 channel', () => { beforeEach(() => { when(mockRobotCoordsForeignDiv) .calledWith( partialComponentPropsMatcher({ width: MULTI_CHANNEL_PIPETTE_WIDTH, height: MULTI_CHANNEL_PIPETTE_HEIGHT, }) ) .mockImplementation(({ children }) => ( <div> {`rectangle with width ${MULTI_CHANNEL_PIPETTE_WIDTH} and height ${MULTI_CHANNEL_PIPETTE_HEIGHT}`}{' '} {children} </div> )) when(mockEightEmanatingNozzles) .calledWith(anyProps()) .mockReturnValue(<div>mock eight emanating nozzles</div>) }) it('should render a rectangle with the correct dimensions', () => { const { getByText } = render( <PipetteRender labwareDef={fixtureTiprack300Ul} pipetteName={'p10_multi'} /> ) getByText( `rectangle with width ${MULTI_CHANNEL_PIPETTE_WIDTH} and height ${MULTI_CHANNEL_PIPETTE_HEIGHT}` ) mockEightEmanatingNozzles.mockRestore() }) it('should render eight emanating nozzles', () => { const { getByText } = render( <PipetteRender labwareDef={fixtureTiprack300Ul} pipetteName={'p10_multi'} /> ) getByText('mock eight emanating nozzles') }) }) })
32.037594
117
0.657357
6d012ce1c729d053651aacc6e81a66b4df384b03
1,118
tsx
TypeScript
src/pages/Record/List.tsx
wallaceAzevedo/Crud-com-React--Typescript-e-React
5892cc78a770c0b677a673e47c1d885e192f8233
[ "MIT" ]
null
null
null
src/pages/Record/List.tsx
wallaceAzevedo/Crud-com-React--Typescript-e-React
5892cc78a770c0b677a673e47c1d885e192f8233
[ "MIT" ]
null
null
null
src/pages/Record/List.tsx
wallaceAzevedo/Crud-com-React--Typescript-e-React
5892cc78a770c0b677a673e47c1d885e192f8233
[ "MIT" ]
null
null
null
import { Record } from '../../interfaces/RecordEntities'; import { RecordListProps } from '../../interfaces/PagesProps'; import { usePage } from '../../contexts/Page'; import { Status } from '../../components/Status'; import { RecordError } from '../../components/RecordError'; export const RecordList = <T extends Record>({ ListItem, records, emptyRecord, activeRecord, setActiveRecord, loading, error, }: RecordListProps<T>) => { const { page } = usePage(); return ( <div className="list"> {error && <RecordError error={error} />} <div> <h2>{page}</h2> <button className="bt-new" onClick={() => setActiveRecord(emptyRecord)}> New </button> <ul> {records.map((record) => ( <li key={record.id} className={record.id === activeRecord?.id ? 'active' : ''} onClick={() => setActiveRecord(record)} > <ListItem record={record} /> </li> ))} </ul> </div> {loading && <Status text="Loading..." />} </div> ); };
26.619048
80
0.528623
2c36cea73bd5b397283c4173a823bdbf5f278ab4
12,089
py
Python
CICE-interface/CICE/configuration/scripts/timeseries.py
minsukji/ci-debug
3e8bbbe6652b702b61d2896612f6aa8e4aa6c803
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
CICE-interface/CICE/configuration/scripts/timeseries.py
minsukji/ci-debug
3e8bbbe6652b702b61d2896612f6aa8e4aa6c803
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
CICE-interface/CICE/configuration/scripts/timeseries.py
minsukji/ci-debug
3e8bbbe6652b702b61d2896612f6aa8e4aa6c803
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
#!/usr/bin/env python ''' This script generates timeseries plots of CICE diagnostic output. It is generated to replicate the previous timeseries.csh script. Written by: Matthew Turner Date: August, 2019 ''' import os import sys import logging import numpy as np def find_logfile(log_dir): ''' This function searches for the most recently created log file in the provided directory. ''' logger.debug('Getting a list of files in {}'.format(log_dir)) try: path = '{}/logs'.format(log_dir.rstrip('/')) files = [os.path.join(path,f) for f in os.listdir('{}/logs'.format(log_dir)) \ if f.startswith('cice.runlog')] except: path = log_dir files = [os.path.join(path,f) for f in os.listdir(log_dir) if f.startswith('cice.runlog')] # Check if any files were found. If not, exit if len(files) == 0: logger.error('No cice.runlog* files found. Please make sure you are passing the \ correct directory.') sys.exit(1) # Get the most recently created file outfile = max(files, key = os.path.getctime) logger.debug('List of files = {}'.format([f for f in files])) logger.debug('Most recent file is {}'.format(outfile)) return outfile def get_data(logfile,field): ''' This function extracts data from a CICE log file for the specific field. ''' import datetime import re logger.debug('Extracting data for {}'.format(field)) # Build the regular expression to extract the data field_regex = field.replace('(','\(').replace('^','\^').replace(')','\)') number_regex = '[-+]?\d+\.?\d+([eE][-+]?\d+)?' my_regex = '^{}\s+=\s+({})\s+({})'.format(field_regex,number_regex,number_regex) dtg = [] arctic = [] antarctic = [] with open(logfile) as f: for line in f.readlines(): m1 = re.search('istep1:\s+(\d+)\s+idate:\s+(\d+)\s+sec:\s+(\d+)', line) if m1: # Extract the current date-time group from the file date = m1.group(2) seconds = int(m1.group(3)) hours = seconds // 3600 minutes = (seconds - hours*3600) // 60 leftover = seconds - hours*3600 - minutes*60 curr_date = '{}-{:02d}:{:02d}:{:02d}'.format(date,hours,minutes,leftover) dtg.append(datetime.datetime.strptime(curr_date, '%Y%m%d-%H:%M:%S')) logger.debug('Currently on timestep {}'.format(dtg[-1])) m = re.search(my_regex, line) if m: # Extract the data from the file if 'E' in m.group(1) or 'e' in m.group(1): expon = True else: expon = False arctic.append(float(m.group(1))) antarctic.append(float(m.group(3))) logger.debug(' Arctic = {}, Antarctic = {}'.format(arctic[-1], antarctic[-1])) return dtg, arctic, antarctic, expon def latexit(string): s = string[::-1].replace('(','($',1) return (s.replace(')','$)',1))[::-1] def plot_timeseries(log, field, dtg, arctic, antarctic, expon, dtg_base=None, arctic_base=None, \ antarctic_base=None, base_dir=None, grid=False): ''' Plot the timeseries data from the CICE log file ''' import re casename = re.sub(r"/logs", "", os.path.abspath(log).rstrip('/')).split('/')[-1] if base_dir: base_casename = re.sub(r"/logs", "", os.path.abspath(base_dir).rstrip('/')).split('/')[-1] # Load the plotting libraries, but set the logging level for matplotlib # to WARNING so that matplotlib debugging info is not printed when running # with '-v' logging.getLogger('matplotlib').setLevel(logging.WARNING) import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as ticker fig = plt.figure(figsize=(12,8)) ax = fig.add_axes([0.05,0.08,0.9,0.9]) # Add the arctic data to the plot ax.plot(dtg,arctic,label='Arctic') # Add the baseline arctic data to the plot, if available if arctic_base: ax.plot(dtg_base,arctic_base,label='Baseline Arctic') # Add the antarctic data to the plot ax.plot(dtg,antarctic,label='Antarctic') # Add the baseline antarctic data to the plot, if available if antarctic_base: ax.plot(dtg_base,antarctic_base,label='Baseline Antarctic') ax.set_xlabel('') ax.set_title('{} Diagnostic Output'.format(latexit(field))) ax.set_ylabel(latexit(field)) # Format the x-axis labels ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d')) ax.xaxis.set_minor_locator(mdates.MonthLocator()) # Add a text box that prints the test case name and the baseline case name (if given) try: text_field = "Test/Case: {}\nBaseline: {}".format(casename,base_casename) from matplotlib.offsetbox import AnchoredText anchored_text = AnchoredText(text_field,loc=2) ax.add_artist(anchored_text) except: text_field = "Test/Case: {}".format(casename) from matplotlib.offsetbox import AnchoredText anchored_text = AnchoredText(text_field,loc=2) ax.add_artist(anchored_text) ax.legend(loc='upper right') # Add grid lines if the `--grid` argument was passed at the command line. if grid: ax.grid(ls='--') # Reduce the number of ticks on the y axis nbins = 10 try: minval = min( \ min(min(arctic), min(antarctic)), \ min(min(arctic_base), min(antarctic_base))) maxval = max( \ max(max(arctic), max(antarctic)), \ max(max(arctic_base), max(antarctic_base))) except: minval = min(min(arctic), min(antarctic)) maxval = max(max(arctic), max(antarctic)) step = (maxval-minval)/nbins ax.yaxis.set_ticks(np.arange(minval, maxval+step, step)) # Format the y-axis tick labels, based on whether or not the values in the log file # are in scientific notation or float notation. if expon: ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.3e')) else: ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.5f')) # Rotate and right align the x labels for tick in ax.get_xticklabels(): tick.set_rotation(45) # Create an output file and save the figure field_tmp = field.split('(')[0].rstrip() try: outfile = '{}_{}_base-{}.png'.format(field_tmp.replace(' ','_'), casename,base_casename) except: outfile = '{}_{}.png'.format(field_tmp.replace(' ','_'), casename) logger.info('Saving file to {}'.format(outfile)) plt.savefig(outfile,dpi=300,bbox_inches='tight') def main(): import argparse parser = argparse.ArgumentParser(description="To generate timeseries plots, this script \ can be passed a directory containing a logs/ subdirectory, \ or it can be run in the directory with the log files, \ without being passed a directory. It will pull the \ diagnostic data from the most recently modified log file.\ \ If no flags are passed selecting the variables to plot, \ then plots will be created for all available variables.") parser.add_argument('log_dir', nargs='?', default=os.getcwd(), \ help="Path to diagnostic output log file. A specific log file can \ be passed, or a case directory. If a directory is passed, \ the most recent log file will be used. If no directory or \ file is passed, the script will look for a log file in the \ current directory.") parser.add_argument('--bdir',dest='base_dir', help='Path to the the log file for a baseline \ dataset, if desired. A specific log file or case directory can \ be passed. If a directory is passed, the most recent log file \ will be used.') parser.add_argument('-v', '--verbose', dest='verbose', help='Print debug output?', \ action='store_true') parser.add_argument('--area', dest='area', help='Create a plot for total ice area?', \ action='store_true') parser.add_argument('--extent', dest='extent', help='Create a plot for total ice extent?', \ action='store_true') parser.add_argument('--volume', dest='ice_volume', help='Create a plot for total ice volume?', \ action='store_true') parser.add_argument('--snw_vol', dest='snow_volume', help='Create a plot for total snow \ volume?', action='store_true') parser.add_argument('--speed', dest='speed', help='Create a plot for rms ice speed?', \ action='store_true') parser.add_argument('--grid',dest='grid', help='Add grid lines to the figures?', \ action='store_true') # Set the defaults for the command line options parser.set_defaults(verbose=False) parser.set_defaults(area=False) parser.set_defaults(extent=False) parser.set_defaults(ice_volume=False) parser.set_defaults(snow_volume=False) parser.set_defaults(speed=False) parser.set_defaults(grid=False) args = parser.parse_args() # If no fields are passed, plot all fields if not ( args.area or args.extent or args.ice_volume or args.snow_volume or args.speed ): args.area = True args.extent = True args.ice_volume = True args.snow_volume = True args.speed = True # Build the fieldlist based on which fields are passed fieldlist = [] if args.area: fieldlist.append('total ice area (km^2)') if args.extent: fieldlist.append('total ice extent(km^2)') if args.ice_volume: fieldlist.append('total ice volume (m^3)') if args.snow_volume: fieldlist.append('total snw volume (m^3)') if args.speed: fieldlist.append('rms ice speed (m/s)') # Setup the logger global logger if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Find the test and baseline log files, based on the input directories. if os.path.isdir(args.log_dir): logger.debug('{} is a directory'.format(args.log_dir)) log = find_logfile(args.log_dir) log_dir = args.log_dir else: logger.debug('{} is a file'.format(args.log_dir)) log = args.log_dir log_dir = args.log_dir.rsplit('/',1)[0] logger.info('Log file = {}'.format(log)) if args.base_dir: if os.path.isdir(args.base_dir): base_log = find_logfile(args.base_dir) base_dir = args.base_dir else: base_log = args.base_dir base_dir = args.base_dir.rsplit('/',1)[0] logger.info('Base Log file = {}'.format(base_log)) # Loop through each field and create the plot for field in fieldlist: logger.debug('Current field = {}'.format(field)) # Get the data from the log files dtg, arctic, antarctic, expon = get_data(log, field) if args.base_dir: dtg_base, arctic_base, antarctic_base, expon_base = get_data(base_log,field) # Plot the data if args.base_dir: plot_timeseries(log_dir, field, dtg, arctic, antarctic, expon, dtg_base, \ arctic_base, antarctic_base, base_dir, grid=args.grid) else: plot_timeseries(log_dir, field, dtg, arctic, antarctic, expon, grid=args.grid) if __name__ == "__main__": main()
40.431438
100
0.599636
e4d10e7aea947dc4d3f2ed09e0c9f35cd1df41cf
2,161
go
Go
gobang/game_context.go
holyshared/learn-golang
c522f264812b079c72b1802d1aacafbfbd8bf473
[ "MIT" ]
3
2017-04-22T06:31:21.000Z
2022-03-27T15:00:25.000Z
gobang/game_context.go
holyshared/learn-golang
c522f264812b079c72b1802d1aacafbfbd8bf473
[ "MIT" ]
null
null
null
gobang/game_context.go
holyshared/learn-golang
c522f264812b079c72b1802d1aacafbfbd8bf473
[ "MIT" ]
2
2017-04-26T11:14:15.000Z
2019-04-15T10:05:02.000Z
package gobang import ( "encoding/json" ) func NewGameContext(rule *GameRule, playerStone, npcPlayerStone Stone) *GameContext { board := NewBoard(rule.BoardSize()) player := NewGamePlayer(playerStone, board) ctx := &NpcAIContext{ rule: rule, board: board, playerStone: playerStone, npcPlayerStone: npcPlayerStone, } ai := NewNpcAI(ctx) npcPlayer := NewNpcPlayer(npcPlayerStone, ai) return &GameContext{ GameRule: rule, board: board, currentPlayer: player, player: player, npcPlayer: npcPlayer, } } type GameContext struct { *GameRule board *Board currentPlayer Player player *GamePlayer npcPlayer *NpcPlayer } func (g *GameContext) CurrentBoard() *Board { return g.board } func (g *GameContext) SelectCell(point Point2D) (*Cell, error) { if !g.board.HaveCell(point) { return nil, NewCellNotFoundError(point) } return g.board.SelectCell(point), nil } func (g *GameContext) CurrentPlayer() Player { return g.currentPlayer } func (g *GameContext) GamePlayer() *GamePlayer { return g.player } func (g *GameContext) NpcPlayer() *NpcPlayer { return g.npcPlayer } func (g *GameContext) ChangeToNextPlayer() { var player Player if g.currentPlayer == g.npcPlayer { player = g.player } else { player = g.npcPlayer } g.currentPlayer = player } func (g *GameContext) CheckBoard() PutStoneResult { player := g.CurrentPlayer() matcher := NewCellReachedMatcher(player.Stone(), g.ReachedStoneCount()) result := matcher.Matches(g.board) if result.HasResult() { return Reached } if g.board.IsAllFilled() { return Filled } return Continue } func (g *GameContext) MarshalJSON() ([]byte, error) { jsonObject := struct { Rule *GameRule `json:"rule"` Board *Board `json:"board"` CurrentPlayer Player `json:"currentPlayer"` Player *GamePlayer `json:"player"` NpcPlayer *NpcPlayer `json:"npcPlayer"` }{ Rule: g.GameRule, Board: g.board, CurrentPlayer: g.currentPlayer, Player: g.player, NpcPlayer: g.npcPlayer, } return json.Marshal(jsonObject) }
20.580952
85
0.669597
b9816bd287a93d89d28055fcefc7b60b2ff90d51
393
dart
Dart
lib/src/core/data/models/product.dart
JS4m/navigation_drawer_challenge
8970e6668c25e8bcaba7bdee1893c30992d8af41
[ "MIT" ]
1
2022-01-22T00:55:07.000Z
2022-01-22T00:55:07.000Z
lib/src/core/data/models/product.dart
JS4m/navigation_drawer_challenge
8970e6668c25e8bcaba7bdee1893c30992d8af41
[ "MIT" ]
null
null
null
lib/src/core/data/models/product.dart
JS4m/navigation_drawer_challenge
8970e6668c25e8bcaba7bdee1893c30992d8af41
[ "MIT" ]
null
null
null
import 'product_category_enum.dart'; class Product { final String name; final String subname; // todo: find a better way to animate bottom. final String price; final String image; final ProductCategory productCategory; const Product({ required this.name, required this.subname, required this.price, required this.image, required this.productCategory, }); }
21.833333
69
0.722646
79afef9d0899f22611bbeec2e07429b44ac817da
252
php
PHP
resources/views/account/files/index.blade.php
vntu98/file-market
63e04af5ab6231afceb8a2f70d7d6311ab334c42
[ "MIT" ]
null
null
null
resources/views/account/files/index.blade.php
vntu98/file-market
63e04af5ab6231afceb8a2f70d7d6311ab334c42
[ "MIT" ]
null
null
null
resources/views/account/files/index.blade.php
vntu98/file-market
63e04af5ab6231afceb8a2f70d7d6311ab334c42
[ "MIT" ]
null
null
null
@extends('account.layouts.default') @section('account.content') <h1 class="title">Your files</h1> @if ($files->count()) @each('account.partials._file', $files, 'file') @else <p>You have no files.</p> @endif @endsection
22.909091
55
0.603175
07e190ef0d7c97aade84ae65a8da9f7cf5293f5b
4,153
css
CSS
src/main/webapp/res/css/fore/fore_orderPaySuccess.css
PassionFire/TmallDemo
34a9a6aafedd24bbb7f0fd9c698b369000206af6
[ "Apache-2.0" ]
2
2020-11-13T15:14:02.000Z
2021-06-11T07:01:40.000Z
src/main/webapp/res/css/fore/fore_orderPaySuccess.css
PassionFire/TmallDemo
34a9a6aafedd24bbb7f0fd9c698b369000206af6
[ "Apache-2.0" ]
15
2019-11-01T08:05:01.000Z
2022-03-31T20:29:35.000Z
src/main/webapp/res/css/fore/fore_orderPaySuccess.css
PassionFire/TmallDemo
34a9a6aafedd24bbb7f0fd9c698b369000206af6
[ "Apache-2.0" ]
2
2021-05-07T05:08:08.000Z
2021-05-08T05:57:47.000Z
nav { width: 100%; } .header { width: 1230px; margin: 0 auto; height: 96px; } .header > #mallLogo { float: left; padding-top: 28px; width: 280px; height: 64px; line-height: 64px; position: relative; } #mallLogo > a { position: relative; display: block; width: 190px; height: 30px; overflow: hidden; } #mallLogo img { width: 190px; height: 28px; cursor: pointer; vertical-align: top; } .header > .shopSearchHeader { float: right; overflow: hidden; width: 597px; padding-top: 25px; } .shopSearchHeader > form { border: solid #ff0036; border-width: 3px 0 3px 3px; } .shopSearchHeader > form > .shopSearchInput { font-family: Arial, serif; position: relative; height: 30px; } input::-webkit-input-placeholder { /* WebKit browsers*/ color: #666; font-weight: normal; } input:-moz-placeholder { /* Mozilla Firefox 4 to 18*/ color: #666; font-weight: normal; } input::-moz-placeholder { /* Mozilla Firefox 19+*/ color: #666; font-weight: normal; } input:-ms-input-placeholder { /* Internet Explorer 10+*/ color: #666; font-weight: normal; } .shopSearchInput > .searchInput { font-size: 12px; color: #000; width: 496px; height: 20px; line-height: 20px; padding: 5px 3px 5px 5px; border: none; font-weight: 900; outline: none; float: left; } .shopSearchInput > .searchBtn { width: 90px; height: 30px; font-size: 16px; cursor: pointer; color: #ffffff; background-color: #FF0036; overflow: hidden; border: 0; font-family: "Microsoft YaHei UI", serif; float: left; } .shopSearchHeader > ul { padding-top: 4px; margin-left: -10px; height: 16px; overflow: hidden; line-height: 16px; margin-bottom: 15px; } .shopSearchHeader li + li { border-left: 1px solid #cccccc; } .shopSearchHeader li { float: left; line-height: 1.1; padding: 0 12px; } .shopSearchHeader li > a { color: #999; font-size: 12px; } .content { width: 1230px; margin: 0 auto 100px; } .content > .content_main { border: 1px solid #D4D4D4; margin-top: 20px; padding-bottom: 20px; } .content_main > #J_AmountList > h2 { height: 60px; line-height: 60px; padding: 0 0 0 76px; background: url(../../images/fore/WebsiteImage/TB10aO.KFXXXXcTXpXXXXXXXXXX-31-32.png) 30px 15px no-repeat #ecffdc; font-size: 14px; font-weight: bold; font-family: Arial, serif; } .content_main > #J_AmountList > .summary_pay_done { padding: 0 0 0 76px; margin: 10px 0; color: #333; } .summary_pay_done > ul { padding: 5px 0 0; } .summary_pay_done > ul > li { font-family: Arial, serif; line-height: 28px; list-style: disc; font-size: 12px; } .summary_pay_done em { font-family: Arial, serif; line-height: 28px; font-size: 14px; color: #b10000; font-weight: bolder; font-style: normal; } .content_main > #J_ButtonList { margin: 13px 0 25px 76px; font-family: Arial, serif; font-size: 12px; } .content_main > #J_RemindList { margin: 0 30px; padding: 21px 46px 21px; border-top: 1px dotted #D4D4D4; } #J_RemindList li.alertLi { background: url(../../images/fore/WebsiteImage/TB1LF0CKFXXXXcAXFXXXXXXXXXX-21-20.png) no-repeat; position: relative; left: -28px; padding-left: 28px; line-height: 21px; } #J_RemindList li.alertLi > p { font-family: Arial, serif; font-size: 12px; } #J_RemindList li.alertLi span.warn { color: #c30000; font-weight: bold; } .content_main > #J_Qrcode { margin: 0 30px; border-top: 1px dotted #d4d4d4; padding-top: 21px; } #J_Qrcode > .mui-tm { width: 260px; height: 81px; position: relative; } .mui-tm > a { color: #2d8cba; margin: 0 5px; } .mui-tm > a > img.type2-info { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } .mui-tm > a > img.type2-qrcode { position: absolute; width: 66px; height: 66px; right: 114px; top: 50%; margin-top: -33px; }
17.900862
118
0.614977
835ec9f9acbc4506f802fcfa8876f4216d76a52a
662
ts
TypeScript
src/utils/index.ts
canvascat/todo
da47ffb9df1de94798d28cff186dfced4715d0d0
[ "MIT" ]
null
null
null
src/utils/index.ts
canvascat/todo
da47ffb9df1de94798d28cff186dfced4715d0d0
[ "MIT" ]
null
null
null
src/utils/index.ts
canvascat/todo
da47ffb9df1de94798d28cff186dfced4715d0d0
[ "MIT" ]
null
null
null
export * from './store'; type ClassNameItem = string | Record<string, boolean> | false | undefined | null; export function normalizeClassName(...names: ClassNameItem[]): string { const result: string[] = []; for (let i = 0; i < names.length; i++) { const item = names[i]; if (!item) continue; if (typeof item === 'string') result.push(item); else Object.entries(item).forEach(([k, v]) => v && result.push(k)); } return result.join(' '); // return names.reduce<string[]>((result, item) => (item && (typeof item === 'string' ? result.push(item) : Object.entries(item).forEach(([k, v]) => v && result.push(k))), result), []).join(' ') }
41.375
196
0.608761
1a2f7f4898f84c6a6a06274e0fa55c407c5cce85
14,350
py
Python
scripts/ml_breakdown.py
liudger/ml_tools
ad5cb151fb882046192a37df79572052984b9c5d
[ "CC-BY-4.0" ]
121
2016-08-01T04:13:00.000Z
2022-03-22T02:52:26.000Z
scripts/ml_breakdown.py
liudger/ml_tools
ad5cb151fb882046192a37df79572052984b9c5d
[ "CC-BY-4.0" ]
2
2019-01-25T09:09:12.000Z
2020-04-30T10:00:38.000Z
scripts/ml_breakdown.py
liudger/ml_tools
ad5cb151fb882046192a37df79572052984b9c5d
[ "CC-BY-4.0" ]
53
2016-08-05T12:52:01.000Z
2022-03-14T14:55:57.000Z
# -= ml_breakdown.py =- # __ by Morgan Loomis # ____ ___ / / http://morganloomis.com # / __ `__ \/ / Revision 4 # / / / / / / / 2018-05-13 # /_/ /_/ /_/_/ _________ # /_________/ # # ______________ # - -/__ License __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Copyright 2018 Morgan Loomis # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the # Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # ___________________ # - -/__ Installation __/- - - - - - - - - - - - - - - - - - - - - - - - - - # # Copy this file into your maya scripts directory, for example: # C:/Documents and Settings/user/My Documents/maya/scripts/ml_breakdown.py # # Run the tool in a python shell or shelf button by importing the module, # and then calling the primary function: # # import ml_breakdown # ml_breakdown.ui() # # # __________________ # - -/__ Description __/- - - - - - - - - - - - - - - - - - - - - - - - - - - # # Blend a keyframe or pose with the next or previous keys, essentially creating a # breakdown pose that is weighted one way or the other. # # ____________ # - -/__ Usage __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Press the "Breakdown Dragger" button to enter the dragger, and the cursor will # turn into a hand. Left-click and hold in the viewport, and then drag either left # or right to weight the key to the next or previous key. Press and hold the # middle mouse button to weight the key toward or away from the average of the # surrounding keys. Alternately, set the slider to the desired weight, and press # the Next, Previous or Average buttons to increment the breakdown. Right click # the buttons to assign to hotkeys. If you have no keys selected, the tool will # act only on curves that are visibile in the graph editor. If there are no keys # at the current frame, keys will be set. # # ____________ # - -/__ Video __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # http://www.youtube.com/watch?v=D8yD4zbHTP8 # # _________ # - -/__ Ui __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # [Breakdown Dragger] : Drag in the viewport to weight a breakdown toward the next or previous frame. # [<<] : Weight toward the previous frame. # [Average] : Weight toward the average of the next and previous frame. # [>>] : Weight toward the next frame. # # ___________________ # - -/__ Requirements __/- - - - - - - - - - - - - - - - - - - - - - - - - - # # This script requires the ml_utilities module, which can be downloaded here: # https://raw.githubusercontent.com/morganloomis/ml_tools/master/ml_utilities.py # # __________ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /_ Enjoy! _/- - - __author__ = 'Morgan Loomis' __license__ = 'MIT' __revision__ = 4 __category__ = 'animation' shelfButton = {'annotation': 'Click to weight keys by dragging, double click to open UI.', 'command': 'import ml_breakdown;ml_breakdown.drag()', 'doubleClickCommand': 'import ml_breakdown;ml_breakdown.ui()', 'imageOverlayLabel': 'BD', 'menuItem': [['Breakdown UI', 'import ml_breakdown;ml_breakdown.ui()'], ['<< Previous', 'import ml_breakdown;ml_breakdown.weightPrevious()'], ['>> Next', 'import ml_breakdown;ml_breakdown.weightNext()'], ['Average', 'import ml_breakdown;ml_breakdown.weightAverage()']], 'order': 12} import maya.cmds as mc from maya import OpenMaya from functools import partial try: import ml_utilities as utl utl.upToDateCheck(32) except ImportError: result = mc.confirmDialog( title='Module Not Found', message='This tool requires the ml_utilities module. Once downloaded you will need to restart Maya.', button=['Download Module','Cancel'], defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel' ) if result == 'Download Module': mc.showHelp('http://morganloomis.com/tool/ml_utilities/',absolute=True) def ui(): ''' User interface for breakdown ''' with utl.MlUi('ml_breakdown', 'Breakdown Tools', width=400, height=180, info='''Select objects. Press Breakdown Dragger to create a new key and weight it by dragging in the viewport. Otherwise use the increment buttons to nudge a key's value toward the next or previous key.''') as win: win.buttonWithPopup(label='Breakdown Dragger', command=drag, annotation='Drag in the viewport to weight a breakdown toward the next or previous frame.', shelfLabel='BDD') mc.separator(height=20) mc.floatSliderGrp('ml_breakdown_value_floatSlider', value=0.2, field=True, minValue=0, maxValue=2) mc.paneLayout(configuration='vertical3',separatorThickness=1) win.ButtonWithPopup(label='<<', command=weightPrevious, annotation='Weight toward the previous frame.', shelfLabel='<', shelfIcon='defaultTwoStackedLayout', readUI_toArgs={'weight':'ml_breakdown_value_floatSlider'}) win.ButtonWithPopup(label='Average', command=weightAverage, annotation='Weight toward the average of the next and previous frame.', shelfLabel='><', shelfIcon='defaultTwoStackedLayout', readUI_toArgs={'weight':'ml_breakdown_value_floatSlider'}) win.ButtonWithPopup(label='>>', command=weightNext, annotation='Weight toward the next frame.', shelfLabel='>', shelfIcon='defaultTwoStackedLayout', readUI_toArgs={'weight':'ml_breakdown_value_floatSlider'}) def quickBreakDownUI(): winName = 'ml_quickBreakdownWin' if mc.window(winName, exists=True): mc.deleteUI(winName) mc.window(winName, title='ml :: QBD', iconName='Quick Breakdown', width=100, height=500) mc.columnLayout(adj=True) mc.paneLayout(configuration='vertical2', separatorThickness=1) mc.text('<<') mc.text('>>') mc.setParent('..') for v in (10,20,50,80,90,100,110,120,150): mc.paneLayout(configuration='vertical2',separatorThickness=1) mc.button(label=str(v)+' %', command=partial(weightPrevious,v/100.0)) mc.button(label=str(v)+' %', command=partial(weightNext,v/100.0)) mc.setParent('..') mc.showWindow(winName) mc.window(winName, edit=True, width=100, height=250) def drag(*args): '''The primary command to run the tool''' BreakdownDragger() def weightPrevious(weight=0.2, *args): weightBreakdownStep(direction='previous', weight=weight) def weightAverage(weight=0.2, *args): weightBreakdownStep(direction='average', weight=weight) def weightNext(weight=0.2, *args): weightBreakdownStep(direction='next', weight=weight) def weightBreakdownStep(direction='next', weight=0.2): keySel = utl.KeySelection() if keySel.selectedKeys(): pass elif keySel.visibleInGraphEditor(): keySel.setKeyframe() elif keySel.keyedChannels(): keySel.setKeyframe() if not keySel.curves: return times = list() values = list() data = list() for curve in keySel.curves: if keySel.selected: times = mc.keyframe(curve, query=True, timeChange=True, sl=True) values = mc.keyframe(curve, query=True, valueChange=True, sl=True) else: times = [keySel.time] values = mc.keyframe(curve, time=keySel.time, query=True, valueChange=True) for i,v in zip(times,values): nextTime = mc.findKeyframe(curve, time=(i,), which='next') n = mc.keyframe(curve, time=(nextTime,), query=True, valueChange=True)[0] prevTime = mc.findKeyframe(curve, time=(i,), which='previous') p = mc.keyframe(curve, time=(prevTime,), query=True, valueChange=True)[0] data.append([curve,i,v,n,p]) for d in data: value = None if direction == 'next': value = d[2]+((d[3]-d[2])*weight) elif direction == 'previous': value = d[2]+((d[4]-d[2])*weight) elif direction == 'average': value = d[2]+(((d[3]+d[4])/2-d[2])*weight) else: break mc.keyframe(d[0], time=(d[1],), valueChange=value) class BreakdownDragger(utl.Dragger): '''Creates the tool and manages the data''' def __init__(self, name='mlBreakdownDraggerContext', minValue=None, maxValue=None, defaultValue=0, title = 'Breakdown'): self.keySel = utl.KeySelection() if self.keySel.selectedKeys(): pass elif self.keySel.visibleInGraphEditor(): self.keySel.setKeyframe() elif self.keySel.keyedChannels(): self.keySel.setKeyframe() if not self.keySel.curves: return utl.Dragger.__init__(self, defaultValue=defaultValue, minValue=minValue, maxValue=maxValue, name=name, title=title) #setup tangent type itt,ott = utl.getHoldTangentType() self.time = dict() self.value = dict() self.next = dict() self.prev = dict() self.average = dict() for curve in self.keySel.curves: if self.keySel.selected: self.time[curve] = mc.keyframe(curve, query=True, timeChange=True, sl=True) self.value[curve] = mc.keyframe(curve, query=True, valueChange=True, sl=True) else: self.time[curve] = self.keySel.time self.value[curve] = mc.keyframe(curve, time=self.keySel.time, query=True, valueChange=True) self.next[curve] = list() self.prev[curve] = list() self.average[curve] = list() for i in self.time[curve]: next = mc.findKeyframe(curve, time=(i,), which='next') prev = mc.findKeyframe(curve, time=(i,), which='previous') n = mc.keyframe(curve, time=(next,), query=True, valueChange=True)[0] p = mc.keyframe(curve, time=(prev,), query=True, valueChange=True)[0] self.next[curve].append(n) self.prev[curve].append(p) self.average[curve].append((n+p)/2) #set the tangents on this key, and the next and previous, so they flatten properly mc.keyTangent(curve, time=(i,), itt=itt, ott=ott) mc.keyTangent(curve, time=(next,), itt=itt) mc.keyTangent(curve, time=(prev,), ott=ott) self.setTool() self.drawString('Left: Weight Prev/Next, Middle: Weight Average') OpenMaya.MGlobal.displayWarning('Left: Weight Prev/Next, Middle: Weight Average') def dragLeft(self): '''This is activated by the left mouse button, and weights to the next or previous keys.''' #clamp it if self.x < -1: self.x = -1 if self.x > 1: self.x = 1 if self.x > 0: self.drawString('>> '+str(int(self.x*100))+' %') for curve in self.keySel.curves: for i,v,n in zip(self.time[curve],self.value[curve],self.next[curve]): mc.keyframe(curve, time=(i,), valueChange=v+((n-v)*self.x)) elif self.x <0: self.drawString('<< '+str(int(self.x*-100))+' %') for curve in self.keySel.curves: for i,v,p in zip(self.time[curve],self.value[curve],self.prev[curve]): mc.keyframe(curve, time=(i,), valueChange=v+((p-v)*(-1*self.x))) def dragMiddle(self): '''This is activated by the middle mouse button, and weights to the average of the surrounding keys.''' #clamp it if self.x < -1: self.x = -1 if self.x > 1: self.x = 1 self.drawString('Average '+str(int(self.x*100))+' %') for curve in self.keySel.curves: for i,v,n in zip(self.time[curve],self.value[curve],self.average[curve]): mc.keyframe(curve, time=(i,), valueChange=v+((n-v)*self.x)) def dragShiftLeft(self): '''This is activated by Shift and the left mouse button, and weights to the next or previous keys, without clamping.''' if self.x > 0: self.drawString('>> '+str(int(self.x*100))+' %') for curve in self.keySel.curves: for i,v,n in zip(self.time[curve],self.value[curve],self.next[curve]): mc.keyframe(curve, time=(i,), valueChange=v+((n-v)*self.x)) elif self.x <0: self.drawString('<< '+str(int(self.x*-100))+' %') for curve in self.keySel.curves: for i,v,p in zip(self.time[curve],self.value[curve],self.prev[curve]): mc.keyframe(curve, time=(i,), valueChange=v+((p-v)*(-1*self.x))) if __name__ == '__main__': quickBreakDownUI() # ______________________ # - -/__ Revision History __/- - - - - - - - - - - - - - - - - - - - - - - - # # Revision 1: 2015-05-13 : First publish. # # Revision 2: 2015-05-13 : Documentation updates. # # Revision 3: 2018-02-17 : Updating license to MIT. # # Revision 4: 2018-05-13 : shelf support
40.196078
193
0.604111
a4aa4fba3eab6ec515ba6f964cc35ae790dcf7bd
864
php
PHP
resources/views/murid/viewNonaktif.blade.php
AdamSukma/Excellent
dfc983dbd88bca377dd871d3e6627020d5fe0fb6
[ "MIT" ]
null
null
null
resources/views/murid/viewNonaktif.blade.php
AdamSukma/Excellent
dfc983dbd88bca377dd871d3e6627020d5fe0fb6
[ "MIT" ]
null
null
null
resources/views/murid/viewNonaktif.blade.php
AdamSukma/Excellent
dfc983dbd88bca377dd871d3e6627020d5fe0fb6
[ "MIT" ]
1
2021-01-08T00:41:29.000Z
2021-01-08T00:41:29.000Z
<form id="logout-form" action="{{ route('murid.logout') }}" method="POST" style="display: none;"> @csrf </form> <div class="wrapper wrapper-full-page "> <div class="full-page register-page section-image" > <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"></div> <div class="card-body"> <h1 class="text-center">Status Siswa Non Aktif</h1> <div class="text-center"> <a class="btn btn-danger" href="{{ route('murid.logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout</a></div> </div> </div> </div> </div> </div> </div> </div>
36
113
0.511574
5fd7b02e25dd617c5493b97658a56995060ac474
4,653
dart
Dart
StudyWatch_SDK_healthwearableApp/Source/lib/user_interface/views/theme/app_theme.dart
analogdevicesinc/ApplicationsWaveTool
0c1f236dd0745caa3187841ee1a882f209ac3ebe
[ "Apache-2.0" ]
2
2019-03-11T15:24:51.000Z
2022-03-07T09:42:05.000Z
StudyWatch_SDK_healthwearableApp/Source/lib/user_interface/views/theme/app_theme.dart
analogdevicesinc/ApplicationsWaveTool
0c1f236dd0745caa3187841ee1a882f209ac3ebe
[ "Apache-2.0" ]
null
null
null
StudyWatch_SDK_healthwearableApp/Source/lib/user_interface/views/theme/app_theme.dart
analogdevicesinc/ApplicationsWaveTool
0c1f236dd0745caa3187841ee1a882f209ac3ebe
[ "Apache-2.0" ]
1
2021-03-16T08:26:05.000Z
2021-03-16T08:26:05.000Z
import 'package:flutter/material.dart'; class AppTheme { AppTheme._(); static Color _iconColor = Colors.blueAccent.shade200; static const Color _lightBGColor = Color(0XE1F2F2f7); static const Color _lightSurfaceColor = Colors.white; static const Color _lightPrimaryColor = Color(0xFF165A9E); static const Color _lightPrimaryVariantColor = Color(0xFF07385e); static const Color _lightSecondaryColor = Color(0xFF03C6FB); static const Color _lightOnPrimaryColor = Colors.black; static const Color _darkBGColor = Color(0xFF1D3046); static const Color _darkSurfaceColor = Color(0xFF0A1521); static const Color _darkPrimaryColor = Color(0xFF07385e); //static const Color _darkPrimaryVariantColor = Colors.black; static const Color _darkSecondaryColor = Color(0xFF03C6FB); static const Color _darkOnPrimaryColor = Colors.white; static const Color cardColor = Colors.white; static final ThemeData lightTheme = ThemeData( scaffoldBackgroundColor: _lightSurfaceColor, appBarTheme: AppBarTheme( color: _lightPrimaryColor, iconTheme: IconThemeData(color: _lightOnPrimaryColor), ), secondaryHeaderColor: Colors.lightBlue[900], cardColor: _lightBGColor, colorScheme: ColorScheme.light( background: _lightBGColor, surface: _lightSurfaceColor, primary: _lightPrimaryColor, primaryVariant: _lightPrimaryVariantColor, secondary: _lightSecondaryColor, onPrimary: _lightOnPrimaryColor, ), iconTheme: IconThemeData( color: _iconColor, ), inputDecorationTheme: InputDecorationTheme( labelStyle: TextStyle(color: _lightPrimaryColor), // style for labels ), textTheme: _lightTextTheme, ); static final ThemeData darkTheme = ThemeData( scaffoldBackgroundColor: _darkSurfaceColor, appBarTheme: AppBarTheme( color: _darkPrimaryColor, iconTheme: IconThemeData(color: _darkOnPrimaryColor), ), secondaryHeaderColor: Color(0xFF056DAC), cardColor: _darkBGColor, colorScheme: ColorScheme.dark( background: _darkBGColor, surface: _darkSurfaceColor, primary: _darkPrimaryColor, //primaryVariant: _darkPrimaryVariantColor, secondary: _darkSecondaryColor, onPrimary: _darkOnPrimaryColor, ), iconTheme: IconThemeData( color: _iconColor, ), inputDecorationTheme: InputDecorationTheme( labelStyle: TextStyle(color: _darkSecondaryColor), // style for labels ), textTheme: _darkTextTheme, ); static final TextTheme _lightTextTheme = TextTheme( headline1: _lightScreenHeadingTextStyle, headline2: _lightNumberTextStyle, headline3: _lightUnitTextStyle, headline4: _lightScreenLoadConfigTextStyle, headline6: TextStyle(color: Colors.white), bodyText1: _lightScreenTaskNameTextStyle, bodyText2: _lightScreenTaskDurationTextStyle, ); static final TextTheme _darkTextTheme = TextTheme( headline1: _darkScreenHeadingTextStyle, headline2: _darkNumberTextStyle, headline3: _darkUnitTextStyle, headline4: _darkScreenLoadConfigTextStyle, bodyText1: _darkScreenTaskNameTextStyle, bodyText2: _darkScreenTaskDurationTextStyle, ); static final TextStyle _lightScreenHeadingTextStyle = TextStyle(fontSize: 48.0, color: _lightOnPrimaryColor); static final TextStyle _lightScreenTaskNameTextStyle = TextStyle(fontSize: 26.0, color: _lightOnPrimaryColor); static final TextStyle _lightScreenLoadConfigTextStyle = TextStyle(fontSize: 16.0, color: _lightOnPrimaryColor); static final TextStyle _lightScreenTaskDurationTextStyle = TextStyle(fontSize: 16.0, color: Colors.grey); static final TextStyle _lightNumberTextStyle = TextStyle( fontSize: 36.0, fontWeight: FontWeight.w900, color: Color(0xFF085692), ); static final TextStyle _darkNumberTextStyle = _lightNumberTextStyle.copyWith(color: _darkSecondaryColor); static final TextStyle _lightUnitTextStyle = TextStyle( fontSize: 26.0, color: Color(0xE1085692), ); static final TextStyle _darkUnitTextStyle = _lightUnitTextStyle.copyWith(color: Color(0xAF03C6FB)); static final TextStyle _darkScreenHeadingTextStyle = _lightScreenHeadingTextStyle.copyWith(color: _darkOnPrimaryColor); static final TextStyle _darkScreenTaskNameTextStyle = _lightScreenTaskNameTextStyle.copyWith(color: _darkOnPrimaryColor); static final TextStyle _darkScreenLoadConfigTextStyle = _lightScreenLoadConfigTextStyle.copyWith(color: _darkOnPrimaryColor); static final TextStyle _darkScreenTaskDurationTextStyle = _lightScreenTaskDurationTextStyle; }
36.351563
76
0.765528
ae7ead957a4f1ce14fabd0c7652ab2bd342cd97c
761
cs
C#
World/TimedObjectSwap.cs
Wolfos/Adventure-RPG
c9fc3008b9217c879e655df073245146ac593703
[ "Apache-2.0" ]
2
2021-04-30T16:54:01.000Z
2021-09-05T13:47:42.000Z
World/TimedObjectSwap.cs
Wolfos/Adventure-RPG
c9fc3008b9217c879e655df073245146ac593703
[ "Apache-2.0" ]
null
null
null
World/TimedObjectSwap.cs
Wolfos/Adventure-RPG
c9fc3008b9217c879e655df073245146ac593703
[ "Apache-2.0" ]
null
null
null
using System.Collections; using Models; using UnityEngine; public class TimedObjectSwap : MonoBehaviour { [SerializeField] private TimeStamp onTime = new TimeStamp(20,0); [SerializeField] private TimeStamp offTime = new TimeStamp(7,0); [SerializeField] private GameObject onObject; [SerializeField] private GameObject offObject; private bool on; private void Start() { on = onObject.activeSelf; } private void TurnOn() { on = true; onObject.SetActive(true); offObject.SetActive(false); } private void TurnOff() { on = false; onObject.SetActive(false); offObject.SetActive(true); } private void Update() { if (TimeManager.IsBetween(onTime, offTime)) { if (!on) TurnOn(); } else { if (on) TurnOff(); } } }
16.543478
65
0.697766
6b7d715c6c833a098b2f31669a8567315c3a1bfa
3,668
swift
Swift
src/xcode/ENA/ENA/Source/Services/Exposure Submission/ExposureSubmissionError.swift
krichly/cwa-app-ios
59fd37d39ddd2b7123c3c5aa5d42339055fbebc6
[ "Apache-2.0" ]
null
null
null
src/xcode/ENA/ENA/Source/Services/Exposure Submission/ExposureSubmissionError.swift
krichly/cwa-app-ios
59fd37d39ddd2b7123c3c5aa5d42339055fbebc6
[ "Apache-2.0" ]
8
2021-07-22T21:59:55.000Z
2022-02-27T10:30:41.000Z
src/xcode/ENA/ENA/Source/Services/Exposure Submission/ExposureSubmissionError.swift
krichly/cwa-app-ios
59fd37d39ddd2b7123c3c5aa5d42339055fbebc6
[ "Apache-2.0" ]
null
null
null
// // 🦠 Corona-Warn-App // import Foundation enum ExposureSubmissionError: Error, Equatable { case other(String) case noRegistrationToken case enNotEnabled case notAuthorized case coronaTestServiceError(CoronaTestServiceError) /// User has not granted access to their keys case keysNotShared /// Access to keys was granted but no keys were collected by the exposure notification framework case noKeysCollected case noSubmissionConsent case noCoronaTestTypeGiven case noCoronaTestOfGivenType case noDevicePairingConsent case noAppConfiguration case invalidTan case invalidResponse case noNetworkConnection case teleTanAlreadyUsed case qrAlreadyUsed case regTokenNotExist case qrDoesNotExist case serverError(Int) case unknown case httpError(String) case `internal` case unsupported case rateLimited case fakeResponse case invalidPayloadOrHeaders case requestCouldNotBeBuilt case qrExpired case positiveTestResultNotShown // User has never seen his positive TestResult case malformedDateOfBirthKey case invalidRequest /// **[Deprecated]** Legacy state to indicate no (meaningful) response was given. /// /// This had multiple reasons (offline, invalid payload, etc.) and was ambiguous. Please consider another state (e.g. `invalidResponse` or `noNetworkConnection`) and refactor existing solutions! case noResponse } extension ExposureSubmissionError: LocalizedError { var errorDescription: String? { switch self { case let .serverError(code): return "\(AppStrings.ExposureSubmissionError.other)\(code)\(AppStrings.ExposureSubmissionError.otherend)" case let .httpError(desc): return "\(AppStrings.ExposureSubmissionError.httpError)\n\(desc)" case .invalidTan: return AppStrings.ExposureSubmissionError.invalidTan case .enNotEnabled: return AppStrings.ExposureSubmissionError.enNotEnabled case .notAuthorized: return AppStrings.ExposureSubmissionError.notAuthorized case .noRegistrationToken: return AppStrings.ExposureSubmissionError.noRegistrationToken case .invalidResponse: return AppStrings.ExposureSubmissionError.invalidResponse case .noResponse: return AppStrings.ExposureSubmissionError.noResponse case .noNetworkConnection: return AppStrings.ExposureSubmissionError.noNetworkConnection case .noAppConfiguration: return AppStrings.ExposureSubmissionError.noAppConfiguration case .qrAlreadyUsed: return AppStrings.ExposureSubmissionError.qrAlreadyUsed case .qrDoesNotExist: return AppStrings.ExposureSubmissionError.qrNotExist case .teleTanAlreadyUsed: return AppStrings.ExposureSubmissionError.teleTanAlreadyUsed case .noKeysCollected: return AppStrings.ExposureSubmissionError.noKeysCollected case .internal: return AppStrings.Common.enError11Description case .unsupported: return AppStrings.Common.enError5Description case .rateLimited: return AppStrings.Common.enError13Description case let .other(desc): return "\(AppStrings.ExposureSubmissionError.other)\(desc)\(AppStrings.ExposureSubmissionError.otherend)" case .unknown: return AppStrings.ExposureSubmissionError.unknown case .fakeResponse: return "Fake request received." case .invalidPayloadOrHeaders: return "\(AppStrings.ExposureSubmissionError.errorPrefix) - Received an invalid payload or headers." case .requestCouldNotBeBuilt: return "\(AppStrings.ExposureSubmissionError.errorPrefix) - The submission request could not be built correctly." case .qrExpired: return AppStrings.ExposureSubmission.qrCodeExpiredAlertText default: Log.error("\(self)", log: .api) return AppStrings.ExposureSubmissionError.defaultError } } }
34.280374
195
0.811614
455daa08d49aad80d104a4e2e1ae20034489d089
1,323
dart
Dart
lib/model/dependency_data.dart
sowderca/azure_devops_sdk
1ef1b3b5f72dca3d5075d211f97196caa99494ad
[ "MIT" ]
2
2019-10-07T12:30:29.000Z
2021-03-19T11:49:53.000Z
lib/model/dependency_data.dart
sowderca/azure_devops_sdk
1ef1b3b5f72dca3d5075d211f97196caa99494ad
[ "MIT" ]
null
null
null
lib/model/dependency_data.dart
sowderca/azure_devops_sdk
1ef1b3b5f72dca3d5075d211f97196caa99494ad
[ "MIT" ]
null
null
null
part of azure_devops_sdk.api; class DependencyData { /* Gets or sets the category of dependency data. */ String input = null; /* Gets or sets the key-value pair to specify properties and their values. */ List<Object> map = []; DependencyData(); @override String toString() { return 'DependencyData[input=$input, map=$map, ]'; } DependencyData.fromJson(Map<String, dynamic> json) { if (json == null) return; if (json['input'] == null) { input = null; } else { input = json['input']; } if (json['map'] == null) { map = null; } else { map = Object.listFromJson(json['map']); } } Map<String, dynamic> toJson() { Map <String, dynamic> json = {}; if (input != null) json['input'] = input; if (map != null) json['map'] = map; return json; } static List<DependencyData> listFromJson(List<dynamic> json) { return json == null ? List<DependencyData>() : json.map((value) => DependencyData.fromJson(value)).toList(); } static Map<String, DependencyData> mapFromJson(Map<String, dynamic> json) { var map = Map<String, DependencyData>(); if (json != null && json.isNotEmpty) { json.forEach((String key, dynamic value) => map[key] = DependencyData.fromJson(value)); } return map; } }
25.941176
112
0.606198
b0e4b665dd58b3e8b801aedc19174727230ae45e
4,215
py
Python
instacopy/apps/accounts/models.py
romannovikov/instacopy-petproject
92ffec02b860c77377182cd1fc58043be195e06e
[ "MIT" ]
null
null
null
instacopy/apps/accounts/models.py
romannovikov/instacopy-petproject
92ffec02b860c77377182cd1fc58043be195e06e
[ "MIT" ]
null
null
null
instacopy/apps/accounts/models.py
romannovikov/instacopy-petproject
92ffec02b860c77377182cd1fc58043be195e06e
[ "MIT" ]
null
null
null
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.validators import UnicodeUsernameValidator from django.core.mail import send_mail from django.db import models from django.urls import reverse from phonenumber_field.modelfields import PhoneNumberField from unixtimestampfield import UnixTimeStampField def profile_photo_directory(instance, filename): return f'users/{instance.user}/profile/{filename}' class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, username, full_name, password, **extra_fields): """ Create and save a user with the given username, email, full_name, and password. """ if not email: raise ValueError('The given email must be set') if not username: raise ValueError('The given username must be set') if not full_name: raise ValueError('The given full name must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model( email=email, username=username, full_name=full_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, full_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user( email, username, full_name, password, **extra_fields ) def create_superuser(self, email, username, full_name, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user( email, username, full_name, password, **extra_fields ) class User(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() email = models.EmailField(unique=True) username = models.CharField( max_length=150, unique=True, validators=[username_validator] ) full_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'full_name'] objects = UserManager() def __str__(self): return self.username def get_short_name(self): return self.username def get_full_name(self): return self.full_name def get_blog_page_url(self): return reverse('blog_page', args=[self.username]) def get_follow_url(self): return reverse('follow_toggle', args=[self.username]) def email_user(self, subject, message, from_email=None, **kwargs): send_mail( subject, message, from_email, [self.email], **kwargs ) class Profile(models.Model): MALE = 'M' FEMALE = 'F' CUSTOM = 'C' PREFER_NOT_TO_SAY = 'P' GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (CUSTOM, 'Custom'), (PREFER_NOT_TO_SAY, 'Prefer Not To Say'), ] user = models.OneToOneField( User, on_delete=models.CASCADE ) photo = models.ImageField(upload_to=profile_photo_directory, verbose_name='Profile photo', blank=True) bio = models.CharField( max_length=160, default='', blank=True ) website = models.URLField(default='', blank=True) phone_number = PhoneNumberField(default='', blank=True) gender = models.CharField( max_length=2, choices=GENDER_CHOICES, default=CUSTOM, ) def __str__(self): return self.user.username def get_absolute_url(self): return reverse('blog_page', kwargs={'username': self.user.username})
32.175573
106
0.676394
0dbcfdfd003e73288657b05d3b281563b980728b
232
cs
C#
C# OOP 2019/01. WorkingWithAbstraction/P03_JediGalaxy/Program.cs
bodyquest/SoftwareUniversity-Bulgaria
a402d8671e3b66e69b216ed126d00747690607dc
[ "MIT" ]
2
2021-11-21T17:50:05.000Z
2022-02-11T23:23:47.000Z
C# OOP 2019/01. WorkingWithAbstraction/P03_JediGalaxy/Program.cs
bodyquest/SoftwareUniversity-Bulgaria
a402d8671e3b66e69b216ed126d00747690607dc
[ "MIT" ]
5
2020-08-09T12:46:12.000Z
2022-03-29T07:14:53.000Z
C# OOP 2019/01. WorkingWithAbstraction/P03_JediGalaxy/Program.cs
bodyquest/SoftwareUniversity-Bulgaria
a402d8671e3b66e69b216ed126d00747690607dc
[ "MIT" ]
2
2020-08-01T16:33:17.000Z
2021-11-21T17:50:06.000Z
 namespace P03_JediGalaxy { using System; using System.Linq; public class Program { public static void Main() { Engine engine = new Engine(); engine.Run(); } } }
14.5
41
0.50431
61847e15cb51e5b900d9a02f50c4ca52dafd2bf6
476
swift
Swift
Snapify/Core/UserInterface/IUserInterfaceLayer.swift
kammodze/Snapify
0405ec3ef0a19d9f1b861784c28d3894ccb88c8b
[ "MIT" ]
5
2018-01-20T22:30:18.000Z
2020-04-02T15:26:01.000Z
Snapify/Core/UserInterface/IUserInterfaceLayer.swift
kammodze/Snapify
0405ec3ef0a19d9f1b861784c28d3894ccb88c8b
[ "MIT" ]
1
2018-01-30T01:39:04.000Z
2018-01-30T01:42:52.000Z
Snapify/Core/UserInterface/IUserInterfaceLayer.swift
kammodze/Snapify
0405ec3ef0a19d9f1b861784c28d3894ccb88c8b
[ "MIT" ]
3
2018-01-30T01:25:32.000Z
2021-05-06T22:29:44.000Z
// // IUserInterfaceLayer.swift // Snapify // // Created by Grzegorz Sagadyn on 03.01.2018. // Copyright © 2018 Grzegorz Sagadyn. All rights reserved. // import UIKit /// Represents abstarct layer of a Snapify architecture /// that adds basic functionality to a View. public protocol IUserInterfaceLayer: SnapifyLayer { associatedtype PresenterLayerType: IPresenterLayer /// The Presenter instance. var presenter: PresenterLayerType? { get set } }
23.8
59
0.728992
391e3bff91e66d6bb12b64b0f11c8c8d82404fbc
3,157
py
Python
requestOxfordDict.py
albert-jin/EventCausalityIdentification
badacecfe3e16d613cd59300d6afd857b6c3fe2a
[ "Apache-2.0" ]
1
2022-01-12T06:29:59.000Z
2022-01-12T06:29:59.000Z
requestOxfordDict.py
albert-jin/EventCausalityIdentification
badacecfe3e16d613cd59300d6afd857b6c3fe2a
[ "Apache-2.0" ]
1
2022-02-20T02:14:48.000Z
2022-02-20T02:59:36.000Z
requestOxfordDict.py
albert-jin/EventCausalityIdentification
badacecfe3e16d613cd59300d6afd857b6c3fe2a
[ "Apache-2.0" ]
null
null
null
""" 用于请求牛津字典的事件描述信息 """ import requests app_id = 'c2e7b1fe' app_key = 'b41be5b3b08f91ebe3d849570f15c52a' path = '/api/v2/search/en-gb' entry_path = '/api/v2/entries/en-gb/' language_type = 'en-gb' urlOxfordApiProxy = 'https://od-api.oxforddictionaries.com' urlProxy = "https://developer.oxforddictionaries.com/api_docs/proxy" methodRequestGet = 'GET' def request_word_explanation(query_word): ''' 查询牛津字典对于词汇的解释 :param query_word: 查询单词 :return: 返回描述文本 {'status': False} or {'status': True, 'result': final_dict_knowledge} ''' target_headers = {'X-Apidocs-Url': urlOxfordApiProxy, 'X-Apidocs-Method': methodRequestGet, 'X-Apidocs-Query': 'q=' + query_word, 'X-Apidocs-Path': path, 'app_id': app_id, 'app_key': app_key} r = requests.get(urlProxy, headers=target_headers) ''' r.text.results[0] 一览 { "id": "pigs_in_clover", "label": "pigs in clover", "matchString": "sbpigs", "matchType": "fuzzy", "score": 22.254377, "word": "pigs in clover" } ''' # matchString 与原查询词汇的区别是:大小写统一 if r.status_code != 200: return {'status': False} res = eval(r.text) # matchString = 原词汇, id,word,label =fuzzy 匹配的词汇 , 优先使用word if 'results' not in res or len(res['results']) == 0: return {'status': False} infos = res['results'][0] keyRetry = infos['word'] or infos['id'] or infos['label'] # 用于查牛津词典的名词解释的中间单词 target_entry_headers = {'X-Apidocs-Url': urlOxfordApiProxy, 'X-Apidocs-Method': methodRequestGet, 'X-Apidocs-Query': '', 'X-Apidocs-Path': entry_path + keyRetry, 'app_id': app_id, 'app_key': app_key} r = requests.get(urlProxy, headers=target_entry_headers) if r.status_code != 200: return {'status': False} res = eval(r.text) try: descriptions = [] entries = res['results'][0]['lexicalEntries'][0]['entries'] for entry in entries: # 一个entry下所有解释 description = ' [SEP] '.join(['.'.join(describe['definitions']) for describe in entry['senses']]) # 一个senses下所有解释 descriptions.append(description) except KeyError: return {'status': False} final_dict_knowledge = ' [SEP] '.join(descriptions) if final_dict_knowledge: return {'status': True, 'result': final_dict_knowledge} else: return {'status': False} if __name__ == '__main__': word = 'SBpigs' request_word_explanation(word) # 牛津官网示例,稍作修改 ''' import json app_id = 'c2e7b1fe' app_key = 'b41be5b3b08f91ebe3d849570f15c52a' language = 'en-gb' url = 'https://od-api.oxforddictionaries.com/api/v2/entries/' + language + '/' + word.lower() r = requests.get(url, headers={'app_id': app_id, 'app_key': app_key}) print("code {}\n".format(r.status_code)) print("text \n" + r.text) print("json \n" + json.dumps(r.json())) '''
35.875
126
0.57808
c6bfeeaaeaffda21139f38b772260eb4292dface
2,538
css
CSS
WebRoot/res/mycss/user.css
zhcppy/BookStore
ad3ccc56698292fb4c9c56d757847f3b7294356f
[ "MIT" ]
6
2018-06-21T11:58:14.000Z
2021-05-18T14:42:22.000Z
WebRoot/res/mycss/user.css
zhcppy/BookStore
ad3ccc56698292fb4c9c56d757847f3b7294356f
[ "MIT" ]
null
null
null
WebRoot/res/mycss/user.css
zhcppy/BookStore
ad3ccc56698292fb4c9c56d757847f3b7294356f
[ "MIT" ]
null
null
null
.row{ margin:0px; } .myspan{ margin-top:130px; width:1200px; min-height:0px; float:none; margin-left:auto; margin-right:auto; min-height:400px; } .mynavigation-left{ width:210px; float:left; } .my-left-nav{ padding:0; margin-top:20px; } .my-left-nav dd{ padding: 15px 0 15px 0px; margin:0px; } .my-left-nav dd a{ padding: 15px 90px 15px 20px; text-decoration: none; color: #999; } .my-left-nav dd a:hover{ color: #000; } .active{ color: #000!important; } .my-left-nav dd i{ float:right; } .myuser-right{ width:920px; float:right; margin-top:10px } .mynavbar{ background: #fafafc; line-height: 38px; border: 1px solid #f3f3f3; } .mynavbar a{ text-decoration: none; color: #515151; } .mynavbar .del:hover{ color: #F73131; } .mynavbar a:hover{ color: #7BBC52; } .right-ci{ width:220px; } .table{ margin-bottom:0; } .table th, .table td{ text-align:center; } .fav img{ padding:20px 600px 20px 200px; } .fav h4{ position: absolute; margin:-70px 0 0 320px; color:#70BFEA; } .adel{ position: absolute; margin-left:780px; border:0px; } .mytr{ position: absolute; padding:0px 10px; width:900px; } .pay:hover{ } /* 验证 */ input.error:focus{ transition:border linear 0.2s,box-shadow linear .2s; outline:none; border-color:red; box-shadow:0 0 8px red; } #username-error,#email-error,#qq-error, #tel-error { width: auto; color:red; margin-left:233px; margin-top:-25px; position: absolute; } /* 熊猫走动 */ .walk{ border:0px; height:140px; width:100px; position:absolute; left:0px; bottom:0px; position:fixed; animation-name:myfirst; animation-duration:5s; animation-timing-function:linear; animation-delay:2s; animation-iteration-count:infinite; animation-direction:alternate; animation-play-state:running; /* Safari and Chrome: */ -webkit-animation-name:myfirst; -webkit-animation-duration:5s; -webkit-animation-timing-function:linear; -webkit-animation-delay:2s; -webkit-animation-iteration-count:infinite; -webkit-animation-direction:alternate; -webkit-animation-play-state:running; } @keyframes myfirst { 0% {left:0px; bottom:0px;} 25% {left:0px; bottom:0px;} 50% {left:100px; bottom:100px;} 75% {left:0px; bottom:100px;} 100% {left:0px; bottom:0px;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { 0% {left:0px; bottom:0px;} 25% {left:100px; bottom:0px;} 50% {left:100px; bottom:100px;} 75% {left:0px; bottom:100px;} 100% {bleft:0px; bottom:0px;} } .walk:hover{ -webkit-transform: rotate(180deg); transform: rotate(180deg); }
15.763975
53
0.690701
0d3d321baafa1af76ffac63d2d304423ec497f0d
3,516
h
C
src/mplfe/common/include/mplfe_compiler_component.h
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
192
2019-08-31T00:51:41.000Z
2019-09-02T06:27:48.000Z
src/mplfe/common/include/mplfe_compiler_component.h
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
3
2019-08-31T08:44:27.000Z
2019-09-02T06:31:01.000Z
src/mplfe/common/include/mplfe_compiler_component.h
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
90
2019-08-30T17:36:45.000Z
2019-09-02T07:01:10.000Z
/* * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #ifndef MPLFE_INCLUDE_COMMON_MPLFE_COMPILER_COMPONENT_H #define MPLFE_INCLUDE_COMMON_MPLFE_COMPILER_COMPONENT_H #include <list> #include <memory> #include "mir_module.h" #include "mplfe_options.h" #include "fe_function.h" #include "fe_input.h" #include "fe_input_helper.h" #include "mpl_scheduler.h" namespace maple { class FEFunctionProcessTask : public MplTask { public: FEFunctionProcessTask(FEFunction &argFunction); virtual ~FEFunctionProcessTask() = default; protected: int RunImpl(MplTaskParam *param) override; int FinishImpl(MplTaskParam *param) override; private: FEFunction &function; }; class FEFunctionProcessSchedular : public MplScheduler { public: FEFunctionProcessSchedular(const std::string &name) : MplScheduler(name) {} virtual ~FEFunctionProcessSchedular() = default; void AddFunctionProcessTask(const std::unique_ptr<FEFunction> &function); void SetDumpTime(bool arg) { dumpTime = arg; } protected: void CallbackThreadMainStart() override; private: std::list<std::unique_ptr<FEFunctionProcessTask>> tasks; }; class MPLFECompilerComponent { public: MPLFECompilerComponent(MIRModule &argModule, MIRSrcLang argSrcLang); virtual ~MPLFECompilerComponent() = default; bool InitFromOptions() { return InitFromOptionsImpl(); } bool ParseInput() { return ParseInputImpl(); } bool PreProcessDecl() { return PreProcessDeclImpl(); } bool ProcessDecl() { return ProcessDeclImpl(); } bool PreProcessWithoutFunction() { return PreProcessWithoutFunctionImpl(); } bool PreProcessWithFunction() { return PreProcessWithFunctionImpl(); } bool ProcessFunctionSerial() { return ProcessFunctionSerialImpl(); } bool ProcessFunctionParallel(uint32 nthreads) { return ProcessFunctionParallelImpl(nthreads); } std::string GetComponentName() const { return GetComponentNameImpl(); } bool Parallelable() const { return ParallelableImpl(); } void DumpPhaseTimeTotal() const { DumpPhaseTimeTotalImpl(); } protected: virtual bool InitFromOptionsImpl() = 0; virtual bool ParseInputImpl() = 0; virtual bool PreProcessDeclImpl() = 0; virtual bool ProcessDeclImpl() = 0; virtual bool PreProcessWithoutFunctionImpl() = 0; virtual bool PreProcessWithFunctionImpl() = 0; virtual bool ProcessFunctionSerialImpl(); virtual bool ProcessFunctionParallelImpl(uint32 nthreads); virtual std::string GetComponentNameImpl() const; virtual bool ParallelableImpl() const; virtual void DumpPhaseTimeTotalImpl() const; MIRModule &module; MIRSrcLang srcLang; std::list<std::unique_ptr<FEInputFieldHelper>> fieldHelpers; std::list<std::unique_ptr<FEInputMethodHelper>> methodHelpers; std::list<std::unique_ptr<FEInputStructHelper>> structHelpers; std::list<std::unique_ptr<FEFunction>> functions; std::unique_ptr<FEFunctionPhaseResult> phaseResultTotal; }; } // namespace maple #endif
27.685039
88
0.751991
c6856a6489a13c8ea13b41ffbc79af66263fae2c
1,762
py
Python
python/wtte/plots/misc.py
sandeepnair2812/Weibull-Time-To-Event-Recurrent-Neural-Network
162f5c17f21db79a316d563b60835d178142fd69
[ "MIT" ]
727
2017-01-29T16:47:38.000Z
2022-03-31T23:21:45.000Z
python/wtte/plots/misc.py
kgulpinar/wtte-rnn
162f5c17f21db79a316d563b60835d178142fd69
[ "MIT" ]
68
2017-02-01T16:32:23.000Z
2022-01-24T11:24:36.000Z
python/wtte/plots/misc.py
kgulpinar/wtte-rnn
162f5c17f21db79a316d563b60835d178142fd69
[ "MIT" ]
199
2017-01-30T10:25:04.000Z
2022-03-30T09:41:59.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from six.moves import xrange from wtte import transforms as tr def timeline_plot(padded, title='', cmap="jet", plot=True, fig=None, ax=None): if fig is None or ax is None: fig, ax = plt.subplots(ncols=2, sharey=True, figsize=(12, 4)) ax[0].imshow(padded, interpolation='none', aspect='auto', cmap=cmap, origin='lower') ax[0].set_ylabel('sequence') ax[0].set_xlabel('sequence time') ax[1].imshow(tr.right_pad_to_left_pad(padded), interpolation='none', aspect='auto', cmap=cmap, origin='lower') ax[1].set_ylabel('sequence') ax[1].set_xlabel('absolute time') # (Assuming sequences end today) fig.suptitle(title, fontsize=14) if plot: fig.show() return None, None else: return fig, ax def timeline_aggregate_plot(padded, title='', cmap="jet", plot=True): fig, ax = plt.subplots(ncols=2, nrows=2, sharex=True, sharey=False, figsize=(12, 8)) fig, ax[0] = timeline_plot( padded, title, cmap=cmap, plot=False, fig=fig, ax=ax[0]) ax[1, 0].plot(np.nanmean(padded, axis=0), lw=0.5, c='black', drawstyle='steps-post') ax[1, 0].set_title('mean/timestep') padded = tr.right_pad_to_left_pad(padded) ax[1, 1].plot(np.nanmean(padded, axis=0), lw=0.5, c='black', drawstyle='steps-post') ax[1, 1].set_title('mean/timestep') fig.suptitle(title, fontsize=14) if plot: fig.show() return None, None else: return fig, ax
30.37931
78
0.608967
8ea14688d92c41a6b7cb64c1e37fab4dc8820dea
2,594
js
JavaScript
Estado_E_Comportamento_Objetos/estadoComport.js
Ruan-codeVi/FundamentosPackres
85c4b65513685e0f6b5e405ed15bcb0d14ac684a
[ "MIT" ]
null
null
null
Estado_E_Comportamento_Objetos/estadoComport.js
Ruan-codeVi/FundamentosPackres
85c4b65513685e0f6b5e405ed15bcb0d14ac684a
[ "MIT" ]
null
null
null
Estado_E_Comportamento_Objetos/estadoComport.js
Ruan-codeVi/FundamentosPackres
85c4b65513685e0f6b5e405ed15bcb0d14ac684a
[ "MIT" ]
null
null
null
/* Objetos contém ESTADO e COMPORTAMENTO. As proprieadades de um objeto nos permite manter um estado sobre o objeto - como exemplo nivel de combustivel, sua tempertura atual etc. Os métodos de um objeto nos permitemter comportamento - como ligar um carro, ligar ar condicionado, ligar radio etc. */ // Exemplo let fiat = { montadora: 'Fiat', modelo: '500', cor: 'preto', ocupantes: 2, kilometragem: '0km', ligado: false, nivelCombustivel: 0, // sensorCintoSeg: false, //métodos - são funções dentro de objetos ligarMotor: function(){ this.ligado = true; if(this.nivelCombustivel == 0){ console.log(`O tanque do ${this.montadora} ${this.modelo} está vazio, abasteça antes para dar a partida!`) } else{ this.ligado = true; console.log('Motor Ligado!'); } }, desligarMotor: function(){ this.ligado = false; }, // colocarCinto: function(){ // this.sensorCintoSeg = true; // if(this.sensorCintoSeg == 'sim'){ // console.log('Cinto ok,') // }else{ // console.log(`Esta sem cinto! O motor do ${this.montadora} ${this.modelo} foi desligado! e não dá partida sem que o motorista estaja usando cinto de segurança`) // this.ligado = false; // } // }, dirigir: function(){ if(this.ligado){ if(this.nivelCombustivel > 0){ console.log(`${this.montadora} ${this.modelo} Vrum Vrum!`); this.nivelCombustivel = this.nivelCombustivel - 1; }else{ console.log(`O tanque do ${this.montadora} ${this.modelo} está vazio. Abasteça por favor!`); this.desligarMotor(); } }else{ console.log('Ligue o motor primeiro') } }, addCombustivel:function(abastecer){ this.nivelCombustivel = this.nivelCombustivel + abastecer; } } /* this é usado para acessar propriedades e métodos de um objeto. Exemplo para utilizar propriedade de objeto, dentro de um método precisa-se usar o this na frente, ponto o nome da propriedade. this.nomePriedade Para utilizar um método de objeto, dentro de outro método precisa-se usar o this na frente, ponto nome do método this.desligarMotor(); */ //Chamando os metodos do objeto, nome_Objeto.método() fiat.ligarMotor(); //armgumento fiat.addCombustivel(2); fiat.ligarMotor(); // fiat.colocarCinto('sim'); fiat.dirigir(); // fiat.colocarCinto('sim'); fiat.dirigir(); fiat.dirigir(); //
31.634146
174
0.616037
a332c1bd39df19a41482cadd47a7eaa92aee1bd3
84
java
Java
Core/src/main/java/parseTree/NotSolidityContractException.java
SeUniVr/EtherSolve
0840e9d572b3e46a6393b60f19cff0d1d9480c4b
[ "MIT" ]
22
2021-03-23T11:25:38.000Z
2022-02-23T02:33:19.000Z
Core/src/main/java/parseTree/NotSolidityContractException.java
SeUniVr/EtherSolve
0840e9d572b3e46a6393b60f19cff0d1d9480c4b
[ "MIT" ]
4
2021-03-31T13:14:25.000Z
2021-11-02T23:12:50.000Z
Core/src/main/java/parseTree/NotSolidityContractException.java
SeUniVr/EtherSolve
0840e9d572b3e46a6393b60f19cff0d1d9480c4b
[ "MIT" ]
5
2021-07-16T10:47:26.000Z
2022-03-07T08:11:43.000Z
package parseTree; public class NotSolidityContractException extends Exception { }
16.8
61
0.845238
694f6faa3b78e5242e5997a21815798d39b071b0
445
sh
Shell
packages/less/build.sh
Biangkerok32/termux-packages
286b2474fd527cbcea70d697dfbc6b5bd640f98f
[ "Apache-2.0" ]
4
2020-09-08T17:44:45.000Z
2021-07-06T11:45:44.000Z
packages/less/build.sh
Biangkerok32/termux-packages
286b2474fd527cbcea70d697dfbc6b5bd640f98f
[ "Apache-2.0" ]
1
2019-03-06T08:14:47.000Z
2019-03-06T08:14:47.000Z
packages/less/build.sh
Quasic/termux-packages
ba4b328e494b7823dbea7acc906bee134b85b442
[ "Apache-2.0" ]
3
2021-04-02T16:30:33.000Z
2022-01-14T06:13:08.000Z
TERMUX_PKG_HOMEPAGE=http://www.greenwoodsoftware.com/less/ TERMUX_PKG_DESCRIPTION="Terminal pager program used to view the contents of a text file one screen at a time" TERMUX_PKG_LICENSE="GPL-3.0" TERMUX_PKG_VERSION=530 TERMUX_PKG_REVISION=2 TERMUX_PKG_SHA256=503f91ab0af4846f34f0444ab71c4b286123f0044a4964f1ae781486c617f2e2 TERMUX_PKG_SRCURL=http://www.greenwoodsoftware.com/less/less-${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_DEPENDS="ncurses"
49.444444
109
0.865169
d10eac17120b48866a4e4c959ebc1a99c9f69502
3,184
dart
Dart
lib/widgets/migrate_legacy_tokens_dialog.dart
bliksemlabs/pi-authenticator
263a90b462cf52afee95c72175ba4151b2a38c5e
[ "MIT" ]
null
null
null
lib/widgets/migrate_legacy_tokens_dialog.dart
bliksemlabs/pi-authenticator
263a90b462cf52afee95c72175ba4151b2a38c5e
[ "MIT" ]
null
null
null
lib/widgets/migrate_legacy_tokens_dialog.dart
bliksemlabs/pi-authenticator
263a90b462cf52afee95c72175ba4151b2a38c5e
[ "MIT" ]
null
null
null
/* privacyIDEA Authenticator Authors: Timo Sturm <[email protected]> Copyright (c) 2017-2021 NetKnights GmbH Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import 'dart:developer'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:privacyidea_authenticator/model/tokens.dart'; import 'package:privacyidea_authenticator/utils/storage_utils.dart'; class MigrateLegacyTokensDialog extends StatefulWidget { @override State<StatefulWidget> createState() => _MigrateLegacyTokensDialogState(); } class _MigrateLegacyTokensDialogState extends State<MigrateLegacyTokensDialog> { Widget _content = Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[CircularProgressIndicator()], ); @override void initState() { super.initState(); _migrateTokens(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return BackdropFilter( filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: AlertDialog( title: Text(AppLocalizations.of(context)!.migratingToken), content: _content, actions: <Widget>[ TextButton( child: Text(AppLocalizations.of(context)!.dismiss), onPressed: () => Navigator.pop(context), ), ], ), ); } void _migrateTokens() async { // Load legacy tokens and add them to the storage. log('Attempt to load legacy tokens.', name: 'migrate_legacy_tokens_dialog.dart#_migrateTokens'); List<Token> legacyTokens = await StorageUtil.loadAllTokensLegacy(); List<PushToken> currentPushToken = (await StorageUtil.loadAllTokens()).whereType<PushToken>().toList(); for (Token old in legacyTokens) { // Skip push token which already exist (by serial) if (old is PushToken) { if (currentPushToken.any((e) => old.serial == e.serial)) { continue; } } await StorageUtil.saveOrReplaceToken(old); } String text; if (legacyTokens.isEmpty) { text = AppLocalizations.of(context)!.noTokensForMigration; } else { text = AppLocalizations.of(context)!.migrationSuccess; } final ScrollController controller = ScrollController(); setState(() { _content = Scrollbar( isAlwaysShown: true, controller: controller, child: SingleChildScrollView( controller: controller, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [Text(text)], ), ), ); }); } }
28.428571
80
0.67902
e24abc00b667147de394edda261bc1e91e4fdd82
20,594
js
JavaScript
public/backend/js/main.js
lanceWan/IBackend
78a2f557576ffea98d4d674f6ef8536da9bedf4a
[ "MIT" ]
null
null
null
public/backend/js/main.js
lanceWan/IBackend
78a2f557576ffea98d4d674f6ef8536da9bedf4a
[ "MIT" ]
null
null
null
public/backend/js/main.js
lanceWan/IBackend
78a2f557576ffea98d4d674f6ef8536da9bedf4a
[ "MIT" ]
null
null
null
/*** Metronic AngularJS App Main Script ***/ /* Metronic App */ var MetronicApp = angular.module("MetronicApp", [ "ngAnimate", "ui.router", "ui.bootstrap", "oc.lazyLoad", "ngSanitize", ]); /* Configure ocLazyLoader(refer: https://github.com/ocombe/ocLazyLoad) */ MetronicApp.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) { $ocLazyLoadProvider.config({ // global configs go here }); }]); /******************************************** BEGIN: BREAKING CHANGE in AngularJS v1.3.x: *********************************************/ /** `$controller` will no longer look for controllers on `window`. The old behavior of looking on `window` for controllers was originally intended for use in examples, demos, and toy apps. We found that allowing global controller functions encouraged poor practices, so we resolved to disable this behavior by default. To migrate, register your controllers with modules rather than exposing them as globals: Before: ```javascript function MyController() { // ... } ``` After: ```javascript angular.module('myApp', []).controller('MyController', [function() { // ... }]); Although it's not recommended, you can re-enable the old behavior like this: ```javascript angular.module('myModule').config(['$controllerProvider', function($controllerProvider) { // this option might be handy for migrating old apps, but please don't use it // in new ones! $controllerProvider.allowGlobals(); }]); **/ //AngularJS v1.3.x workaround for old style controller declarition in HTML MetronicApp.config(['$controllerProvider', function($controllerProvider) { // this option might be handy for migrating old apps, but please don't use it // in new ones! $controllerProvider.allowGlobals(); }]); /******************************************** END: BREAKING CHANGE in AngularJS v1.3.x: *********************************************/ /* Setup global settings */ MetronicApp.factory('settings', ['$rootScope', function($rootScope) { // supported languages var settings = { layout: { pageSidebarClosed: false, // sidebar menu state pageContentWhite: false, // set page content layout pageBodySolid: false, // solid body color state pageAutoScrollOnLoad: 1000 // auto scroll to top on page load }, assetsPath: '../backend', globalPath: '../backend/', layoutPath: '../backend', }; $rootScope.settings = settings; return settings; }]); /* Setup App Main Controller */ MetronicApp.controller('AppController', ['$scope', '$rootScope', function($scope, $rootScope) { $scope.$on('$viewContentLoaded', function() { App.initComponents(); // init core components // Layout.init(); // Init entire layout(header, footer, sidebar, etc) on page load if the partials included in server side instead of loading with ng-include directive }); }]); /*** Layout Partials. By default the partials are loaded through AngularJS ng-include directive. In case they loaded in server side(e.g: PHP include function) then below partial initialization can be disabled and Layout.init() should be called on page load complete as explained above. ***/ /* Setup Layout Part - Header */ MetronicApp.controller('HeaderController', ['$scope', function($scope) { Layout.initHeader(); // init header }]); /* Setup Layout Part - Sidebar */ MetronicApp.controller('SidebarController', ['$scope', function($scope) { Layout.initSidebar(); // init sidebar }]); /* Setup Layout Part - Theme Panel */ MetronicApp.controller('ThemePanelController', ['$scope', function($scope) { Demo.init(); // init theme panel }]); /* Setup Layout Part - Footer */ MetronicApp.controller('FooterController', ['$scope', function($scope) { Layout.initFooter(); // init footer }]); /* Setup Rounting For All Pages */ MetronicApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) { // Redirect any unmatched url // $urlRouterProvider.otherwise("/admin"); $stateProvider // 后台首页 .state('admin', { url: "/admin", templateUrl: "/admin/ajaxindex", data: {pageTitle: 'Admin Dashboard Template'}, controller: "DashboardController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before a LINK element with this ID. Dynamic CSS files must be loaded between core and theme css files files: [ 'backend/plugins/datatables/datatables.min.css', 'backend/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css', 'backend/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css', 'backend/plugins/bootstrap-select/css/bootstrap-select.min.css', 'backend/plugins/datatables/datatables.all.min.js', 'backend/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js', 'backend/plugins/bootstrap-select/js/bootstrap-select.min.js', 'backend/js/controllers/DashboardController.js', ] }); }] } }) // 用户列表 .state('admin.user', { // abstract: true, url: "/user", templateUrl: "/admin/user/ngindex", data: {pageTitle: '用户列表'}, controller: "UserController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ cache: false, name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before a LINK element with this ID. Dynamic CSS files must be loaded between core and theme css files files: [ 'backend/js/user/datatable-ajax.js', 'backend/plugins/angularjs/plugins/angular-bootstrap-switch.min.js', 'backend/js/controllers/UserController.js', ] }); }] } }) .state('admin.usercreate', { url : "/user/create", templateUrl : "/admin/user/ngcreate", data: {pageTitle: '添加用户'}, controller: "UserCreateController", resolve : { deps : ['$ocLazyLoad', function($ocLazyLoad){ return $ocLazyLoad.load({ cache:false, name : 'MetronicApp', insertBefore : '#ng_load_plugins_before', files : [ 'backend/js/controllers/user/UserCreateController.js', ] }); }] } }) //权限列表 .state('admin.permission', { url: "/permission", templateUrl: "/admin/permission/ngindex", data: {pageTitle: '权限列表'}, controller: "PermissionController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load([{ cache: false, insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' name: 'MetronicApp', files: [ 'backend/js/permission/datatable-ajax.js', 'backend/js/controllers/PermissionController.js', ] }]); }] } }) // 菜单列表 .state('admin.menu', { url: "/menu", templateUrl: "/admin/menu/ngindex", data: {pageTitle: '菜单列表'}, controller: "MenuController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load([{ name: 'MetronicApp', files: [ 'backend/plugins/jquery-nestable/jquery.nestable.css', 'backend/plugins/jquery-nestable/jquery.nestable.js', 'backend/js/script/nestable.js', 'backend/js/controllers/MenuController.js' ] }]); }] } }) // 角色列表 .state('admin.role', { url: "/role", templateUrl: "/admin/role/ngindex", data: {pageTitle: '角色列表 '}, controller: "RoleController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load([{ name: 'MetronicApp', cache: false, insertBefore: '#ng_load_plugins_before', files: [ 'backend/js/role/datatable-ajax.js', 'backend/js/controllers/RoleController.js', ] }]); }] } }) // 创建角色 .state('admin.roleCreate', { url: "/role/create", templateUrl: "/admin/role/create", data: {pageTitle: '添加角色'}, controller: "RoleController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load([{ name: 'MetronicApp', // cache: false, insertBefore: '#ng_load_plugins_before', files: [ 'backend/js/controllers/RoleController.js', ] }]); }] } }) // Date & Time Pickers .state('pickers', { url: "/pickers", templateUrl: "views/pickers.html", data: {pageTitle: 'Date & Time Pickers'}, controller: "GeneralPageController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load([{ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../assets/global/plugins/clockface/css/clockface.css', '../assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css', '../assets/global/plugins/bootstrap-timepicker/css/bootstrap-timepicker.min.css', '../assets/global/plugins/bootstrap-colorpicker/css/colorpicker.css', '../assets/global/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css', '../assets/global/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css', '../assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js', '../assets/global/plugins/bootstrap-timepicker/js/bootstrap-timepicker.min.js', '../assets/global/plugins/clockface/js/clockface.js', '../assets/global/plugins/moment.min.js', '../assets/global/plugins/bootstrap-daterangepicker/daterangepicker.js', '../assets/global/plugins/bootstrap-colorpicker/js/bootstrap-colorpicker.js', '../assets/global/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js', '../assets/pages/scripts/components-date-time-pickers.min.js', 'js/controllers/GeneralPageController.js' ] }]); }] } }) // Custom Dropdowns .state('dropdowns', { url: "/dropdowns", templateUrl: "views/dropdowns.html", data: {pageTitle: 'Custom Dropdowns'}, controller: "GeneralPageController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load([{ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../assets/global/plugins/bootstrap-select/css/bootstrap-select.min.css', '../assets/global/plugins/select2/css/select2.min.css', '../assets/global/plugins/select2/css/select2-bootstrap.min.css', '../assets/global/plugins/bootstrap-select/js/bootstrap-select.min.js', '../assets/global/plugins/select2/js/select2.full.min.js', '../assets/pages/scripts/components-bootstrap-select.min.js', '../assets/pages/scripts/components-select2.min.js', 'js/controllers/GeneralPageController.js' ] }]); }] } }) // Advanced Datatables .state('datatablesAdvanced', { url: "/datatables/managed.html", templateUrl: "views/datatables/managed.html", data: {pageTitle: 'Advanced Datatables'}, controller: "GeneralPageController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../assets/global/plugins/datatables/datatables.min.css', '../assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css', '../assets/global/plugins/datatables/datatables.all.min.js', '../assets/pages/scripts/table-datatables-managed.min.js', 'js/controllers/GeneralPageController.js' ] }); }] } }) // Ajax Datetables .state('datatablesAjax', { url: "/datatables/ajax.html", templateUrl: "views/datatables/ajax.html", data: {pageTitle: 'Ajax Datatables'}, controller: "GeneralPageController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../assets/global/plugins/datatables/datatables.min.css', '../assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css', '../assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css', '../assets/global/plugins/datatables/datatables.all.min.js', '../assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js', '../assets/global/scripts/datatable.js', 'js/scripts/table-ajax.js', 'js/controllers/GeneralPageController.js' ] }); }] } }) // User Profile .state("profile", { url: "/profile", templateUrl: "views/profile/main.html", data: {pageTitle: 'User Profile'}, controller: "UserProfileController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css', '../assets/pages/css/profile.css', '../assets/global/plugins/jquery.sparkline.min.js', '../assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.js', '../assets/pages/scripts/profile.min.js', 'js/controllers/UserProfileController.js' ] }); }] } }) // User Profile Dashboard .state("profile.dashboard", { url: "/dashboard", templateUrl: "views/profile/dashboard.html", data: {pageTitle: 'User Profile'} }) // User Profile Account .state("profile.account", { url: "/account", templateUrl: "views/profile/account.html", data: {pageTitle: 'User Account'} }) // User Profile Help .state("profile.help", { url: "/help", templateUrl: "views/profile/help.html", data: {pageTitle: 'User Help'} }) // Todo .state('todo', { url: "/todo", templateUrl: "views/todo.html", data: {pageTitle: 'Todo'}, controller: "TodoController", resolve: { deps: ['$ocLazyLoad', function($ocLazyLoad) { return $ocLazyLoad.load({ name: 'MetronicApp', insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before' files: [ '../assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css', '../assets/apps/css/todo-2.css', '../assets/global/plugins/select2/css/select2.min.css', '../assets/global/plugins/select2/css/select2-bootstrap.min.css', '../assets/global/plugins/select2/js/select2.full.min.js', '../assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js', '../assets/apps/scripts/todo-2.min.js', 'js/controllers/TodoController.js' ] }); }] } }); // MetronicApp.config(function($provide) { // $provide.decorator('$state', function($delegate) { // var originalTransitionTo = $delegate.transitionTo; // $delegate.transitionTo = function(to, toParams, options) { // return originalTransitionTo(to, toParams, angular.extend({ // reload: true // }, options)); // }; // return $delegate; // } // )}; // enable html5Mode for pushstate ('#'-less URLs) $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); }]); /* Init global settings and run the app */ MetronicApp.run(["$rootScope", "settings", "$state", function($rootScope, settings, $state) { $rootScope.$state = $state; // state to be accessed from view $rootScope.$settings = settings; // state to be accessed from view }]);
40.780198
194
0.505973
41a3f2900022a70945e3dcd85395c84ed2ca9a5e
217
swift
Swift
platzitweets/Commons/Models/Requests/RegisterRequest.swift
omarefg/platzi-tweets
448a6264424b0740160c75c532562cf21fdd4d07
[ "MIT" ]
null
null
null
platzitweets/Commons/Models/Requests/RegisterRequest.swift
omarefg/platzi-tweets
448a6264424b0740160c75c532562cf21fdd4d07
[ "MIT" ]
null
null
null
platzitweets/Commons/Models/Requests/RegisterRequest.swift
omarefg/platzi-tweets
448a6264424b0740160c75c532562cf21fdd4d07
[ "MIT" ]
null
null
null
// // RegisterRequest.swift // platzitweets // // Created by Omar Flores on 10/10/20. // import Foundation struct RegisterRequest: Codable { let email: String let password: String let names: String }
14.466667
39
0.682028
b03b64bcc05fab5fdefca7483f31bbb0137b66e6
1,343
py
Python
python/quiz/main.py
r-angeles/kivy-lab
baf4bf18aff28a1c9cd525c9b8ec949cb08e8356
[ "MIT" ]
2
2021-09-18T20:16:41.000Z
2022-02-13T22:56:27.000Z
python/quiz/main.py
r-angeles/kivy-lab
baf4bf18aff28a1c9cd525c9b8ec949cb08e8356
[ "MIT" ]
null
null
null
python/quiz/main.py
r-angeles/kivy-lab
baf4bf18aff28a1c9cd525c9b8ec949cb08e8356
[ "MIT" ]
null
null
null
import csv class Quiz: all_quizzes = [] def __init__(self, question, choices, answer): self.question = question self.choices = choices self.answer = answer Quiz.all_quizzes.append(self) @classmethod def instantiate_from_csv(cls): with open('practise/python/quiz/questions.csv', 'r') as f: reader = csv.DictReader(f) items = list(reader) for item in items: Quiz( question=item.get('question'), choices=item.get('choices'), answer=int(item.get('answer')), ) def __repr__(self): return f"Item('{self.question}', {self.choices}, {self.answer})" # To do: # Print each instance to the quiz interface # Split choices into list using split method. # Add for loop on QuizInterface class to loop over the list. # Add a row on csv ('result') whether a user has correctly answered a question (default on false) # Add method on interface to take inputs from console # Add method looping through 'result' sum(), checking how many is True/False class QuizInterface: def print_quiz(self, quiz): print('A Quiz!') print('===================') def main(): Quiz.instantiate_from_csv() print(Quiz.all_quizzes) if __name__ == "__main__": main()
27.408163
97
0.613552
bb40f4e68aa7c9ce5fbf7b41f346dba9122c53b2
2,827
cs
C#
CreateAR.Commons.Unity.Async/SynchronizedObject.cs
enklu/commons-unity-async
1f0c528fee29d610741b928710298602c6bc047a
[ "MIT" ]
3
2018-10-01T13:01:23.000Z
2021-05-07T18:40:10.000Z
CreateAR.Commons.Unity.Async/SynchronizedObject.cs
enklu/commons-unity-async
1f0c528fee29d610741b928710298602c6bc047a
[ "MIT" ]
null
null
null
CreateAR.Commons.Unity.Async/SynchronizedObject.cs
enklu/commons-unity-async
1f0c528fee29d610741b928710298602c6bc047a
[ "MIT" ]
1
2018-10-01T13:00:24.000Z
2018-10-01T13:00:24.000Z
using System; using System.Collections.Generic; namespace CreateAR.Commons.Unity.Async { /// <summary> /// Wraps an object and queues asynchronous actions on object. Instead of /// an OnChanged event, the subscriber to changes is also asyncronous. /// </summary> /// <typeparam name="T"></typeparam> public class SynchronizedObject<T> { /// <summary> /// Actions to perform. /// </summary> private readonly Queue<Action<T, Action<T>>> _actions = new Queue<Action<T, Action<T>>>(); /// <summary> /// The subscriber. /// </summary> private readonly Action<T, Action> _subscriber; /// <summary> /// True iff the an action is processing. /// </summary> private bool _isWaitingOnProcessing; /// <summary> /// True iff the subscriber is processing. /// </summary> private bool _isWaitingOnSubscriber; /// <summary> /// The underlying data. /// </summary> public T Data { get; private set; } /// <summary> /// Constructor. /// </summary> /// <param name="data">The initial data.</param> /// <param name="subscriber">The subscriber. Called every time the data is changed.</param> public SynchronizedObject(T data, Action<T, Action> subscriber) { Data = data; _subscriber = subscriber; } /// <summary> /// Queues an asynchronous action on an object. /// </summary> /// <param name="action">The action to take.</param> public bool Queue(Action<T, Action<T>> action) { if (_isWaitingOnSubscriber) { return false; } _actions.Enqueue(action); ProcessQueue(); return true; } /// <summary> /// Processes the next item in the queue. /// </summary> private void ProcessQueue() { if (_isWaitingOnProcessing) { return; } if (_actions.Count == 0) { return; } _isWaitingOnProcessing = true; var action = _actions.Dequeue(); action(Data, OnComplete); } /// <summary> /// Called when the action is complete. /// </summary> /// <param name="val">The new value.</param> private void OnComplete(T val) { Data = val; _isWaitingOnProcessing = false; _isWaitingOnSubscriber = true; _subscriber(Data, () => { _isWaitingOnSubscriber = false; ProcessQueue(); }); } } }
26.420561
99
0.505129
ef85d1451b06102d1904b311d487d2cc984ef8f4
13,571
c
C
NitroPaint/ncgr.c
AdAstra-LD/NitroPaint
bd507aa279cea6a1fe6a96fdaa6c8c4f07efa717
[ "BSD-2-Clause" ]
null
null
null
NitroPaint/ncgr.c
AdAstra-LD/NitroPaint
bd507aa279cea6a1fe6a96fdaa6c8c4f07efa717
[ "BSD-2-Clause" ]
null
null
null
NitroPaint/ncgr.c
AdAstra-LD/NitroPaint
bd507aa279cea6a1fe6a96fdaa6c8c4f07efa717
[ "BSD-2-Clause" ]
null
null
null
#include "ncgr.h" #include "nclr.h" #include "nscr.h" #include "color.h" #include <stdio.h> LPCWSTR characterFormatNames[] = { L"Invalid", L"NCGR", L"Hudson", L"Hudson 2", L"NCBR", L"Binary", NULL }; int calculateWidth(int nTiles) { int width = 1; for (int i = 1; i < nTiles; i++) { if (i * i > nTiles) break; if (nTiles % i == 0) width = i; } int height = nTiles / width; if (width > height) return height; //prioritize wide over tall output return width; } int ncgrIsValidHudson(LPBYTE buffer, int size) { if (size < 8) return 0; if (*buffer == 0x10) return 0; if (((*buffer) & 0xF0) != 0) return 0; int dataLength = *(WORD *) (buffer + 1); if (buffer[3] != 0) return 0; if (dataLength * 32 + 4 == size || dataLength * 64 + 4 == size) { //no second header return NCGR_TYPE_HUDSON2; } if (buffer[4] != 1 && buffer[4] != 0) return 0; dataLength -= 4; if (dataLength + 8 != size) return 0; return NCGR_TYPE_HUDSON; } int ncgrIsValidBin(LPBYTE buffer, int size) { if (size & 0x1F) return 0; return NCGR_TYPE_BIN; } void ncgrFree(OBJECT_HEADER *header) { NCGR *ncgr = (NCGR *) header; if (ncgr->tiles != NULL) { for (int i = 0; i < ncgr->nTiles; i++) { free(ncgr->tiles[i]); } free(ncgr->tiles); } ncgr->tiles = NULL; COMBO2D *combo = ncgr->combo2d; if (ncgr->combo2d != NULL) { ncgr->combo2d->ncgr = NULL; if (combo->nclr == NULL && combo->ncgr == NULL && combo->nscr == NULL) { combo2dFree(combo); free(combo); } } ncgr->combo2d = NULL; } void ncgrInit(NCGR *ncgr, int format) { ncgr->header.size = sizeof(NCGR); fileInitCommon((OBJECT_HEADER *) ncgr, FILE_TYPE_CHARACTER, format); ncgr->header.dispose = ncgrFree; ncgr->combo2d = NULL; } int hudsonReadCharacter(NCGR *ncgr, char *buffer, int size) { if (size < 8) return 1; //file too small if (*buffer == 0x10) return 1; //TODO: LZ77 decompress int type = ncgrIsValidHudson(buffer, size); if (type == NCGR_TYPE_INVALID) return 1; int nCharacters = 0; if (type == NCGR_TYPE_HUDSON) { int dataLength = *(WORD *) (buffer + 1); dataLength -= 4; if (dataLength + 8 > size) return 1; nCharacters = *(WORD *) (buffer + 5); } else if (type == NCGR_TYPE_HUDSON2) { nCharacters = *(WORD *) (buffer + 1); } ncgrInit(ncgr, type); ncgr->nTiles = nCharacters; ncgr->tileWidth = 8; ncgr->mappingMode = GX_OBJVRAMMODE_CHAR_1D_32K; ncgr->nBits = 8; ncgr->tilesX = -1; ncgr->tilesY = -1; if (type == NCGR_TYPE_HUDSON) { if (buffer[4] == 0) { ncgr->nBits = 4; } } else if (type == NCGR_TYPE_HUDSON2) { ncgr->nBits = 4; } int tileCount = nCharacters; int tilesX, tilesY; tilesX = calculateWidth(nCharacters); tilesY = tileCount / tilesX; BYTE ** tiles = (BYTE **) calloc(tileCount, sizeof(BYTE **)); buffer += 0x4; if (type == NCGR_TYPE_HUDSON) buffer += 0x4; for (int i = 0; i < tileCount; i++) { tiles[i] = (BYTE *) calloc(8 * 8, 1); BYTE * tile = tiles[i]; if (ncgr->nBits == 8) { memcpy(tile, buffer, 64); buffer += 64; } else if (ncgr->nBits == 4) { for (int j = 0; j < 32; j++) { BYTE b = *buffer; tile[j * 2] = b & 0xF; tile[j * 2 + 1] = b >> 4; buffer++; } } } ncgr->tilesX = tilesX; ncgr->tilesY = tilesY; ncgr->tiles = tiles; return 0; } int ncgrReadCombo(NCGR *ncgr, char *buffer, int size) { int format = combo2dIsValid(buffer, size); ncgrInit(ncgr, NCGR_TYPE_COMBO); int charOffset = 0; switch (format) { case COMBO2D_TYPE_TIMEACE: { ncgr->nTiles = *(int *) (buffer + 0xA08); ncgr->mappingMode = GX_OBJVRAMMODE_CHAR_2D; ncgr->nBits = *(int *) buffer == 0 ? 4 : 8; ncgr->tilesX = calculateWidth(ncgr->nTiles); ncgr->tilesY = ncgr->nTiles / ncgr->tilesX; charOffset = 0xA0C; break; } case COMBO2D_TYPE_BANNER: { ncgr->nTiles = 16; ncgr->tileWidth = 8; ncgr->tilesX = 4; ncgr->tilesY = 4; ncgr->nBits = 4; ncgr->mappingMode = GX_OBJVRAMMODE_CHAR_1D_32K; charOffset = 0x20; break; } } int nTiles = ncgr->nTiles; BYTE **tiles = (BYTE **) calloc(nTiles, sizeof(BYTE *)); for (int i = 0; i < nTiles; i++) { BYTE *tile = (BYTE *) calloc(64, 1); tiles[i] = tile; if (ncgr->nBits == 8) { memcpy(tile, buffer + charOffset + i * 0x40, 0x40); } else { BYTE *src = buffer + charOffset + i * 0x20; for (int j = 0; j < 32; j++) { BYTE b = src[j]; tile[j * 2] = b & 0xF; tile[j * 2 + 1] = b >> 4; } } } ncgr->tiles = tiles; return 0; } int ncgrReadBin(NCGR *ncgr, char *buffer, int size) { ncgrInit(ncgr, NCGR_TYPE_BIN); ncgr->nTiles = size / 0x20; ncgr->nBits = 4; ncgr->mappingMode = GX_OBJVRAMMODE_CHAR_1D_32K; ncgr->tileWidth = 8; ncgr->tilesX = calculateWidth(ncgr->nTiles); ncgr->tilesY = ncgr->nTiles / ncgr->tilesX; BYTE **tiles = (BYTE **) calloc(ncgr->nTiles, sizeof(BYTE **)); for (int i = 0; i < ncgr->nTiles; i++) { BYTE *tile = (BYTE *) calloc(64, 1); for (int j = 0; j < 32; j++) { BYTE b = *buffer; tile[j * 2] = b & 0xF; tile[j * 2 + 1] = b >> 4; buffer++; } tiles[i] = tile; } ncgr->tiles = tiles; return 0; } int ncgrRead(NCGR *ncgr, char *buffer, int size) { if (*(DWORD *) buffer != 0x4E434752) { if (ncgrIsValidHudson(buffer, size)) return hudsonReadCharacter(ncgr, buffer, size); if (combo2dIsValid(buffer, size)) return ncgrReadCombo(ncgr, buffer, size); if (ncgrIsValidBin(buffer, size)) return ncgrReadBin(ncgr, buffer, size); } if (size < 0x10) return 1; DWORD magic = *(DWORD *) buffer; if (magic != 0x4E434752 && magic != 0x5247434E) return 1; buffer += 0x10; int rahcSize = *(int *) buffer; unsigned short tilesY = *(unsigned short *) (buffer + 0x8); unsigned short tilesX = *(unsigned short *) (buffer + 0xA); int depth = *(int *) (buffer + 0xC); int mapping = *(int *) (buffer + 0x10); depth = 1 << (depth - 1); int tileDataSize = *(int *) (buffer + 0x18); int type = *(int *) (buffer + 0x14); int format = NCGR_TYPE_NCGR; if (type == 1) { format = NCGR_TYPE_NCBR; } int tileCount = tilesX * tilesY; int nPresentTiles = tileDataSize >> 5; if (depth == 8) nPresentTiles >>= 1; if (NCGR_1D(mapping) || tileCount != nPresentTiles) { tileCount = nPresentTiles; tilesX = calculateWidth(tileCount); tilesY = tileCount / tilesX; } BYTE **tiles = (BYTE **) calloc(tileCount, sizeof(BYTE **)); buffer += 0x20; if (format == NCGR_TYPE_NCGR) { for (int i = 0; i < tileCount; i++) { tiles[i] = (BYTE *) calloc(8 * 8, 1); BYTE * tile = tiles[i]; if (depth == 8) { memcpy(tile, buffer, 64); buffer += 64; } else if (depth == 4) { for (int j = 0; j < 32; j++) { BYTE b = *buffer; tile[j * 2] = b & 0xF; tile[j * 2 + 1] = b >> 4; buffer++; } } } } else if (format == NCGR_TYPE_NCBR) { for (int y = 0; y < tilesY; y++) { for (int x = 0; x < tilesX; x++) { int offset = x * 4 + 4 * y * tilesX * 8; BYTE *tile = calloc(64, 1); tiles[x + y * tilesX] = tile; if (depth == 8) { offset *= 2; BYTE *indices = buffer + offset; memcpy(tile, indices, 8); memcpy(tile + 8, indices + 8 * tilesX, 8); memcpy(tile + 16, indices + 16 * tilesX, 8); memcpy(tile + 24, indices + 24 * tilesX, 8); memcpy(tile + 32, indices + 32 * tilesX, 8); memcpy(tile + 40, indices + 40 * tilesX, 8); memcpy(tile + 48, indices + 48 * tilesX, 8); memcpy(tile + 56, indices + 56 * tilesX, 8); } else if (depth == 4) { BYTE *indices = buffer + offset; for (int j = 0; j < 8; j++) { for (int i = 0; i < 4; i++) { tile[i * 2 + j * 8] = indices[i + j * 4 * tilesX] & 0xF; tile[i * 2 + 1 + j * 8] = indices[i + j * 4 * tilesX] >> 4; } } } } } } ncgrInit(ncgr, format); ncgr->nBits = depth; ncgr->nTiles = tileCount; ncgr->tiles = tiles; ncgr->tileWidth = 8; ncgr->tilesX = tilesX; ncgr->tilesY = tilesY; ncgr->mappingMode = mapping; return 0; } int ncgrReadFile(NCGR *ncgr, LPCWSTR path) { return fileRead(path, (OBJECT_HEADER *) ncgr, (OBJECT_READER) ncgrRead); } int ncgrGetTile(NCGR * ncgr, NCLR * nclr, int x, int y, DWORD * out, int previewPalette, BOOL drawChecker, BOOL transparent) { int nIndex = x + y * ncgr->tilesX; BYTE * tile = ncgr->tiles[nIndex]; int nTiles = ncgr->nTiles; if (x + y * ncgr->tilesX < nTiles) { for (int i = 0; i < 64; i++) { int index = tile[i]; if ((index == 0 && drawChecker) && transparent) { int c = ((i & 0x7) ^ (i >> 3)) >> 2; if (c) out[i] = 0xFFFFFFFF; else out[i] = 0xFFC0C0C0; } else if (index || !transparent) { COLOR w = 0; if (nclr && (index + (previewPalette << ncgr->nBits)) < nclr->nColors) w = nclr->colors[index + (previewPalette << ncgr->nBits)]; out[i] = ColorConvertFromDS(CREVERSE(w)) | 0xFF000000; } else out[i] = 0; } } else { if (!drawChecker) { memset(out, 0, 64 * 4); } else { for (int i = 0; i < 64; i++) { int c = ((i & 0x7) ^ (i >> 3)) >> 2; if (c) out[i] = 0xFFFFFFFF; else out[i] = 0xFFC0C0C0; } } return 1; } return 0; } int ncgrWrite(NCGR *ncgr, BSTREAM *stream) { int status = 0; if (ncgr->header.format == NCGR_TYPE_NCGR || ncgr->header.format == NCGR_TYPE_NCBR) { BYTE ncgrHeader[] = { 'R', 'G', 'C', 'N', 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0x10, 0, 0x1, 0 }; BYTE charHeader[] = { 'R', 'A', 'H', 'C', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; if (ncgr->header.format == NCGR_TYPE_NCBR) { charHeader[20] = 1; } int nTiles = ncgr->nTiles; int nBytesPerTile = 64; if (ncgr->nBits == 4) nBytesPerTile >>= 1; int sectionSize = 0x20 + nTiles * nBytesPerTile; int fileSize = 0x10 + sectionSize; if (ncgr->nBits == 8) *(int *) (charHeader + 0xC) = 4; else if (ncgr->nBits == 4) *(int *) (charHeader + 0xC) = 3; *(int *) (charHeader + 0x10) = ncgr->mappingMode; *(int *) (charHeader + 0x4) = sectionSize; if (NCGR_2D(ncgr->mappingMode)) { *(unsigned short *) (charHeader + 0x8) = ncgr->tilesY; *(unsigned short *) (charHeader + 0xA) = ncgr->tilesX; } else { *(int *) (charHeader + 0x8) = 0xFFFFFFFF; } *(int *) (charHeader + 0x1C) = 0x18; *(int *) (charHeader + 0x18) = sectionSize - 0x20; *(int *) (ncgrHeader + 0x8) = fileSize; bstreamWrite(stream, ncgrHeader, sizeof(ncgrHeader)); bstreamWrite(stream, charHeader, sizeof(charHeader)); if (ncgr->header.format == NCGR_TYPE_NCGR) { for (int i = 0; i < ncgr->nTiles; i++) { if (ncgr->nBits == 8) { bstreamWrite(stream, ncgr->tiles[i], 64); } else { BYTE buffer[32]; for (int j = 0; j < 32; j++) { BYTE b = ncgr->tiles[i][(j << 1)] | (ncgr->tiles[i][(j << 1) + 1] << 4); buffer[j] = b; } bstreamWrite(stream, buffer, 32); } } } else if (ncgr->header.format == NCGR_TYPE_NCBR) { BYTE *bmp = (BYTE *) calloc(nTiles, 8 * ncgr->nBits); int nWidth = ncgr->tilesX * 8; for (int y = 0; y < ncgr->tilesY; y++) { for (int x = 0; x < ncgr->tilesX; x++) { BYTE *tile = ncgr->tiles[x + y * ncgr->tilesX]; if (ncgr->nBits == 8) { for (int i = 0; i < 64; i++) { int tX = x * 8 + (i % 8); int tY = y * 8 + (i / 8); bmp[tX + tY * nWidth] = tile[i]; } } else { for (int i = 0; i < 32; i++) { int tX = x * 8 + ((i * 2) % 8); int tY = y * 8 + (i / 4); bmp[(tX + tY * nWidth) / 2] = tile[i * 2] | (tile[i * 2 + 1] << 4); } } } } bstreamWrite(stream, bmp, nTiles * 8 * ncgr->nBits); free(bmp); } } else if(ncgr->header.format == NCGR_TYPE_HUDSON || ncgr->header.format == NCGR_TYPE_HUDSON2) { if (ncgr->header.format == NCGR_TYPE_HUDSON) { BYTE header[] = { 0, 0, 0, 0, 1, 0, 0, 0 }; if (ncgr->nBits == 4) header[4] = 0; *(WORD *) (header + 5) = ncgr->nTiles; int nCharacterBytes = 64 * ncgr->nTiles; if (ncgr->nBits == 4) nCharacterBytes >>= 1; *(WORD *) (header + 1) = nCharacterBytes + 4; bstreamWrite(stream, header, sizeof(header)); } else if(ncgr->header.format == NCGR_TYPE_HUDSON2) { BYTE header[] = { 0, 0, 0, 0 }; *(WORD *) (header + 1) = ncgr->nTiles; bstreamWrite(stream, header, sizeof(header)); } for (int i = 0; i < ncgr->nTiles; i++) { if (ncgr->nBits == 8) { bstreamWrite(stream, ncgr->tiles[i], 64); } else { BYTE buffer[32]; for (int j = 0; j < 32; j++) { BYTE b = ncgr->tiles[i][(j << 1)] | (ncgr->tiles[i][(j << 1) + 1] << 4); buffer[j] = b; } bstreamWrite(stream, buffer, 32); } } } else if (ncgr->header.format == NCGR_TYPE_BIN) { for (int i = 0; i < ncgr->nTiles; i++) { if (ncgr->nBits == 8) { bstreamWrite(stream, ncgr->tiles[i], 64); } else { BYTE t[32]; for (int j = 0; j < 32; j++) { t[j] = ncgr->tiles[i][j * 2] | (ncgr->tiles[i][j * 2 + 1] << 4); } bstreamWrite(stream, t, 32); } } } else if (ncgr->header.format == NCGR_TYPE_COMBO) { status = combo2dWrite(ncgr->combo2d, stream); } return status; } int ncgrWriteFile(NCGR *ncgr, LPWSTR name) { return fileWrite(name, (OBJECT_HEADER *) ncgr, (OBJECT_WRITER) ncgrWrite); }
28.874468
130
0.552207
4bf680edd2f559112bd73d8d6a67f3cfb95ef1bd
601
h
C
mqtt.h
pdgendt/shairport-sync
dc07d7fc04b4bd8eb9d3c37f2dad4fc99c3f291d
[ "MIT" ]
5,625
2015-01-02T09:21:40.000Z
2022-03-31T23:38:11.000Z
mqtt.h
boardwalk/shairport-sync
c2bb4cddf06005e7d42548202adb34374d3a88bc
[ "MIT" ]
1,310
2015-01-01T10:30:27.000Z
2022-03-31T15:06:19.000Z
mqtt.h
boardwalk/shairport-sync
c2bb4cddf06005e7d42548202adb34374d3a88bc
[ "MIT" ]
609
2015-01-01T20:34:19.000Z
2022-03-31T07:49:35.000Z
#ifndef MQTT_H #define MQTT_H #include <mosquitto.h> #include <stdint.h> int initialise_mqtt(); void mqtt_process_metadata(uint32_t type, uint32_t code, char *data, uint32_t length); void mqtt_publish(char *topic, char *data, uint32_t length); void mqtt_setup(); void on_connect(struct mosquitto *mosq, void *userdata, int rc); void on_disconnect(struct mosquitto *mosq, void *userdata, int rc); void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg); void _cb_log(struct mosquitto *mosq, void *userdata, int level, const char *str); #endif /* #ifndef MQTT_H */
40.066667
93
0.770383
741362541916f5bfc4d0af7fc1092d9264016df0
2,669
css
CSS
css/theme.css
raingart/Nova-YouTube-extension
c1f3759c05231fabf6a9a43cda167c481391608d
[ "Apache-2.0" ]
33
2021-04-28T08:33:34.000Z
2022-03-08T14:03:25.000Z
css/theme.css
raingart/New-Horizons-for-YouTube-extension
68938187a3da904ac70eb5bbb2d748c7c0491201
[ "Apache-2.0" ]
5
2020-01-02T21:22:17.000Z
2021-03-10T04:23:59.000Z
css/theme.css
raingart/New-Horizons-for-YouTube-extension
68938187a3da904ac70eb5bbb2d748c7c0491201
[ "Apache-2.0" ]
2
2021-06-08T04:19:08.000Z
2022-01-03T17:03:50.000Z
:root { /* --bg: #1c1c1c; --bg: oldlace; --fg: slategrey; */ --input-bg: #fff; --input-border: #cccccc; --btn-bg: silver; --btn-fg: #fff; --li-item: #e0e0e0; --hr: #B7B7B7; --href: #00b7fc; --plugins-before: slategrey; --plugins-section-hover: silver; --label1: initial; --label1: #343a45; } /* turn on dark mode by default */ /* @media (prefers-color-scheme:dark) { */ :root { --bg: #1c1c1c; --fg: slategrey; --input-bg: #171717; --input-border: #2d2d2d; --li-item: #353535; --hr: #3d3d3d; --btn-bg: #3e3e3e; --plugins-before: #D5DDE5; --plugins-section-hover: #303030; --label1: initial; --label2: #8c8b8b; } /* } */ body { background: var(--bg); color: var(--fg); /* -webkit-filter: invert(100%); */ } /* gray background */ body:after { bottom: 0; box-shadow: inset 0 0 378px 119px rgba(0, 0, 0, .10); content: ' '; display: block; left: 0; pointer-events: none; position: fixed; right: 0; top: 0; z-index: 1000; } a { /* color: #3d3d3d; */ color: var(--href); } hr { border-width: 0; border-top: 1px solid var(--hr); } button, input, select, textarea { background-color: var(--input-bg); border: 1px solid var(--input-border); } /* button, [type=submit], [type=reset], [type=button] { background-color: var(--btn-bg); color: var(--btn-fg); } */ button:hover, [type=submit]:hover, [type=reset]:hover, [type=button]:hover { background-color: var(--href); color: var(--btn-fg); } /* scrollbar */ ::-webkit-scrollbar { width: 10px; height: 8px; } ::-webkit-scrollbar-button { width: 0; height: 0; } ::-webkit-scrollbar-thumb { border: 0; /* border-radius: 3px; */ background: #888; } ::-webkit-scrollbar-thumb:hover { background: #666; } ::-webkit-scrollbar-thumb:active { background: #444; } ::-webkit-scrollbar-track { border: 0; border-radius: 0; background: #e1e1e1; } /* ::-webkit-scrollbar-track:hover { background: #666; } */ /*::-webkit-scrollbar-track:active { background: #333; }*/ ::-webkit-scrollbar-corner { background: transparent; } @media (prefers-color-scheme:dark) { body:after { display: none; } ::-webkit-scrollbar-thumb { background: #333; } ::-webkit-scrollbar-thumb:hover { background: #666; } ::-webkit-scrollbar-thumb:active { background: #888; } ::-webkit-scrollbar-track { background: #222; } /* ::-webkit-scrollbar-track:hover { background: #666; } */ /* ::-webkit-scrollbar-track:active { background: #333; } */ }
18.795775
76
0.569876
6891da4a19b630e1f50bfbdbbebf7db848ed601f
6,381
lua
Lua
KkthnxUI/Config/Settings.lua
mrrosh/KkthnxUI_WotLK
59d36f99bebce53b90fbfd3806911b7a61133dab
[ "MIT" ]
null
null
null
KkthnxUI/Config/Settings.lua
mrrosh/KkthnxUI_WotLK
59d36f99bebce53b90fbfd3806911b7a61133dab
[ "MIT" ]
null
null
null
KkthnxUI/Config/Settings.lua
mrrosh/KkthnxUI_WotLK
59d36f99bebce53b90fbfd3806911b7a61133dab
[ "MIT" ]
1
2021-12-07T14:15:51.000Z
2021-12-07T14:15:51.000Z
local K, C, L, _ = select(2, ...):unpack() -- Media Options C["Media"] = { ["Backdrop_Color"] = {5/255, 5/255, 5/255, 0.8}, ["Blank"] = [[Interface\AddOns\KkthnxUI\Media\Textures\Blank]], ["Blank_Font"] = [[Interface\AddOns\KkthnxUI\Media\Fonts\Invisible.ttf]], ["Blizz"] = [[Interface\AddOns\KkthnxUI\Media\Border\Border_Default.tga]], ["Border_Color"] = {255/255, 255/255, 255/255, 1}, ["Border_Glow"] = [[Interface\AddOns\KkthnxUI\Media\Border\Border_Glow.tga]], ["Combat_Font"] = [[Interface\AddOns\KkthnxUI\Media\Fonts\Damage.ttf]], ["Combat_Font_Size"] = 16, ["Combat_Font_Size_Style"] = "OUTLINE" or "THINOUTLINE", ["Font"] = [[Interface\AddOns\KkthnxUI\Media\Fonts\Normal.ttf]], ["Font_Size"] = 12, ["Font_Style"] = "OUTLINE" or "THINOUTLINE", ["Glow"] = [[Interface\AddOns\KkthnxUI\Media\Textures\GlowTex.tga]], ["Overlay_Color"] = {0/255, 0/255, 0/255, 0.8}, ["Proc_Sound"] = [[Interface\AddOns\KkthnxUI\Media\Sounds\Proc.ogg]], ["Texture"] = [[Interface\TargetingFrame\UI-StatusBar]], ["Warning_Sound"] = [[Interface\AddOns\KkthnxUI\Media\Sounds\Warning.ogg]], ["Whisp_Sound"] = [[Interface\AddOns\KkthnxUI\Media\Sounds\Whisper.ogg]], } -- ActionBar Options C["ActionBar"] = { ["BottomBars"] = 3, ["ButtonSize"] = 36, ["ButtonSpace"] = 3, ["Enable"] = true, ["EquipBorder"] = false, ["Hotkey"] = true, ["Macro"] = true, ["OutOfMana"] = {128/255, 128/255, 255/255}, ["OutOfRange"] = {204/255, 26/255, 26/255}, ["PetBarHide"] = false, ["PetBarHorizontal"] = false, ["RightBars"] = 2, ["Selfcast"] = false, ["ShowGrid"] = true, ["SplitBars"] = false, ["StanceBarHide"] = false, ["StanceBarHorizontal"] = true, ["ToggleMode"] = true, } -- Announcements Options C["Announcements"] = { ["Bad_Gear"] = false, ["Feasts"] = false, ["Interrupt"] = false, ["Portals"] = false, ["PullCountdown"] = true, ["SaySapped"] = false, ["Spells"] = false, ["SpellsFromAll"] = false, ["Toys"] = false, } -- Automation Options C["Automation"] = { ["AutoCollapse"] = true, ["AutoInvite"] = false, ["DeclineDuel"] = false, ["LoggingCombat"] = false, ["Resurrection"] = false, ["ScreenShot"] = false, ["SellGreyRepair"] = false, ["TabBinder"] = false, } -- Bag Options C["Bag"] = { ["BagColumns"] = 10, ["BankColumns"] = 17, ["ButtonSize"] = 34, ["ButtonSpace"] = 4, ["Enable"] = true, ["HideSoulBag"] = false, } -- Blizzard Options C["Blizzard"] = { ["Capturebar"] = true, ["ClassColor"] = true, ["DarkTextures"] = false, ["DarkTexturesColor"] = {77/255, 77/255, 77/255}, ["Durability"] = true, ["MoveAchievements"] = true, ["Reputations"] = true, } -- Buffs & Debuffs Options C["Aura"] = { ["Enable"] = true, ["BuffSize"] = 32, ["CastBy"] = false, ["ClassColorBorder"] = false, } -- Chat Options C["Chat"] = { ["CombatLog"] = true, ["DamageMeterSpam"] = false, ["Enable"] = true, ["Filter"] = true, ["Height"] = 150, ["Outline"] = false, ["Spam"] = false, ["FadeTime"] = 20, ["Sticky"] = true, ["TabsMouseover"] = true, ["TabsOutline"] = false, ["WhispSound"] = true, ["Width"] = 400, } -- Cooldown Options C["Cooldown"] = { ["Enable"] = true, ["FontSize"] = 20, ["Threshold"] = 3, } -- Error Options C["Error"] = { ["Black"] = true, ["White"] = false, ["Combat"] = false, } -- Filger Options C["Filger"] = { ["BuffsSize"] = 37, ["CooldownSize"] = 30, ["Enable"] = true, ["MaxTestIcon"] = 5, ["PvPSize"] = 60, ["ShowTooltip"] = false, ["TestMode"] = false, } -- General Options C["General"] = { ["AutoScale"] = true, ["BubbleFontSize"] = 12, ["BubbleBackdrop"] = false, ["ReplaceBlizzardFonts"] = true, ["TranslateMessage"] = true, ["UIScale"] = 0.71, ["MultisampleCheck"] = false, ["WelcomeMessage"] = true, } -- Loot Options C["Loot"] = { ["ConfirmDisenchant"] = false, ["AutoGreed"] = false, ["LootFilter"] = true, ["IconSize"] = 30, ["Enable"] = true, ["GroupLoot"] = true, ["Width"] = 222, } -- Minimap Options C["Minimap"] = { ["CollectButtons"] = true, ["Enable"] = true, ["Ping"] = true, ["Size"] = 150, } -- Miscellaneous Options C["Misc"] = { ["AFKCamera"] = false, ["AlreadyKnown"] = false, ["Armory"] = false, ["BGSpam"] = false, ["DurabilityWarninig"] = false, ["EnhancedMail"] = true, ["HatTrick"] = true, ["InviteKeyword"] = "inv", ["ItemLevel"] = false, ["SpeedyLoad"] = false, } -- Nameplate Options C["Nameplate"] = { ["AdditionalHeight"] = 0, ["AdditionalWidth"] = 0, ["AuraSize"] = 20, ["BadColor"] = {199/255, 64/255, 64/255}, ["ClassIcons"] = false, ["Combat"] = false, ["Enable"] = true, ["EnhanceThreat"] = false, ["GoodColor"] = {74/255, 173/255, 74/255}, ["HealthValue"] = true, ["Height"] = 9, ["NameAbbreviate"] = true, ["NearColor"] = {217/255, 196/255, 92/255}, ["CastBarName"] = true, ["Auras"] = false, ["Width"] = 120, } -- PowerBar Options C["PowerBar"] = { ["Enable"] = false, ["FontOutline"] = false, ["Height"] = 4, ["DKRuneBar"] = false, ["Combo"] = true, ["Mana"] = true, ["Rage"] = true, ["Rune"] = true, ["RuneCooldown"] = true, ["ValueAbbreviate"] = true, ["Width"] = 200, } -- PulseCD Options C["PulseCD"] = { ["Enable"] = false, ["Size"] = 75, ["Sound"] = false, ["AnimationScale"] = 1.5, ["HoldTime"] = 0, ["Threshold"] = 3, } -- Skins Options C["Skins"] = { ["Spy"] = false, ["ChatBubble"] = true, ["CLCRet"] = false, ["DBM"] = false, ["MinimapButtons"] = true, ["Recount"] = false, ["Skada"] = false, ["WeakAuras"] = false, ["WorldMap"] = false, } -- Tooltip Options C["Tooltip"] = { ["Achievements"] = false, ["ArenaExperience"] = false, ["Cursor"] = false, ["Enable"] = true, ["HealthValue"] = true, ["HideCombat"] = false, ["HideButtons"] = false, ["InstanceLock"] = false, ["ItemCount"] = false, ["ItemIcon"] = false, ["QualityBorder"] = false, ["RaidIcon"] = false, ["Rank"] = false, ["SpellID"] = false, ["Talents"] = false, ["Target"] = true, ["Title"] = true, ["WhoTargetting"] = false, } -- Unitframe Options C["Unitframe"] = { ["ComboFrame"] = false, ["SmoothBars"] = false, ["AuraOffsetY"] = 3, ["BetterPowerColors"] = false, ["CastBarScale"] = 1.2, ["ClassHealth"] = false, ["ClassIcon"] = false, ["CombatFeedback"] = false, ["Enable"] = false, ["EnhancedFrames"] = false, ["GroupNumber"] = false, ["PvPIcon"] = true, ["LargeAuraSize"] = 26, ["Outline"] = false, ["PercentHealth"] = false, ["Scale"] = 1.2, ["SmallAuraSize"] = 22, }
23.898876
78
0.593637
46e58369023202bd01a3e73e67bd5a35f6907105
11,014
py
Python
tests/utils/test_shape_utils.py
897615138/tfsnippet-jill
2fc898a4def866c8d3c685168df1fa22083bb143
[ "MIT" ]
63
2018-06-06T11:56:40.000Z
2022-03-22T08:00:59.000Z
tests/utils/test_shape_utils.py
897615138/tfsnippet-jill
2fc898a4def866c8d3c685168df1fa22083bb143
[ "MIT" ]
39
2018-07-04T12:40:53.000Z
2022-02-09T23:48:44.000Z
tests/utils/test_shape_utils.py
897615138/tfsnippet-jill
2fc898a4def866c8d3c685168df1fa22083bb143
[ "MIT" ]
34
2018-06-25T09:59:22.000Z
2022-02-23T12:46:33.000Z
import pytest import numpy as np import tensorflow as tf from tfsnippet.utils import * class IntShapeTestCase(tf.test.TestCase): def test_int_shape(self): self.assertEqual(get_static_shape(tf.zeros([1, 2, 3])), (1, 2, 3)) self.assertEqual( get_static_shape(tf.placeholder(tf.float32, [None, 2, 3])), (None, 2, 3) ) self.assertIsNone(get_static_shape(tf.placeholder(tf.float32, None))) class ResolveNegativeAxisTestCase(tf.test.TestCase): def test_resolve_negative_axis(self): # good case self.assertEqual(resolve_negative_axis(4, (0, 1, 2)), (0, 1, 2)) self.assertEqual(resolve_negative_axis(4, (0, -1, -2)), (0, 3, 2)) # bad case with pytest.raises(ValueError, match='`axis` out of range: \\(-5,\\) ' 'vs ndims 4.'): _ = resolve_negative_axis(4, (-5,)) with pytest.raises(ValueError, match='`axis` has duplicated elements ' 'after resolving negative axis.'): _ = resolve_negative_axis(4, (0, -4)) class GetBatchSizeTestCase(tf.test.TestCase): def test_get_batch_size(self): def run_check(sess, x, axis, x_in=None, dynamic=True): if x_in is None: x_in = tf.constant(x) dynamic = False batch_size = get_batch_size(x_in, axis) if dynamic: self.assertIsInstance(batch_size, tf.Tensor) self.assertEqual(sess.run(batch_size, feed_dict={x_in: x}), x.shape[axis]) else: self.assertEqual(batch_size, x.shape[axis]) with self.test_session() as sess: x = np.zeros([2, 3, 4], dtype=np.float32) # check when shape is totally static run_check(sess, x, 0) run_check(sess, x, 1) run_check(sess, x, 2) run_check(sess, x, -1) # check when some shape is dynamic, but the batch axis is not run_check(sess, x, 0, tf.placeholder(tf.float32, [2, None, None]), dynamic=False) run_check(sess, x, 1, tf.placeholder(tf.float32, [None, 3, None]), dynamic=False) run_check(sess, x, 2, tf.placeholder(tf.float32, [None, None, 4]), dynamic=False) run_check(sess, x, -1, tf.placeholder(tf.float32, [None, None, 4]), dynamic=False) # check when the batch axis is dynamic run_check(sess, x, 0, tf.placeholder(tf.float32, [None, 3, 4]), dynamic=True) run_check(sess, x, 1, tf.placeholder(tf.float32, [2, None, 4]), dynamic=True) run_check(sess, x, 2, tf.placeholder(tf.float32, [2, 3, None]), dynamic=True) run_check(sess, x, -1, tf.placeholder(tf.float32, [2, 3, None]), dynamic=True) # check when the shape is totally dynamic x_in = tf.placeholder(tf.float32, None) run_check(sess, x, 0, x_in, dynamic=True) run_check(sess, x, 1, x_in, dynamic=True) run_check(sess, x, 2, x_in, dynamic=True) run_check(sess, x, -1, x_in, dynamic=True) class GetRankTestCase(tf.test.TestCase): def test_get_rank(self): with self.test_session() as sess: # test static shape ph = tf.placeholder(tf.float32, (1, 2, 3)) self.assertEqual(get_rank(ph), 3) # test partially dynamic shape ph = tf.placeholder(tf.float32, (1, None, 3)) self.assertEqual(get_rank(ph), 3) # test totally dynamic shape ph = tf.placeholder(tf.float32, None) self.assertEqual( sess.run(get_rank(ph), feed_dict={ ph: np.arange(6, dtype=np.float32).reshape((1, 2, 3)) }), 3 ) class GetDimensionSizeTestCase(tf.test.TestCase): def test_get_dimension_size(self): with self.test_session() as sess: # test static shape ph = tf.placeholder(tf.float32, (1, 2, 3)) self.assertEqual(get_dimension_size(ph, 0), 1) self.assertEqual(get_dimension_size(ph, 1), 2) self.assertEqual(get_dimension_size(ph, 2), 3) self.assertEqual(get_dimension_size(ph, -1), 3) # test dynamic shape, but no dynamic axis is queried ph = tf.placeholder(tf.float32, (1, None, 3)) self.assertEqual(get_dimension_size(ph, 0), 1) self.assertEqual(get_dimension_size(ph, 2), 3) self.assertEqual(get_dimension_size(ph, -1), 3) # test dynamic shape def _assert_equal(a, b): self.assertIsInstance(a, tf.Tensor) self.assertEqual(sess.run(a, feed_dict={ph: ph_in}), b) ph = tf.placeholder(tf.float32, (1, None, 3)) ph_in = np.arange(6, dtype=np.float32).reshape((1, 2, 3)) _assert_equal(get_dimension_size(ph, 1), 2) _assert_equal(get_dimension_size(ph, -2), 2) axis_ph = tf.placeholder(tf.int32, None) self.assertEqual( sess.run(get_dimension_size(ph, axis_ph), feed_dict={ph: ph_in, axis_ph: 1}), 2 ) # test fully dynamic shape ph = tf.placeholder(tf.float32, None) _assert_equal(get_dimension_size(ph, 0), 1) _assert_equal(get_dimension_size(ph, 1), 2) _assert_equal(get_dimension_size(ph, 2), 3) _assert_equal(get_dimension_size(ph, -2), 2) def test_get_dimensions_size(self): with self.test_session() as sess: # test empty query ph = tf.placeholder(tf.float32, None) self.assertTupleEqual(get_dimensions_size(ph, ()), ()) # test static shape ph = tf.placeholder(tf.float32, (1, 2, 3)) self.assertTupleEqual(get_dimensions_size(ph), (1, 2, 3)) self.assertTupleEqual(get_dimensions_size(ph, [0]), (1,)) self.assertTupleEqual(get_dimensions_size(ph, [1]), (2,)) self.assertTupleEqual(get_dimensions_size(ph, [2]), (3,)) self.assertTupleEqual(get_dimensions_size(ph, [2, 0, 1]), (3, 1, 2)) # test dynamic shape, but no dynamic axis is queried ph = tf.placeholder(tf.float32, (1, None, 3)) self.assertTupleEqual(get_dimensions_size(ph, [0]), (1,)) self.assertTupleEqual(get_dimensions_size(ph, [2]), (3,)) self.assertTupleEqual(get_dimensions_size(ph, [2, 0]), (3, 1)) # test dynamic shape def _assert_equal(a, b): ph_in = np.arange(6, dtype=np.float32).reshape((1, 2, 3)) self.assertIsInstance(a, tf.Tensor) np.testing.assert_equal(sess.run(a, feed_dict={ph: ph_in}), b) ph = tf.placeholder(tf.float32, (1, None, 3)) _assert_equal(get_dimensions_size(ph), (1, 2, 3)) _assert_equal(get_dimensions_size(ph, [1]), (2,)) _assert_equal(get_dimensions_size(ph, [2, 0, 1]), (3, 1, 2)) # test fully dynamic shape ph = tf.placeholder(tf.float32, None) _assert_equal(get_dimensions_size(ph), (1, 2, 3)) _assert_equal(get_dimensions_size(ph, [0]), (1,)) _assert_equal(get_dimensions_size(ph, [1]), (2,)) _assert_equal(get_dimensions_size(ph, [2]), (3,)) _assert_equal(get_dimensions_size(ph, [2, 0, 1]), (3, 1, 2)) def test_get_shape(self): with self.test_session() as sess: # test static shape ph = tf.placeholder(tf.float32, (1, 2, 3)) self.assertTupleEqual(get_shape(ph), (1, 2, 3)) # test dynamic shape def _assert_equal(a, b): ph_in = np.arange(6, dtype=np.float32).reshape((1, 2, 3)) self.assertIsInstance(a, tf.Tensor) np.testing.assert_equal(sess.run(a, feed_dict={ph: ph_in}), b) ph = tf.placeholder(tf.float32, (1, None, 3)) _assert_equal(get_shape(ph), (1, 2, 3)) # test fully dynamic shape ph = tf.placeholder(tf.float32, None) _assert_equal(get_shape(ph), (1, 2, 3)) class ConcatShapesTestCase(tf.test.TestCase): def test_concat_shapes(self): with self.test_session() as sess: # test empty self.assertTupleEqual(concat_shapes(()), ()) # test static shapes self.assertTupleEqual( concat_shapes(iter([ (1, 2), (3,), (), (4, 5) ])), (1, 2, 3, 4, 5) ) # test having dynamic shape shape = concat_shapes([ (1, 2), tf.constant([3], dtype=tf.int32), (), tf.constant([4, 5], dtype=tf.int32), ]) self.assertIsInstance(shape, tf.Tensor) np.testing.assert_equal(sess.run(shape), (1, 2, 3, 4, 5)) class IsShapeEqualTestCase(tf.test.TestCase): def test_is_shape_equal(self): def check(x, y, x_ph=None, y_ph=None): ans = x.shape == y.shape feed_dict = {} if x_ph is not None: feed_dict[x_ph] = x x = x_ph if y_ph is not None: feed_dict[y_ph] = y y = y_ph result = is_shape_equal(x, y) if is_tensor_object(result): result = sess.run(result, feed_dict=feed_dict) self.assertEqual(result, ans) with self.test_session() as sess: # check static shapes x1 = np.random.normal(size=[2, 3, 4]) x2 = np.random.normal(size=[2, 1, 4]) x3 = np.random.normal(size=[1, 2, 3, 4]) check(x1, np.copy(x1)) check(x1, x2) check(x1, x3) # check partial dynamic shapes x1_ph = tf.placeholder(dtype=tf.float32, shape=[2, None, 4]) x2_ph = tf.placeholder(dtype=tf.float32, shape=[2, None, 4]) x3_ph = tf.placeholder(dtype=tf.float32, shape=[None] * 4) check(x1, np.copy(x1), x1_ph, x2_ph) check(x1, x2, x1_ph, x2_ph) check(x1, x3, x1_ph, x3_ph) # check fully dimension shapes x1_ph = tf.placeholder(dtype=tf.float32, shape=None) x2_ph = tf.placeholder(dtype=tf.float32, shape=None) x3_ph = tf.placeholder(dtype=tf.float32, shape=None) check(x1, np.copy(x1), x1_ph, x2_ph) check(x1, x2, x1_ph, x2_ph) check(x1, x3, x1_ph, x3_ph)
39.056738
80
0.539041
392e70fcb3cbed6fd7e437f61128433bc5549e60
373
py
Python
setup.py
ngeraci/ucr_archivestools
2eab4caa26075521ef0bf7adbcc1c83af34865fe
[ "BSD-3-Clause" ]
null
null
null
setup.py
ngeraci/ucr_archivestools
2eab4caa26075521ef0bf7adbcc1c83af34865fe
[ "BSD-3-Clause" ]
15
2018-04-24T19:48:03.000Z
2021-12-13T19:47:39.000Z
setup.py
ngeraci/ucr_archivestools
2eab4caa26075521ef0bf7adbcc1c83af34865fe
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='aspace_tools', version="0.3", packages=find_packages(), include_package_data=True, install_requires=[ 'requests', 'lxml', 'iso-639' ], entry_points={ 'console_scripts': [ 'oac-process = aspace_tools.oac_process:main', ] } )
21.941176
58
0.592493
cd2e9bc773dbe863a5a573751f7f1e29b2810fc9
1,100
cs
C#
src/SharpNeat.Tasks/FunctionRegression/IBlackBoxProbe.cs
subski/sharpneat-refactor
5022b82b7ebdadb64dc9fc34bdc05746fb31f235
[ "MIT" ]
58
2017-12-24T19:33:57.000Z
2022-03-12T18:31:17.000Z
src/SharpNeat.Tasks/FunctionRegression/IBlackBoxProbe.cs
subski/sharpneat-refactor
5022b82b7ebdadb64dc9fc34bdc05746fb31f235
[ "MIT" ]
25
2017-12-28T20:35:18.000Z
2022-02-06T20:55:02.000Z
src/SharpNeat.Tasks/FunctionRegression/IBlackBoxProbe.cs
subski/sharpneat-refactor
5022b82b7ebdadb64dc9fc34bdc05746fb31f235
[ "MIT" ]
15
2018-08-03T20:56:20.000Z
2022-01-27T08:37:00.000Z
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2020 Colin Green ([email protected]) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using SharpNeat.BlackBox; namespace SharpNeat.Tasks.FunctionRegression { /// <summary> /// For probing and recording the responses of instances of <see cref="IBlackBox{T}"/>. /// </summary> public interface IBlackBoxProbe { // TODO: Convert responseArr to Span<double> /// <summary> /// Probe the given black box, and record the responses in <paramref name="responseArr"/>. /// </summary> /// <param name="box">The black box to probe.</param> /// <param name="responseArr">Response array.</param> void Probe(IBlackBox<double> box, double[] responseArr); } }
36.666667
98
0.617273
a00e9fe733bc2eb8cc87f9a063ed5e3ff69948c8
4,846
ts
TypeScript
src/Symbols.ts
TeamDev-it/Esri-vue-maps
20bce97a203f486f124e70911b1bac80cccda6ac
[ "MIT" ]
null
null
null
src/Symbols.ts
TeamDev-it/Esri-vue-maps
20bce97a203f486f124e70911b1bac80cccda6ac
[ "MIT" ]
null
null
null
src/Symbols.ts
TeamDev-it/Esri-vue-maps
20bce97a203f486f124e70911b1bac80cccda6ac
[ "MIT" ]
null
null
null
import { Loader, CreationResult } from "./esriUtils" export class Symbols { public async ExtrudeSymbol3DLayer(options?: any): Promise<__esri.ExtrudeSymbol3DLayer> { return (await Loader.create<__esri.ExtrudeSymbol3DLayer>(Loader.packageName + "/symbols/ExtrudeSymbol3DLayer", options)).result; } public async FillSymbol(options?: any): Promise<__esri.FillSymbol> { return (await Loader.create<__esri.FillSymbol>(Loader.packageName + "/symbols/FillSymbol", options)).result; } public async FillSymbol3DLayer(options?: any): Promise<__esri.FillSymbol3DLayer> { return (await Loader.create<__esri.FillSymbol3DLayer>(Loader.packageName + "/symbols/FillSymbol3DLayer", options)).result; } public async Font(options?: any): Promise<__esri.Font> { return (await Loader.create<__esri.Font>(Loader.packageName + "/symbols/Font", options)).result; } public async IconSymbol3DLayer(options?: any): Promise<__esri.IconSymbol3DLayer> { return (await Loader.create<__esri.IconSymbol3DLayer>(Loader.packageName + "/symbols/IconSymbol3DLayer", options)).result; } public async LabelSymbol3D(options?: any): Promise<__esri.LabelSymbol3D> { return (await Loader.create<__esri.LabelSymbol3D>(Loader.packageName + "/symbols/LabelSymbol3D", options)).result; } public async LineSymbol(options?: any): Promise<__esri.LineSymbol> { return (await Loader.create<__esri.LineSymbol>(Loader.packageName + "/symbols/LineSymbol", options)).result; } public async LineSymbol3D(options?: any): Promise<__esri.LineSymbol3D> { return (await Loader.create<__esri.LineSymbol3D>(Loader.packageName + "/symbols/LineSymbol3D", options)).result; } public async LineSymbol3DLayer(options?: any): Promise<__esri.LineSymbol3DLayer> { return (await Loader.create<__esri.LineSymbol3DLayer>(Loader.packageName + "/symbols/LineSymbol3DLayer", options)).result; } public async MarkerSymbol(options?: any): Promise<__esri.MarkerSymbol> { return (await Loader.create<__esri.MarkerSymbol>(Loader.packageName + "/symbols/MarkerSymbol", options)).result; } public async MeshSymbol3D(options?: any): Promise<__esri.MeshSymbol3D> { return (await Loader.create<__esri.MeshSymbol3D>(Loader.packageName + "/symbols/MeshSymbol3D", options)).result; } public async ObjectSymbol3DLayer(options?: any): Promise<__esri.ObjectSymbol3DLayer> { return (await Loader.create<__esri.ObjectSymbol3DLayer>(Loader.packageName + "/symbols/ObjectSymbol3DLayer", options)).result; } public async PathSymbol3DLayer(options?: any): Promise<__esri.PathSymbol3DLayer> { return (await Loader.create<__esri.PathSymbol3DLayer>(Loader.packageName + "/symbols/PathSymbol3DLayer", options)).result; } public async PictureFillSymbol(options?: any): Promise<__esri.PictureFillSymbol> { return (await Loader.create<__esri.PictureFillSymbol>(Loader.packageName + "/symbols/PictureFillSymbol", options)).result; } public async PictureMarkerSymbol(options?: any): Promise<__esri.PictureMarkerSymbol> { return (await Loader.create<__esri.PictureMarkerSymbol>(Loader.packageName + "/symbols/PictureMarkerSymbol", options)).result; } public async PointSymbol3D(options?: any): Promise<__esri.PointSymbol3D> { return (await Loader.create<__esri.PointSymbol3D>(Loader.packageName + "/symbols/PointSymbol3D", options)).result; } public async PolygonSymbol3D(options?: any): Promise<__esri.PolygonSymbol3D> { return (await Loader.create<__esri.PolygonSymbol3D>(Loader.packageName + "/symbols/PolygonSymbol3D", options)).result; } public async SimpleFillSymbol(options?: any): Promise<__esri.SimpleFillSymbol> { return (await Loader.create<__esri.SimpleFillSymbol>(Loader.packageName + "/symbols/SimpleFillSymbol", options)).result; } public async SimpleLineSymbol(options?: any): Promise<__esri.SimpleLineSymbol> { return (await Loader.create<__esri.SimpleLineSymbol>(Loader.packageName + "/symbols/SimpleLineSymbol", options)).result; } public async SimpleMarkerSymbol(options?: any): Promise<__esri.SimpleMarkerSymbol> { return (await Loader.create<__esri.SimpleMarkerSymbol>(Loader.packageName + "/symbols/SimpleMarkerSymbol", options)).result; } public async TextSymbol(options?: any): Promise<__esri.TextSymbol> { return (await Loader.create<__esri.TextSymbol>(Loader.packageName + "/symbols/TextSymbol", options)).result; } public async TextSymbol3DLayer(options?: any): Promise<__esri.TextSymbol3DLayer> { return (await Loader.create<__esri.TextSymbol3DLayer>(Loader.packageName + "/symbols/TextSymbol3DLayer", options)).result; } public async WebStyleSymbol(options?: any): Promise<__esri.WebStyleSymbol> { return (await Loader.create<__esri.WebStyleSymbol>(Loader.packageName + "/symbols/WebStyleSymbol", options)).result; } }
49.958763
132
0.762897
2d6d749b3938941fe50ed982b412fb4c3b9da69c
3,823
css
CSS
css/resume.css
maoning/maoning.github.io
06401949a23f6906a9f87017c617111fda7b468c
[ "MIT" ]
null
null
null
css/resume.css
maoning/maoning.github.io
06401949a23f6906a9f87017c617111fda7b468c
[ "MIT" ]
null
null
null
css/resume.css
maoning/maoning.github.io
06401949a23f6906a9f87017c617111fda7b468c
[ "MIT" ]
null
null
null
/*header { height:150px; border-radius: 10px; background-color:#3F3F3F; color:white; text-align:center; line-height: 35px; padding-top: 20px; border-style: solid; border-width: 1px; } body { text-align: center; } #wrapper { width:800px; height: auto; margin:0 auto; position:relative } #container { width:100%; float:left; padding:10px; } nav { position: fixed; top: 210px; line-height:30px; background-color:white; border-style: solid; border-width: 1px; height:180px; width:80px; padding:20px; font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: left; font-size: 13px; } section { width:460px; height: auto; float:left; margin-left: 140px; left: 150px; padding-top: 15px; padding-left:20px; padding-right: 15px; text-align: left; border-style: solid; border-width: 1px; border-color: lightgray; } aside { margin-top: 20px; height:130px; width:100px; float:right; margin-right: 20px; padding:10px; background-color:white; border-style: solid; border-width: 1px; font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: left; word-wrap: break-word; } footer { border-radius: 10px; background-color:#3F3F3F; color:white; clear:both; text-align:center; padding:5px; border-style: solid; border-width: 1px; font-family: 'Abel', sans-serif; font-weight: 500; } header h1 { font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: center; font-size: 25px; } header p { padding: 20px; font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: right; font-size: 15px; } section h2 { font-family: 'Open Sans', sans-serif, Helvetica, Arial; font-style: normal; font-weight: 400; color: #0E3968; src: local('Open Sans'), local('OpenSans'), url('http://themes.googleusercontent.com/static/fonts/opensans/v5/cJZKeOuBrn4kERxqtaUH3T8E0i7KZn-EPnyo3HZu7kw.woff') format('woff'); } section h3 { color: black; font-size: 15px; font-weight: bold; font-family: 'Abel', sans-serif; } section p { color: black; font-size: 15px; font-weight: 100; font-family: 'Abel', sans-serif; } aside p { font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: left; font-size: 13px; } aside h2 { font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: left; font-size: 13px; } aside a { font-family: 'Yanone Kaffeesatz', sans-serif; font-weight: 100; text-align: left; font-size: 13px; } section li { color: black; font-size: 15px; font-weight: 100; font-family: 'Abel', sans-serif; padding: 10px 20px; }*/ /* unvisited link */ /*a:link { color: #000000; }*/ /* visited link */ /*a:visited { color: #000000; }*/ /* mouse over link */ /*a:hover { color: #003399; }*/ /***********Hover Text Box*************/ .courses { color: #900; text-decoration: none; color: black; font-size: 15px; font-weight: 100; font-family: 'Abel', sans-serif;} .courses:hover { color: red; position: relative; font-size: 15px; } .courses[data-title]:hover:after { content: attr(data-title); padding: 4px 8px; color: #333; position: absolute; left: 100px; top: 100%; z-index: 20; width: 400px; white-space: pre-wrap; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; background-color: lightgray; color: black; font-size: 15px; font-weight: 100; font-family: 'Abel', sans-serif; } .courses.notCompleted { color: lightgray; font-size: 15px; font-weight: 100; font-family: 'Abel', sans-serif; }
17.864486
179
0.630395
548d0b621ebfc016f29d6f153be64937a7dd5ae3
1,712
dart
Dart
lib/c/clipOvalSample.dart
Seek-knowledge/flutter_widget_sample
914c21084aeef9ba8e6ace20c0857742c6902092
[ "MIT" ]
1
2018-09-11T08:10:21.000Z
2018-09-11T08:10:21.000Z
lib/c/clipOvalSample.dart
Seek-knowledge/flutter_widget_sample
914c21084aeef9ba8e6ace20c0857742c6902092
[ "MIT" ]
null
null
null
lib/c/clipOvalSample.dart
Seek-knowledge/flutter_widget_sample
914c21084aeef9ba8e6ace20c0857742c6902092
[ "MIT" ]
null
null
null
import 'package:flutter_ui_demo/base.dart'; import 'package:flutter/material.dart'; // ignore: must_be_immutable class ClipOvalSample extends BaseContentApp { static const String routeName = 'ClipOvalSample'; @override String get title => routeName; @override Widget get contentWidget => _Sample(); @override String get desc => ''' 一个 widget,用来裁剪子widget,让其成为一个椭圆、圆形的 widget,超出这个范围会被裁剪掉不显示。 '''; @override String get sampleCode => ''' ClipOval( clipper: _ImageClipper(), child: Image.asset('images/img.jpeg'), ), class _ImageClipper extends CustomClipper<Rect> { @override Rect getClip(Size size) { return Rect.fromLTWH(0.0, size.height / 4, size.width, size.height / 4 * 3); } @override bool shouldReclip(CustomClipper<Rect> oldClipper) { return true; } } '''; } class _Sample extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Column( children: <Widget>[ Text('默认是裁剪成圆形,如下所示'), SizedBox(height: 10.0), ClipOval( child: Image.asset('images/img.jpeg'), ), SizedBox(height: 30.0,), Text('可以传入一个矩形区域,这样在裁剪的时候就可以变成一个椭圆,如下所示'), SizedBox(height: 10.0,), ClipOval( clipper: _ImageClipper(), child: Image.asset('images/img.jpeg'), ), ], ), ); } } class _ImageClipper extends CustomClipper<Rect> { @override Rect getClip(Size size) { return Rect.fromLTWH(0.0, size.height / 4, size.width, size.height / 4 * 3); } @override bool shouldReclip(CustomClipper<Rect> oldClipper) { return true; } }
21.948718
82
0.619159
e24677f5976f533999736de7a1122ffd5751af04
4,391
js
JavaScript
docs/build/assets/js/5b560578.0a1ff630.js
SiddeshSambasivam/DataAnnotated
7b1563334ad3283bffd1081a05aa3df6a5c906c6
[ "MIT" ]
6
2021-02-26T02:19:17.000Z
2021-03-01T05:01:36.000Z
docs/build/assets/js/5b560578.0a1ff630.js
SiddeshSambasivam/DataAnnotated
7b1563334ad3283bffd1081a05aa3df6a5c906c6
[ "MIT" ]
10
2021-02-26T07:33:41.000Z
2021-04-26T18:25:49.000Z
docs/build/assets/js/5b560578.0a1ff630.js
SiddeshSambasivam/DataAnnotated
7b1563334ad3283bffd1081a05aa3df6a5c906c6
[ "MIT" ]
2
2021-02-25T23:16:09.000Z
2021-04-13T15:59:40.000Z
(window.webpackJsonp=window.webpackJsonp||[]).push([[13],{107:function(e,t,n){"use strict";n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return m}));var r=n(0),a=n.n(r);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n,r,a={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var s=a.a.createContext({}),p=function(e){var t=a.a.useContext(s),n=t;return e&&(n="function"==typeof e?e(t):c(c({},t),e)),n},l=function(e){var t=p(e.components);return a.a.createElement(s.Provider,{value:t},e.children)},b={inlineCode:"code",wrapper:function(e){var t=e.children;return a.a.createElement(a.a.Fragment,{},t)}},f=a.a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,o=e.originalType,u=e.parentName,s=i(e,["components","mdxType","originalType","parentName"]),l=p(n),f=r,m=l["".concat(u,".").concat(f)]||l[f]||b[f]||o;return n?a.a.createElement(m,c(c({ref:t},s),{},{components:n})):a.a.createElement(m,c({ref:t},s))}));function m(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var o=n.length,u=new Array(o);u[0]=f;var c={};for(var i in t)hasOwnProperty.call(t,i)&&(c[i]=t[i]);c.originalType=e,c.mdxType="string"==typeof e?e:r,u[1]=c;for(var s=2;s<o;s++)u[s]=n[s];return a.a.createElement.apply(null,u)}return a.a.createElement.apply(null,n)}f.displayName="MDXCreateElement"},84:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return u})),n.d(t,"metadata",(function(){return c})),n.d(t,"toc",(function(){return i})),n.d(t,"default",(function(){return p}));var r=n(3),a=n(7),o=(n(0),n(107)),u={title:"Thank you!"},c={unversionedId:"thank-you",id:"thank-you",isDocsHomePage:!1,title:"Thank you!",description:"Congratulations on making it this far!",source:"@site/docs/thank-you.md",slug:"/thank-you",permalink:"/docs/thank-you",editUrl:"https://github.com/facebook/docusaurus/edit/master/website/docs/thank-you.md",version:"current",sidebar:"docs",previous:{title:"Markdown Features",permalink:"/docs/markdown-features"}},i=[{value:"What&#39;s next?",id:"whats-next",children:[]}],s={toc:i};function p(e){var t=e.components,n=Object(a.a)(e,["components"]);return Object(o.b)("wrapper",Object(r.a)({},s,n,{components:t,mdxType:"MDXLayout"}),Object(o.b)("p",null,"Congratulations on making it this far!"),Object(o.b)("p",null,"You have learned the ",Object(o.b)("strong",{parentName:"p"},"basics of Docusaurus")," and made some changes to the ",Object(o.b)("strong",{parentName:"p"},"initial template"),"."),Object(o.b)("p",null,"But Docusaurus has ",Object(o.b)("strong",{parentName:"p"},"much more to offer"),"!"),Object(o.b)("h2",{id:"whats-next"},"What's next?"),Object(o.b)("ul",null,Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://v2.docusaurus.io/"},"Read the official documentation"),"."),Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://v2.docusaurus.io/docs/styling-layout"},"Design and Layout your Docusaurus site")),Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://v2.docusaurus.io/docs/search"},"Integrate a search bar into your site")),Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://v2.docusaurus.io/showcase"},"Find inspirations in Docusaurus showcase")),Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://v2.docusaurus.io/community/support"},"Get involved in the Docusaurus Community"))))}p.isMDXComponent=!0}}]);
4,391
4,391
0.692781
0321865a6af950846c389c6b7fc6a6e17ed5dd48
3,882
cpp
C++
src_train_dropout_two_hidden/test_arpa.cpp
sagae/nndep
efa7db1cfe276647bfdd71658ee5b248a51182f4
[ "MIT" ]
4
2016-10-12T13:09:49.000Z
2017-11-16T09:00:26.000Z
src_train_dropout_two_hidden/test_arpa.cpp
sagae/nndep
efa7db1cfe276647bfdd71658ee5b248a51182f4
[ "MIT" ]
null
null
null
src_train_dropout_two_hidden/test_arpa.cpp
sagae/nndep
efa7db1cfe276647bfdd71658ee5b248a51182f4
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <cstdio> //#include "cmph.hpp" //#include "biglm.hpp" //#include "quantizer.hpp" #include "arpa.hpp" #include "arpaMultinomial.h" #include <boost/algorithm/string_regex.hpp> #include <boost/program_options.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/algorithm/string/join.hpp> //using namespace std; using namespace boost; using namespace biglm; using namespace nplm; //using boost::random::mersenne_twister_engine; int main (int argc, char *argv[]) { /* using namespace boost::program_options; options_description optdes("Allowed options"); optdes.add_options() ("help,h", "display help message") ("mph-file,m", value<string>(), "Use vocabulary and perfect hash functions from file") ("mph-only", "Only generate vocabulary and perfect hash functions") ("input-file", value<string>(), "Input language model (ARPA format)") ("quantizer-file,q", value<string>(), "File containing interval means") ("output-file,o", value<string>(), "Output file (biglm format)") ("checksum-bits,k", value<int>()->default_value(8), "bits for checksum (higher is more accurate)") ("b", value<int>()->default_value(175), "b parameter to BRZ") ("graphsize", value<double>()->default_value(2.9), "graph size parameter to BRZ (>= 2.6)") ("debug,d", "debug mode"); positional_options_description poptdes; poptdes.add("input-file", 1); poptdes.add("output-file", 1); variables_map vm; store(command_line_parser(argc, argv).options(optdes).positional(poptdes).run(), vm); notify(vm); // validate combination of options int error = 0; if (vm.count("help") || error) { cout << "make_biglm <input-file> <output-file>\n\n"; cout << optdes << "\n"; return 0; } */ /* // CREATING an input file stream //ifstream in(vm["input-file"].as<string>().c_str()); string file = string("e.blanks.lm.3gram.test"); ifstream in(file.c_str()); if (in.fail()) { cerr << "couldn't open language model\n"; exit(1); } int order; arpa_reader r(in, 1); arpa_line l; vector<string> vocab; size_type vocab_size; order = r.n_orders(); int o; while ((o = r.next_order())) { cout<<"o is "<<o<<endl; if (o == 1) { cerr << "building perfect hash for vocab (" << r.n_ngrams(o) << " keys)..."; for (int i=0; i<r.n_ngrams(o); i++) { arpa_line l = r.next_ngram(); vocab.push_back(l.words[0]); cout<<"The line is "<<l.words[0]<<endl; cout<<"The prob is "<<l.prob<<" and bow is "<<l.bow<<endl; //vocab.push_back(l.words[0]); } } else { for (int i=0; i<r.n_ngrams(o); i++) { arpa_line l = r.next_ngram(); cout<<"The line is "; for (int j=0; j<l.words.size();j++) { cout<<l.words[j]<<" "; } cout<<endl; cout<<"The prob is "<<l.prob<<endl; } } } */ std::cout<<"creating the arpa sampler"<<endl; //string file = string("e.blanks.lm.3gram.test.integerized"); std::string file = std::string("e.blanks.lm.3gram.test.unk.integerized"); unsigned int count = 27; Arpa_multinomial<unsigned int> mult(count,file); //unsigned seed = std::time(0); unsigned int seed = 1234; //for testing only boost::random::mt19937 rng(seed); std::vector<unsigned int> samples = std::vector<unsigned int>(); std::vector<double> probs; std::vector<unsigned int> context = std::vector<unsigned int>(); context.push_back(20); context.push_back(19); mult.sample(rng, 100, context, samples, probs); cerr<<"we will now print the samples "<<endl; cerr<<"Size of samples is "<<samples.size()<<endl; for (int i=0; i<100; i++){ cout<<"sample "<<i<<" was "<<samples[i]<<endl; cout<<"sample "<<i<<"logprob was "<<probs[i]<<endl; } return(0); }
29.633588
102
0.622875
e5d6e980af0dc3e5196cac1d13e7a57b2f8c8f6f
87
lua
Lua
lua/harpoon/test/manage-a-mark.lua
brandoncc/harpoon
a6faacee326b90a862097962ca0affcf9a3f2a8a
[ "MIT" ]
1
2022-03-08T00:33:38.000Z
2022-03-08T00:33:38.000Z
lua/harpoon/test/manage-a-mark.lua
joacohoyos/harpoon
b0437610ab1399ba85fd605f9e2ee357a8706097
[ "MIT" ]
null
null
null
lua/harpoon/test/manage-a-mark.lua
joacohoyos/harpoon
b0437610ab1399ba85fd605f9e2ee357a8706097
[ "MIT" ]
null
null
null
-- TODO: Harpooned local Marker = require('harpoon.mark') local eq = assert.are.same
14.5
38
0.712644
bd76efc26c2a65125e5c0d4c54068ed2695e8219
1,860
rb
Ruby
app/services/qa_server/performance_per_byte_data_service.rb
LD4P/qa_server
5740f1868a6b8b895428303753d0f0739da1788d
[ "Apache-2.0" ]
5
2019-05-12T18:06:49.000Z
2022-03-01T16:47:39.000Z
app/services/qa_server/performance_per_byte_data_service.rb
LD4P/qa_server
5740f1868a6b8b895428303753d0f0739da1788d
[ "Apache-2.0" ]
243
2018-08-17T14:06:15.000Z
2022-03-31T20:01:47.000Z
app/services/qa_server/performance_per_byte_data_service.rb
LD4P/qa_server
5740f1868a6b8b895428303753d0f0739da1788d
[ "Apache-2.0" ]
5
2018-09-14T13:42:02.000Z
2022-03-01T12:43:24.000Z
# frozen_string_literal: true # This class calculates performance stats based on size of data. module QaServer class PerformancePerByteDataService class << self include QaServer::PerformanceHistoryDataKeys class_attribute :stats_calculator_class, :performance_data_class self.stats_calculator_class = QaServer::PerformancePerByteCalculatorService self.performance_data_class = QaServer::PerformanceHistory # Performance data based on size of data. # @param authority_name [String] name of an authority # @param action [Symbol] :search, :fetch, or :all_actions # @param n [Integer] calculate stats for last n records # @returns [Hash] performance statistics based on size of data # @example returns for n=2 # { data_raw_bytes_from_source: [16271, 16271], # retrieve_bytes_per_ms: [67.24433786890475, 55.51210410757532], # retrieve_ms_per_byte: [0.014871140555351083, 0.018014089288745542] # graph_load_bytes_per_ms_ms: [86.74089418722461, 54.97464153778724], # graph_load_ms_per_byte: [0.011528587632974647, 0.018190205011389522], # normalization_bytes_per_ms: [64.70169466560836, 89.25337465693322], # normalization_ms_per_byte: [0.01530700843338457, 0.015455545718983178] # } def calculate(authority_name:, action:, n: 10) records = records_by(authority_name, action) stats_calculator_class.new(records: records, n: n).calculate end private def records_by(authority_name, action) where_clause = {} where_clause[:authority] = authority_name unless authority_name.nil? || authority_name == ALL_AUTH where_clause[:action] = action unless action.nil? || action == ALL_ACTIONS performance_data_class.where(where_clause) end end end end
44.285714
106
0.714516
dc50dc757e97cb07a227d3f33b3ea773f8dfc24d
1,091
ts
TypeScript
frontend/src/app/core/models/movie.model.ts
znuznu/visum
dcbcd71cac172fbd1d78334dd28f828fa29bc34c
[ "MIT" ]
null
null
null
frontend/src/app/core/models/movie.model.ts
znuznu/visum
dcbcd71cac172fbd1d78334dd28f828fa29bc34c
[ "MIT" ]
null
null
null
frontend/src/app/core/models/movie.model.ts
znuznu/visum
dcbcd71cac172fbd1d78334dd28f828fa29bc34c
[ "MIT" ]
null
null
null
import { Actor } from './people/actor.model'; import { Director } from './people/director.model'; import { Genre } from './genre.model'; import { MovieReview } from './review/movie-review'; import { MovieViewingHistory } from './history/history.model'; export class Movie { id: number; title: string; releaseDate: string; actors: Actor[]; directors: Director[]; review: MovieReview; genres: Genre[]; isFavorite: boolean; shouldWatch: boolean; viewingHistory: MovieViewingHistory[]; creationDate: string; constructor(movie?: Partial<Movie>) { movie = movie ?? {}; this.id = movie.id ?? undefined; this.title = movie.title ?? ''; this.releaseDate = movie.releaseDate ?? ''; this.actors = movie.actors ?? []; this.directors = movie.directors ?? []; this.review = movie.review ?? undefined; this.genres = movie.genres ?? []; this.isFavorite = movie.isFavorite ?? false; this.shouldWatch = movie.shouldWatch ?? false; this.creationDate = movie.creationDate ?? null; this.viewingHistory = movie.viewingHistory ?? []; } }
31.171429
62
0.665445
383d1690972029912a2fa534732ac047177d43e6
171
php
PHP
src/App/Fields/Link.php
inwebcomp/admin
17b1be1aa351b03c77c8b3606cb4425393da8aaf
[ "BSD-2-Clause", "MIT" ]
null
null
null
src/App/Fields/Link.php
inwebcomp/admin
17b1be1aa351b03c77c8b3606cb4425393da8aaf
[ "BSD-2-Clause", "MIT" ]
15
2020-02-29T21:15:26.000Z
2022-03-01T13:38:12.000Z
src/App/Fields/Link.php
inwebcomp/admin
17b1be1aa351b03c77c8b3606cb4425393da8aaf
[ "BSD-2-Clause", "MIT" ]
null
null
null
<?php namespace InWeb\Admin\App\Fields; use Illuminate\Support\Traits\Macroable; class Link extends Field { use Macroable; public $component = 'link-field'; }
13.153846
40
0.719298
15b5698a9b8c44741d9e24989d6a469815d1e754
863
gemspec
Ruby
js_data_rails.gemspec
dts/js_data_rails
bda171682a626244b05a74f87a630fd6606426d3
[ "MIT" ]
null
null
null
js_data_rails.gemspec
dts/js_data_rails
bda171682a626244b05a74f87a630fd6606426d3
[ "MIT" ]
null
null
null
js_data_rails.gemspec
dts/js_data_rails
bda171682a626244b05a74f87a630fd6606426d3
[ "MIT" ]
null
null
null
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "js_data_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "js_data_rails" s.version = JsDataRails::VERSION s.authors = ["Daniel Staudigel"] s.email = ["[email protected]"] s.homepage = "https://github.com/dts/js_data_rails" s.summary = "JsDataRails is a simple integration between rails and JsData." s.description = "JsDataRails aims to simplify the definition of data structures so that you can generate a resource specification automatically." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.1.6" s.add_development_dependency "sqlite3" end
35.958333
147
0.687138
aa43d666ad707500f4b7c54042968dd63529e68e
1,812
lua
Lua
test/test.lua
actboy168/lml
9e20597a6df872a93589b9385038470e3343c149
[ "MIT" ]
2
2020-01-26T02:26:33.000Z
2021-11-11T00:32:13.000Z
test/test.lua
actboy168/lml
9e20597a6df872a93589b9385038470e3343c149
[ "MIT" ]
null
null
null
test/test.lua
actboy168/lml
9e20597a6df872a93589b9385038470e3343c149
[ "MIT" ]
1
2019-10-11T10:47:48.000Z
2019-10-11T10:47:48.000Z
package.path = [[.\test\?.lua]] package.cpath = [[.\build\msvc\bin\?.dll]] local lml = require 'lml' local print_r = require 'print_r' function LOAD(filename) local f = assert(io.open(filename, 'rb')) local r = lml(f:read 'a') f:close() return r end local function EQUAL(a, b) for k, v in pairs(a) do if type(v) == 'table' then EQUAL(v, b[k]) else assert(v == b[k]) end end end local n = 0 local function TEST(script, t) n = n + 1 local name = 'TEST-' .. n local r = lml(script, name) local ok, e = pcall(EQUAL, r, t) if not ok then print(script) print('--------------------------') print_r(r) print('--------------------------') print_r(t) print('--------------------------') error(name) end local ok, e = pcall(EQUAL, t, r) if not ok then print(script) print('--------------------------') print_r(r) print('--------------------------') print_r(t) print('--------------------------') error(name) end end TEST( [==[ TEST ]==] , { '', false, { 'TEST' }, } ) TEST( [==[ TEST: STATE ]==] , { '', false, { 'TEST', 'STATE' }, } ) TEST( [==[ TEST A B ]==] , { '', false, { 'TEST', false, {'A'}, {'B'}} } ) TEST( [==[ TEST: STATE A B ]==] , { '', false, { 'TEST', 'STATE', {'A'}, {'B'}} } ) TEST( [==[ TEST: STATE A: STATE_A B: STATE_B ]==] , { '', false, { 'TEST', 'STATE', {'A', 'STATE_A'}, {'B', 'STATE_B'}} } ) TEST( [==[ TEST: STATE A: STATE_A A1 A2 B: STATE_B B1 B2 ]==] , { '', false, { 'TEST', 'STATE', {'A', 'STATE_A', {'A1'}, {'A2'}}, {'B', 'STATE_B', {'B1'}, {'B2'}}} } ) TEST( [==[ 'TE:ST': '''A000''' ]==] , { '', false, { 'TE:ST', "'A000'"} } ) TEST( [==[ TEST A '多行字符串 1': '多行字符串 2' B ]==] , { '', false, { 'TEST', false, {'A', false, {'多行字符串\n1', '多行字符串\n2', {'B'}}}} } ) print('test ok!')
11.468354
86
0.450883